Pages

Thursday, September 15, 2011

Template Language Terms in Django

Let’s quickly review some Django Template Language terms
  • A template is a text document, or a normal Python string, that is marked up using the Django template language. A template can contain block tags and variables.

  • A block tag is a symbol within a template that does something. This definition is deliberately vague. For example, a block tag can produce content, serve as a control structure (an if statement or for loop), grab content from a database, or enable access to other template tags.
    Block tags are surrounded by {% and %}:
    {% if is_logged_in %}
    Thanks for logging in!
    {% else %}
    Please log in.
    {% endif %}
  • A variable is a symbol within a template that outputs a value.
    Variable tags are surrounded by {{ and }}:
    My first name is {{ first_name }}. My last name is {{ last_name }}.
  • A context is a name -> value mapping (similar to a Python dictionary) that is passed to a template.
  • A template renders a context by replacing the variable “holes” with values from the context and executing all block tags.

Tuesday, August 9, 2011

Convert Windows-1251 (Cyrillic) to Unicode using Python

Just 4 lines of code to convert some file content from Windows-1251 (Cyrillic) to Unicode with Python

import codecs

f = codecs.open(filename, 'r', 'cp1251')
u = f.read()   # now the contents have been transformed to a Unicode string
out = codecs.open(output, 'w', 'utf-8')
out.write(u)   # and now the contents have been output as UTF-8
 

The multi valued string regex pattern

Let’s write a regular expression to identify user inputs in the form of two values, separated by either comma or space, such as:   12.6, 3  or  12.6    3 

The condition being this value must be single or integer; spaces should be handled; no need to check empty spaces at the start of end of the string; "12.6" or "12.6," are both not accepted.

This should work (code by les patter)

string pattern = @"\d+(\.\d)?(\s|\,)\s*\d+(\.\d)?";
string[] tests = {
"12.6, 3",
"12.6 3",
"12.6",
"12.6,",
", 3",
" 4",
"1, 2.3",
"123, 456",
};
foreach (string test in tests)
Console.WriteLine("{0}: {1}", Regex.IsMatch(test, pattern), test);
}