As programmers we rarely have a luxury to write a project from scratch. Usually we have
to retrofit existing projects with all cool things we need. If a new component, or a library
we want to use introduces new concepts that bleed outside its boundary, we have a “culture clash”,
when old code is unaware about new concepts have to work with it anyhow. Sometimes the clash is so bad
that we have to give up on using shiny new things, or have to significantly rework their code,
which requires time and efforts we cannot afford.
Incomplete objects allow us to concentrate on important properties of JavaScript objects
ignoring the rest: we don’t need to specify every single property, and we can deal with
cyclical graphs.
Incomplete arrays is a complimentary feature to inspect only the first few array items.
Both features are very useful for patterns, and heya-unify
provides rich facilities to automate
creating incomplete objects: they can be marked up explicitly on per-instance basis, recursively
with a special utility, and we can specify how to deal with objects by default during unification.
Custom unification in heya-unify
allows us to deal with our specific objects in JavaScript,
create unification helpers, and even custom logical conditions. It is there to bridge unification
with our existing projects.
Looking at the 1st part
and
the 2nd part
of the series is recommended before diving into details.
Custom unification
Unification makes comparing simple objects a cinch no matter how complex they are, and we can easily apply it
to JSON-like trees as is. Additionally heya-unify
“knows” how to unify other common JavaScript objects:
dates, and regular expressions. Yet in Real Life™ we are faced with complications like that:
Finally: my open source JavaScript project DCL
is built on ideas described in this article. Available for node.js and modern browsers, it implements OOP with mixins and AOP at "class" and object level. Read documentation and background articles on www.dcljs.org
, clone its code on github.com/uhop/dcl
, and follow @dcl_js
.
Almost any Java programmer, who starts to study JS groking its OOP facilities and a dynamic nature of JS, thinks that they can be greatly improved and starts its own OOP library/helpers. Majority of them left forgotten when their authors learn more and more details and patterns of JS, yet some grow to fruition and being marketed. This article is dedicated to such people.
Many years ago I decided to replace plain text areas in Django’s Admin with rich text editor, so I can edit HTML on my blog using WYSIWYG. Six (yes, 6) years ago I looked around and selected
TinyMCE
. Over time it turned out that I was forced to upgrade TinyMCE and the link script I had because new browsers continue breaking my rich editor editing. Finally it stopped working again in all modern browsers, and I decided that enough is enough. It is time to replace it. This time I settled on Dojo’s Rich Editor
hosted on Google CDN
— simple, functional, less work to set up.
Explaining some dark corners of JavaScript, browsers, or Dojo for the 100th time I realized that I already did it on numerous occasions, and some of my answers are published on public web sites. So I decided to round up the most general ones I posted on StackOverflow
and publish links to them here for a future reference.
JavaScript
This section is for language-specific topics. They can be equally applied in any environment.
In the previous post
we explored “array extras” and how they can help us to write concise yet performant and clean code. In this post we take a look at generalizing recursive algorithms with recursion combinators — high-level functions that encapsulate all boilerplate code needed to set up the recursion. These functions were added to dojox.lang.functional and will be officially released with Dojo 1.2.
In general the recursion is a form of iterative problem solving in the same category as loops. There are two major natural sources of recursive algorithms: recursive data
structures (lists, trees, and so on), and recursive definitions
(factorial, Fibonacci numbers, the GCD algorithm, etc.). The
recursion plays a prominent role in the functional programming (FP),
and one of the best articles on this topic is “Recursion Theory and Joy”
by Manfred von Thun
, the creator of Joy
(a purely functional
programming language with Forth-like syntax). Manfred’s article
explains intricacies of recursion including the venerable Y
combinator
, recursion combinators in general, and introduces a practical set of recursion combinators, which will guide us in this post.
Finally: my open source JavaScript project DCL
is built on ideas described in this article. Available for node.js and modern browsers, it implements OOP with mixins and AOP at "class" and object level. Read documentation and background articles on www.dcljs.org
, clone its code on github.com/uhop/dcl
, and follow @dcl_js
.
If we look at the history of computer programming languages, we can see that practically all new programming methodologies were about one thing: taming complexity. The anarchy of earlier days of procedural programming
(example: Fortran) gave way to structured programming
(Pascal), which was refined with modular programming
(Modula), and was reformulated when object-oriented programing
went mainstream (C++, and much later Java). And it stopped there. The focus shifted to different branches of computer programming, namely to functional programming, and, to a lesser degree, logical programming. The only major development in this branch was the rise of aspect-oriented programming
(AOP) paradigm. Let’s take a look at AOP in our favorite language: JavaScript, and how Dojo helps the language with dojox.lang.aspect package.
Everybody knows that JavaScript is a multi-paradigm language, and it can be used to program functionally. Practically all functional idioms can be used directly: higher-order functions, recursion, closures, and so on. The recent resurgence of Functional Programming (FP) brings functional methodologies in the mainstream. FP fundamentals gave us a lot of powerful idioms: iterative functions, which can replace loops, list processing in general, function manipulations, and many other things, which helps us to keep our code small yet concise, more powerful, and more fun. Let’s take a look at how Dojo helps to leverage the functional paradigm in the Core, and in the extended DojoX package (dojox.lang.functional).
Update 9/30/2006: when you finish this article don’t forget to read more about setting up tools in the second part: Setting up tools 2
.
My goal is to set up working environment for Django
development on Windows box. You can find a lot of information on setting up open-source development tools on Linux. Somehow it is assumed that your project should target LAMP (Linux, Apache, MySQL, Python). Windows-bound guys are advised to decorate their platform as ersatz Linux: install Apache, install MySQL, and you have WAMP (Windows, Apache, MySQL, Python). What kind of fun is that? No, we are going full WIMP (Windows, IIS, MS SQL, Python)!
Update on 11/25/2007: today this article presents mostly historical interest. Since Dojo 0.2 a lot of versions were published and many things were changed. At the time of this writing Dojo is at ripe 1.0. I had to disable all Ajax action in examples because I don’t use Dojo 0.2 anymore.
What is Filtering? It is a selection of items using some criteria (filter). In this tutorial I am going to filter documents of my blog (made with Django
, of course) matching titles against user-specified substring. Later on I’ll talk about generalization of this approach.
Update: "The Simple Way" part of this tutorial is obsolete
now. I am going to recreate examples using new improved RSS framework. Stay tuned!
I was asked several times to explain how I did RSS for my site. Django has RSS framework, which is not documented. Most probably I am not the right guy to explain it but I’ll try.
There are three ways to implement RSS with Django:
- The Simple: using Django’s RSS framework.
- The Smart: using django.utils.feedgenerator.
- The Hard: write a view and output XML manually or using standard xml.sax.saxutils.
If you want Django to do everything for you, then you should use "The Simple Way". If you want some custom object selection, you should use "The Smart Way". For obsessed workaholics, S&M adepts, and guys-with-really-convoluted-needs the only way is "The Hard Way". Being lazy I prefer #1 and #2. If you want #3, I suggest you to study files mentioned in "The Simple Way" subsection below.
The Simple Way
If you look into Django’s code, you will find several files related to RSS:
After some requests I decided to publish my code for categories. It’s very simple. It was inspired by following articles: A "category" Data Model
(note: this article uses old-style model format, it doesn’t work anymore) and Relating an object to itself, many-to-one
.
from django.core import meta
class Category(meta.Model):
"""
Category defines following fields:
name - simple name of category, e.g., 'C++'
full_name - full name of category, which includes names of all parents,
e.g. 'Development::C++'
parent - reference to parent category or null
description - HTML description of category, or null
Notes:
1) full_name is not editable. It is calculated automatically
by calculate_full_name() method during save phase (hook _pre_save).
2) Separator specified by get_separator() method. It can be
overridden in subclasses.
"""
name = meta.CharField(maxlength=50)
full_name = meta.CharField(maxlength=250, unique=True,
editable=False)
parent = meta.ForeignKey('self', blank=True, null=True,
related_name='child')
description = meta.TextField(blank=True, null=True,
help_text="Use raw HTML.")
class META:
verbose_name_plural = 'Categories'
module_name = verbose_name_plural.lower()
admin = meta.Admin(
list_display = ('full_name',),
search_fields = ['full_name',],
js = (
'/tiny_mce/tiny_mce.js',
'/appmedia/admin/js/textareas.js',
),
)
ordering = ('full_name',)
def __repr__(self):
return self.full_name
def _pre_save(self):
self.full_name = self.calculate_full_name()
def get_separator(self):
return '::'
# note: used in templates
def get_all_children(self):
"get list of all children of the category"
output = []
children = self.get_child_list()
for c in children:
output.append(c)
output.extend(c.get_all_children())
return output
# note: the last object of the list is the category itself
# note: used in templates
def get_all_parents(self):
"get list of all parents of the category from top level parent down"
id_list = []
object = self
while True:
id_list.append(object)
if not object.parent_id:
break
object = object.get_parent()
id_list.reverse()
return id_list
# note: used in templates
def calculate_full_name(self):
"calculate full name from parent list"
return self.get_separator().join([x.name for x in self.get_all_parents()])
# note: used in templates
def get_path(self):
"get relative path of the category"
return 'categories/%d/' % self.id
As you can see it is very simple. This model defines full_name field, which is auto-populated. I was toying with an idea to keep parent_name and produce full_name by concatenating parent_name with name. But after some trials I decided against it: it introduced a lot of complexities and runtime overhead by saving a few bytes in database. In my opinion it doesn’t worth it. This model defines some convenience methods as well. They are meant to be used in templates.