Wednesday, December 12, 2007

Tuesday, December 11, 2007

Adding classes/style to django form elements

The 'attrs' argument to the Widget class used with each particular
Field (the Widget is what actually renders the HTML) accepts a
dictionary which will become HTML attribute names and values. For
example:

username = forms.CharField(widget=forms.TextInput(attrs={'class': 'myclass'}))

will become:



the old forms default of having class attributes for each
input type (e.g. class=vTextField for type=text)

Sunday, December 09, 2007

populating select box from database ror

controller code looks something like:

class testController < ApplicationController

def test
@categories= Category.find_all
end

end

use
<%= options_from_collection_for_select @categories, 'id', 'name' %>
to populate the select box


Saturday, December 08, 2007

Django Forms

Start with this basic Form subclass, which we’ll call ContactForm:

from django import newforms as forms

class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)

A form is composed of Field objects.

Creating Form instances

A Form instance is either bound to a set of data, or unbound.

* If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
* If it’s unbound, it cannot do validation but it can still render the blank form as HTML.

To create an unbound Form instance, simply instantiate the class:

>>> f = ContactForm()

To bind data to a form, pass the data as a dictionary as the first parameter to your Form class constructor:

>>> data = {'subject': 'hello',
... 'message': 'Hi there',
... 'sender': 'foo@example.com',
... 'cc_myself': True}
>>> f = ContactForm(data)

In this dictionary, the keys are the field names, which correspond to the attributes in your Form class. The values are the data you’re trying to validate. These will usually be strings, but there’s no requirement that they be strings; the type of data you pass depends on the Field, as we’ll see in a moment.

If you need to distinguish between bound and unbound form instances at runtime, check the value of the form’s is_bound attribute:

>>> f = ContactForm()
>>> f.is_bound
False
>>> f = ContactForm({'subject': 'hello'})
>>> f.is_bound
True

Note that passing an empty dictionary creates a bound form with empty data:

>>> f = ContactForm({})
>>> f.is_bound
True

If you have a bound Form instance and want to change the data somehow, or if you want to bind an unbound Form instance to some data, create another Form instance. There is no way to change data in a Form instance. Once a Form instance has been created, you should consider its data immutable, whether it has data or not.


1) The primary task of a Form object is to validate data. With a bound Form instance, call the is_valid() method to run validation and return a boolean designating whether the data was valid:
2) Each Field in a Form class is responsible not only for validating data, but also for “cleaning” it — normalizing it to a consistent format.

f.errors
In this dictionary, the keys are the field names, and the values are lists of Unicode strings representing the error messages. The error messages are stored in lists because a field can have multiple error messages.

f.cleaned_data
If your data does not validate, your Form instance will not have a cleaned_data attribute:

cleaned_data will always only contain a key for fields defined in the Form, even if you pass extra data when you define the Form. In this example, we pass a bunch of extra fields to the ContactForm constructor, but cleaned_data contains only the form’s fields:

print f

You can access errors without having to call is_valid() first. The form’s data will be validated the first time either you call is_valid() or access errors.

The validation routines will only get called once, regardless of how many times you access errors or call is_valid()

Each field type has a default HTML representation. CharField and EmailField are represented by an . BooleanField is represented by an . Note these are merely sensible defaults; you can specify which HTML to use for a given field by using widgets

Use the auto_id argument to the Form constructor to control the label and id behavior. This argument must be True, False or a string.
If auto_id is False, then the form output will not include

Saturday, November 24, 2007

render_to_response()

render_to_response()

Because it’s such a common idiom to load a template, fill a Context and return an HttpResponse object with the result of the
rendered template, Django provides a shortcut that lets you do those things in one line of code. This shortcut is a function
called render_to_response(), which lives in the module django.shortcuts. Most of the time, you’ll be using render_to_response() rather than loading templates and creating Context and HttpResponse objects manually.

Here’s the ongoing current_datetime example rewritten to use render_to_response():

from django.shortcuts import render_to_response
import datetime
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})

What a difference! Let’s step through the code changes:
l We no longer have to import get_template, Template, Context or HttpResponse. Instead, we
import django.shortcuts.render_to_response. The import datetime remains.
l Within the current_datetime function, we still calculate now, but the template loading, context creation, template rendering
and HttpResponse creation is all taken care of by the render_to_response() call. Because render_to_response() returns
an HttpResponse object, we can simply return that value in the view.
The first argument to render_to_response() should be the name of the template to use, relative to your template directory. The
second argument, if given, should be a dictionary to use in creating a Context for that template. If you don’t provide a second
argument, render_to_response() will use an empty dictionary

Friday, November 23, 2007

Django Stuff - 1

Projects vs. apps

What’s the difference between a project and an app? An app is a Web application that does something — e.g., a weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects.

Each model is a Python class that subclasses django.db.models.Model.
Each attribute of the model represents a database field.
Model metadata (non-field information) goes in an inner class named Meta.
Metadata used for Django’s admin site goes into an inner class named Admin

Executing Custon SQL
def my_custom_sql(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
return row


How Django processes a request

When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine which Python code to execute:
Django looks at the ROOT_URLCONF setting in your settings file. This should be a string representing the full Python import path to your URLconf. For example: "mydjangoapps.urls".
Django loads that Python module and looks for the variable urlpatterns. This should be a Python list, in the format returned by the function django.conf.urls.defaults.patterns().
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function. The view gets passed a request object as its first argument and any values captured in the regex as remaining arguments.

Tuesday, April 24, 2007

More Commands @ FreeBSD

Clearing the Terminal:

Clear

Adding a User:
adduser  [-u uid [-o]] [-g group] [-G group,...]
[-d home] [-s shell] [-c comment] [-m [-k template]]
[-f inactive] [-e expire mm/dd/yy] [-p passwd] [-n] [-r] name
adduser -D [-g group] [-b base] [-s shell] [-f inactive] [-e expire mm/dd/yy]

To see what groups anyone else belongs to:

Add their login name to the end of the groups command like so:
groups genisis

Add a group:
pw group add group1
To add users user1 and user2 to the group( group1):
pw groupmod group1 -M user1,user2


Thursday, April 19, 2007

Commands @ FreeBSD

Delete all contents of a directory

rm -f *

Download a file from a URL

wget URL

Delete a directory

rm -r dirname

Delete a file

rm -f filename

List Processes

ps ax

Killing a process

Kill -9 PID

Finding a file

find (where to find) -name FileName


Tuesday, April 10, 2007

Counting number of lines in a file @ python

f = open(filename)
lines = f.readlines()
f.close()

print "%s has %d lines." % (filename, len(lines))

Wednesday, March 28, 2007

copying data from one table to another @ mysql

insert into tbl (field1,field2) select field1,field2 from users

Tuesday, March 27, 2007

Loops @ Ruby

n.times {|i| puts i}

Well, the method Integer#times iterate self times (n in this) and for each iteration calls the block, gives it the current value।

something do |line|
#process something and line here
end

something' is a method and this method call the block with
some value.

For example if you want to read a file, you write

IO.foreach('file') do |line|
# do something with line
end

the method IO::foreach open the file given in argument, read each line and
call the block, given it the current line. At the end, IO::foreach close
the file



n.times {|i| puts i}

or

n.times do |i|
puts i
end


a=["hello","to","you"]
a.each {|i| puts i}

(1..10)each{|i| puts i}

or

for i in (1..10)
puts i
end



Monday, March 26, 2007

File Handling @ Python

A file object maintains state about the file it has open. The tell method of a file object tells you your current position in the open file. Since you haven't done anything with this file yet, the current position is 0, which is the beginning of the file.
The seek method of a file object moves to another position in the open file. The second parameter specifies what the first one means; 0 means move to an absolute position (counting from the start of the file), 1 means move to a relative position (counting from the current position), and 2 means move to a position relative to the end of the file. Since the MP3 tags you're looking for are stored at the end of the file, you use 2 and tell the file object to move to a position 128 bytes from the end of the file.
The tell method confirms that the current file position has moved.
The read method reads a specified number of bytes from the open file and returns a string with the data that was read। The optional parameter specifies the maximum number of bytes to read. If no parameter is specified, read will read until the end of the file. (You could have simply said read() here, since you know exactly where you are in the file and you are, in fact, reading the last 128 bytes.) The read data is assigned to the tagData variable, and the current position is updated based on how many bytes were read.

import os
def filesnsubfiles(root):
file = os.listdir(root)
for i in file:
if os.path.isdir(root + "\\" + i):
filesnsubfiles(root + "\\" + i)
else:
print (root + "\\" + i)

Monday, March 12, 2007

ActionScript

Some of the differences between ActionScript and JavaScript are as follows:

• ActionScript does not support browser-specific objects such as Document, Window,
and Anchor.
• ActionScript does not completely support all the JavaScript built-in objects.
• ActionScript does not support some JavaScript syntax constructs, such as statement labels.
• In ActionScript, the eval() action can perform only variable references

An introduction to important ActionScript terms.

Actions are statements that instruct a SWF file to do something while it is playing. For example,
gotoAndStop() sends the playhead to a specific frame or label. In this manual, the terms action
and statement are interchangeable.
Boolean is a true or false value.
Classes are data types that you can create to define a new type of object. To define a class,
you use the class keyword in an external script file (not in a script you are writing in the
Actions panel).

Constants are elements that don’t change. For example, the constant Key.TAB always has the
same meaning: it indicates the Tab key on a keyboard. Constants are useful for comparing values.
Constructors are functions that you use to define the properties and methods of a class.
By definition, constructors are functions within a class definition that have the same name
as the class. For example, the following code defines a Circle class and implements a
constructor function:
// file Circle.as
class Circle {
private var radius:Number
private var circumference:Number
// constructor
function Circle(radius:Number) {
circumference = 2 * Math.PI * radius;
}
}
The term constructor is also used when you create (instantiate) an object based on a particular
class. The following statements are constructors for the built-in Array class and the custom
Circle class:
my_array:Array = new Array();
my_circle:Circle = new Circle();

Data types describe the kind of information a variable or ActionScript element can hold. The
ActionScript data types are String, Number, Boolean, Object, MovieClip, Function, null, and
undefined.

Events are actions that occur while a SWF file is playing. For example, different events are
generated when a movie clip loads, the playhead enters a frame, the user clicks a button or movie
clip, or the user types on the keyboard

Event handlers are special actions that manage events such as mouseDown or load. There are two
kinds of ActionScript event handlers: event handler methods and event listeners. (There are also
two event handlers, on() and onClipEvent(), that you can assign directly to buttons and movie
clips.) In the Actions toolbox, each ActionScript object that has event handler methods or event
listeners has a subcategory called Events or Listeners. Some commands can be used both as event
handlers and as event listeners and are included in both subcategories

Identifiers are names used to indicate a variable, property, object, function, or method. The first
character must be a letter, underscore (_), or dollar sign ($). Each subsequent character must be a
letter, number, underscore, or dollar sign. For example, firstName is the name of a variable.

Instances are objects that belong to a certain class. Each instance of a class contains all the
properties and methods of that class. For example, all movie clips are instances of the MovieClip
class, so you can use any of the methods or properties of the MovieClip class with any movie
clip instance

Instance names are unique names that let you target movie clip and button instances in scripts.
You use the Property inspector to assign instance names to instances on the Stage. For example, a
master symbol in the library could be called counter and the two instances of that symbol in
the SWF file could have the instance names scorePlayer1_mc and scorePlayer2_mc. The
following code sets a variable called score inside each movie clip instance by using
instance names:
_root.scorePlayer1_mc.score += 1;
_root.scorePlayer2_mc.score -= 1;
You can use special suffixes when naming instances

Methods

are functions associated with a class. For example, getBytesLoaded() is a built-in
method associated with the MovieClip class. You can also create functions that act as methods,
either for objects based on built-in classes or for objects based on classes that you create

Objects are collections of properties and methods; each object has its own name and is an
instance of a particular class. Built-in objects are predefined in the ActionScript language. For
example, the built-in Date object provides information from the system clock

Packages are directories that contain one or more class files, and reside in a designated classpath
directory

Target paths are hierarchical addresses of movie clip instance names, variables, and objects in a
SWF file. You name a movie clip instance in the movie clip Property inspector. (The main
Timeline always has the name _root.) You can use a target path to direct an action at a movie clip
or to get or set the value of a variable.

Friday, February 23, 2007

Metaprogramming @ Ruby

Metaprogramming is the writing of programs that write or manipulate other programs (or themselves) as their data or that do part of the work that is otherwise done at run time during compile time. In many cases, this allows programmers to get more done in the same amount of time as they would take to write all the code manually.

The language in which the metaprogram is written is called the metalanguage. The language of the programs that are manipulated is called the object-language. The capacity of a programming language to be its own meta-language is called reflexivity.

Not all metaprogramming involves generative programming. If programs are modifiable at runtime (as in Lisp, Python, Smalltalk, Ruby, PHP, Perl, Tcl and other languages), then techniques can be used to accomplish metaprogramming without actually generating source code.

Thursday, February 22, 2007

still more rails

URL routing
An incoming URL always maps to some action within a controller. A controller is simply a Ruby class, and each action implemented by the controller is a public method within the controller class. The default mapping from URL to action method is (in "Rails-speak"):

/:controller/:action/:id

If the default URL routing does not meet your needs, you can easily specify your own routing rules, even using regular expressions

Rails routing rules are Ruby code. Here is an example:

map.connect 'date/:year/:month/:day',
:controller => 'blog',
:action => 'by_date',
:month => nil,
:day => nil,
:requirements => {:year => /\d{4}/,
:day => /\d{1,2}/,
:month => /\d{1,2}/}With this routing rule, the following URLs are valid:

http://myblog.com/date/2005
http://myblog.com/date/2005/08
http://myblog.com/date/2005/08/01

This rule decomposes a URL containing a date that, perhaps, a blog might use to display the postings for a particular date. A URL that matches this form will map to the BlogController class and the by_date method. The parameter hash will contain values for a four-digit year (/\d{4}/ is a Ruby regular expression), a two-digit month, and a two-digit day. Further, the month and day are optional; if no values are present, the parameter hash will contain the default value of nil.

Filters allow you to run preprocessing code before Rails executes an action and post-processing code after it completes an action. They are useful for such things as caching or authentication before calling the action, and compression or localization of the response after calling an action. The before_filter processing can either allow the action to be called normally by returning true, or abort the action by returning false (or by performing a render or redirect operation).





http://www.onlamp.com/pub/a/onlamp/2005/10/13/what_is_rails.html?page=5

Tuesday, February 20, 2007

More Rails

Class names are mixed case (each word
starts with a capital letter, and there are no breaks). Table names (and, as
we’ll see later, variable names and symbols) are lowercase, with an underscore
between words

Over in app/controllers you’ll find a file called application.
rb. This file is used to establish a context for the entire application.
By default, it contains an empty definition of class ApplicationController.

If we end a piece of
embedded Ruby with -%> (note the extra minus sign), ERb will suppress the
newline that follows. That means embedded Ruby that doesn’t generate
any output won’t end up leaving extraneous blank lines in the output.

A commonly used method of array objects is <<, which appends a value to
its receiver.

The session construct stores the objects that you want to keep around
between browser requests. To make this work, Rails has to take these
objects and store them at the end of one request, loading them back
in when a subsequent request comes in from the same browser. To
store objects outside the running application, Rails uses Ruby’s serialization
mechanism, which converts objects to data that can be loaded back in.

Rails has a convenient way of dealing with
errors and error reporting. It defines a structure called a flash. A flash is a
bucket (actually closer to a Hash), into which you can store stuff as you process
a request. The contents of the flash are available to the next request
in this session before being deleted automatically. Typically the flash is
used to collect error messages

The flash information is accessible within the views by using the @flash instance variable.

Why couldn’t we just store the error in any old instance variable? Remember
that a redirect is sent by our application to the browser, which then
sends a new request back to our application. By the time we receive that
request, our application has moved on—all the instance variables from
previous requests are long gone. The flash data is stored in the session in
order to make it available between requests.

A helper is simply code in a module that is automatically included into your views.
You define helper files in app/helpers. A helper named xyz_helper.rb defines
methods that will be available to views invoked by the xyz controller. If
you define helper methods in the file app/helpers/application_helper.rb, those
methods will be available in all views.

model objects perform two roles: they map data into and out of the
database, but they are also just regular objects that hold business data.
They affect the database only when you tell them to, typically by calling
save( ).

The render_component( ) method invokes the given action and substitutes
the output it renders into the current view.


one way of handling subroutines at the view level is by using components to show the contents of a page on some other page. A lighter-weight way of doing the same thing is using a partial template. Unlike the component-based approach, a partial template
has no corresponding action; it’s simply a chunk of template code
that has been factored into a separate file

We know how to create new rows in a database table; we create an action,
put a form into a view, and invoke the model to save data away.

Inside a Rails controller, the request information is available in the attribute request. We can check the request type using the methods get?( ) and post?( ).

form_tag needs no parameters, as it defaults to submitting the form back
to the action and controller that rendered the template

Ruby’s attr_accessor creates a read/write attribute in the model.

Monday, February 19, 2007

rails

A Rails scaffold is an autogenerated framework for manipulating a model.
When we run the generator, we tell it that we want a scaffold for a particular
model (which it creates) and that we want to access it through a given
controller (which it also creates).

All scaffold-generated applications use the stylesheet scaffold.css in the
directory public/stylesheets.

The scaffold generator automatically makes use of Rails’ built-in
pagination helper. This breaks the lists of products into pages of 10 entries
each and automatically handles navigation between pages

In Rails, a model is automatically mapped to a database table whose name is the plural form of the model’s class.


The model layer is the gatekeeper between the world of code and the
database. Nothing to do with our application comes out of the database or
gets stored back into the database that doesn’t first go through the model.
This makes it an ideal place to put all validation; it doesn’t matter whether
the data comes from a form or from some programmatic manipulation in
our application. If the model checks it before writing to the database, then
the database will be protected from bad data.

Tuesday, January 30, 2007

Delete vs Truncate @ SQL

SQL Server
TRUNCATE is a DDL command and cannot be rolled back. All of the memory space is released back to the server.
DELETE is a DML command and can be rolled back.

Both commands accomplish identical tasks (removing all data from a table), but TRUNCATE is much faster

TRUNCATE : You can't use WHERE clause
DELETE : You can use WHERE clause

Truncate = Delete+Commit -so we cant roll back
Truncate is a Transcation control language

Truncate: Drop all object's statistics and marks like High Water Mark, free extents and leave the object really empty with the first extent.
Delete: You can keep object's statistics and all allocated space.

Truncate will write only one query in the ldf file to remove whole data unlike the Delete query which will write one query per record in the ldf file

You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.

http://www.geekinterview.com/question_details/425

MYSQL

TRUNCATE TABLE empties a table completely. Logically, this is equivalent to a DELETE statement that deletes all rows, but there are practical differences under some circumstances.

For InnoDB before version 5.0.3, TRUNCATE TABLE is mapped to DELETE, so there is no difference. Starting with MySQL 5.0.3, fast TRUNCATE TABLE is available. However, the operation is still mapped to DELETE if there are foreign key constraints that reference the table. (When fast truncate is used, it resets any AUTO_INCREMENT counter. From MySQL 5.0.13 on, the AUTO_INCREMENT counter is reset by TRUNCATE TABLE, regardless of whether there is a foreign key constraint.)

For other storage engines, TRUNCATE TABLE differs from DELETE in the following ways in MySQL 5.0:

Truncate operations drop and re-create the table, which is much faster than deleting rows one by one.

Truncate operations are not transaction-safe; an error occurs when attempting one in the course of an active transaction or active table lock.

The number of deleted rows is not returned.

As long as the table format file tbl_name.frm is valid, the table can be re-created as an empty table with TRUNCATE TABLE, even if the data or index files have become corrupted.

The table handler does not remember the last used AUTO_INCREMENT value, but starts counting from the beginning. This is true even for MyISAM and InnoDB, which normally do not reuse sequence values.

Since truncation of a table does not make any use of DELETE, the TRUNCATE statement does not invoke ON DELETE triggers.

Monday, January 29, 2007

DOM @ XML

The XML Document Object Model (XML DOM) defines a standard way for accessing and manipulating XML documents.

The DOM presents an XML document as a tree-structure (a node tree), with the elements, attributes, and text defined as nodes.

Parsing the XML DOM

To manipulate an XML document, you need an XML parser. The parser loads the document into your computer's memory. Once the document is loaded, its data can be manipulated using the DOM. The DOM treats the XML document as a tree.

There are some differences between Microsoft's XML parser and the XML parser used in Mozilla browsers. In this tutorial we will show you how to create cross browser scripts that will work in both Internet Explorer and Mozilla browsers


Microsoft's XML Parser
Microsoft's XML parser is a COM component that comes with Internet Explorer 5 and higher. Once you have installed Internet Explorer, the parser is available to scripts.

Microsoft's XML parser supports all the necessary functions to traverse the node tree, access the nodes and their attribute values, insert and delete nodes, and convert the node tree back to XML.

To create an instance of Microsoft's XML parser, use the following code:

JavaScript:

var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");

The first line of the script above creates an instance of the XML parser. The second line turns off asynchronized loading, to make sure that the parser will not continue execution of the script before the document is fully loaded. The third line tells the parser to load an XML document called "note.xml".

XML Parser in Mozilla, Firefox, and Opera
Mozilla's XML parser supports all the necessary functions to traverse the node tree, access the nodes and their attribute values, insert and delete nodes, and convert the node tree back to XML.

To create an instance of the XML parser in Mozilla browsers, use the following code:

JavaScript:

var xmlDoc=document.implementation.createDocument("ns","root",null);

The first parameter, ns, defines the namespace used for the XML document. The second parameter, root, is the XML root element in the XML file. The third parameter, null, is always null because it is not implemented yet

The following code fragment loads an existing XML document ("note.xml") into Mozillas' XML parser:

var xmlDoc=document.implementation.createDocument("","",null);
xmlDoc.load("note.xml");

The first line of the script above creates an instance of the XML parser. The second line tells the parser to load an XML document called "note.xml".

Monday, January 08, 2007

Thursday, January 04, 2007

Social Software



List of Social Softwares
http://en.wikipedia.org/wiki/List_of_social_software

Introduction-to-the-Read-Write-Web

Wednesday, January 03, 2007

Misc things @ JavaScript

Ok/Cancel box:

if (confirm('Like cookies?')) { document.write('you like cookies!') }

The buttons on a confirm box cannot be changed, nor can you specify a
default button

Session object
The Session object is a host object (i.e. not native) that is made
available to JavaScript code processed on the server in an ASP
pre-processing page.

under ASP I believe the Session object's
properties are accessed using ' ( ) ' notation, so in an ASP page,
Session("UserID") = "" is valid.

The ASP Session object cannot be acessed by code running on the client. It is only available to that JavaScript which
runs on the server **before** the ASP page is sent to the client.

An Iframe is a frame, so to get to the page that holds the Iframe you need
'parent'. From the popupwindow to the first window, use the word 'opener'.
So you need parent.opener...
But JS will only communicate between all these windowobjects if they all
reside in the same domain.