Saturday, December 23, 2006

PySpotting

Choose Python. Choose readability.
Choose the simple over the complex and
the complex over the complicated. Choose
dynamic typing. Choose duck typing.
Choose decorators. Choose generators.
Choose metaclasses if you don't value
your sanity. Choose to import this. Choose
an almost-fanatical devotion to the BDFL,
unless he comes up with something like
optional static typing, in which case choose
to whine about it in your blog until he stops.
Choose Effbot. Choose Timbot. Choose
wx. Choose to come up with a bloody implementation
before spouting off on
comp.lang.python or Python-Dev. Choose
the explicit rather than the implicit. Choose
one obvious way to do it, especially if you
are Dutch. Choose list comprehensions.
Choose Paul Graham's essays and
s/LISP/Python/g. Choose Jython when
your marketing people choose Java.
Choose speed of development over speed
of execution, but when in doubt, import
psyco. Choose to finish early and laugh at
your colleagues as they waste their miserable
lives bowing down in subservience to
that sadistic little C++ compiler.
Choose Python.
Choose your __future__

The General Query Log @ Mysql

The general query log is a general record of what mysqld is doing. The server writes information to this log when clients connect or disconnect, and it logs each SQL statement received from clients. The general query log can be very useful when you suspect an error in a client and want to know exactly what the client sent to mysqld.

mysqld writes statements to the query log in the order that it receives them, which might differ from the order in which they are executed. This logging order contrasts to the binary log, for which statements are written after they are executed but before any locks are released. (Also, the query log contains all statements, whereas the binary log does not contain statements that only select data.)

To enable the general query log, start mysqld with the --log[=file_name] or -l [file_name] option.

If no file_name value is given for --log or -l, the default name is host_name.log in the data directory.

Server restarts and log flushing do not cause a new general query log file to be generated (although flushing closes and reopens it). On Unix, you can rename the file and create a new one by using the following commands:
shell> mv host_name.log host_name-old.log
shell> mysqladmin flush-logs
shell> cp host_name-old.log backup-directory
shell> rm host_name-old.log

On Windows, you cannot rename the log file while the server has it open. You must stop the server and rename the file, and then restart the server to create a new log file.

String Methods @ Python

strip( [chars])

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'


split( [sep [,maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified, then there is no limit on the number of splits (all possible splits are made). Consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, "'1„2'.split(',')"returns "['1', '', '2']"). The sep argument may consist of multiple characters (for example, "'1, 2, 3'.split(', ')" returns "['1', '2', '3']"). Splitting an empty string with a specified separator returns "['']".

If sep is not specified or is None, a different splitting algorithm is applied. First, whitespace characters (spaces, tabs, newlines, returns, and formfeeds) are stripped from both ends. Then, words are separated by arbitrary length strings of whitespace characters. Consecutive whitespace delimiters are treated as a single delimiter ("'1 2 3'.split()" returns "['1', '2', '3']"). Splitting an empty string or a string consisting of just whitespace returns an empty list.

List Manipulation @ Python

Just think of python variables as labels to objects, not as storing stuff or even references to something.

In fact you don't event need copy module... since when you slice a list it returns a new list object with the objects needed, you can use a slice to give a new list with all objects, a copy:

>>> a = [1, 2, 3]
>>> b = [a[:], a[:], a[:]]
>>> b
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
>>> b[1][1]
2
>>> b[1][1] = 4
>>> b
[[1, 2, 3], [1, 4, 3], [1, 2, 3]]

You get changed only the 2nd list, because you created three copies:

>>> a is a
True
>>> a[:] is a[:]
False
>>> a[:] == a[:]
True


The same happen for elementary types, they are no exception, but the behavior with them may be different because they are immutable and may be the same object. With integers, for instance, in this case, with small integers,

>>> x = 10
>>> y = x - 1
>>> z = x - 1
>>> y == z
True
>>> y is z
True

Both y and z are integers with the same value and are the same object. But with large integers, the same may not happen:

>>> x = 123456789
>>> y = x - 1
>>> z = x - 1
>>> y == z
True
>>> y is z
False

Here they have the same value, but they are not the same object. Since they are immutable, it doesn't matter, just to keep in mind to always think if you want to make comparisons by value (==) or by identity (is)

"==" compare by value, if both objects have the same value, while "is" compare by identity, if they are the same object.

Example, here x and y have the same value, but are not the same objects.

>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x == y
True
>>> x is y
False


Here x and y are the same object, and therefore have the same value:
>>> x = y = [1, 2, 3]
>>> x == y
True
>>> x is y
True

But, when you deal with immutable objects, Python have an internal cache, so they may be the same object, but you have no guarantee, so be careful if you want to check by value or identity...

Friday, December 22, 2006

Enabling Task Manager @ Windows

Click Run
· Enter gpedit.msc in the Open box and click OK
· In the Group Policy settings window
o Select User Configuration
o Select Administrative Templates
o Select System
o Select Ctrl+Alt+Delete options
o Select Remove Task Manager
o Double-click the Remove Task Manager option
that will do

XML Data island @ XML

In an HTML document, you can embed the XML file above with the xml tag. The id attribute of the xml tag defines an ID for the data island, and the src attribute points to the XML file to embed:

The datasrc attribute of the tag binds the HTML table element to the XML data island. The datasrc attribute refers to the id attribute of the data island.
tags cannot be bound to data, so we are using tags. The tag allows the datafld attribute to refer to the XML element to be displayed.


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.

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");

VBScript:
set xmlDoc=CreateObject("Microsoft.XMLDOM")

ASP:
set xmlDoc=Server.CreateObject("Microsoft.XMLDOM")
The following code fragment loads an existing XML document ("note.xml") into Microsoft's XML parser:
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load("note.xml");
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".

http://www.w3schools.com/xml/xml_data_island.asp

Repeat @ Python

class repeat(__builtin__.object)
repeat(element [,times]) -> create an iterator which returns the element
for the specified number of times. If not specified, returns the element
endlessly.

Methods defined here:

__getattribute__(...)
x.__getattribute__('name') <==> x.name

__iter__(...)
x.__iter__() <==> iter(x)

__len__(...)
x.__len__() <==> len(x)

__repr__(...)
x.__repr__() <==> repr(x)

next(...)
x.next() -> the next value, or raise StopIteration

----------------------------------------------------------------------
Data and other attributes defined here:

__new__ =
T.__new__(S, ...) -> a new object with type S, a subtype of T

Thursday, December 21, 2006

Dictionary @ Python

> Python dict is a hash table, isn't it? Yup.
> I know that hashtable has the concept of "bucket size" and "min bucket
> count" stuff,

Some implementations of hash tables do. Python's does not. Python's uses what's called "open addressing" instead.

> and they should be configurable so I can set them to the proper value
> when I know how many items I'm going to handle.
> If these two values can't be set, the hashtable will give them default
> values. When there are more and more items being added to the
> hashtable, it increase its buckets and copy the old items into the new
> one and re-calculate the hash value of each item.

That's several distinct claims, each of which is true of some hash table implementations but not of others. Python's implementation has no "buckets", so all that's simply irrelevant. Python's implementation (not all do) saves the hash value of each item, so when it does need to grow (or shrink) the space allocated to the table, it does not need to recalculate the hash value of any item.
You should also note that copying a dict key or value (no matter of what type) consists in its entirety of copying one machine address (a 4- or 8-byte pointer, depending on platform).

> I think this will waste some time doing the increasing-copying thing.

It does take time to resize. "Waste" is a value judgment ;-)
> If I know I'm going to handle about 20000 items, I can set the size of
> hashtable to 30000.
> So, can I do this in python?

You can't. Unless you build up to 20000 items over and over (many thousands of times), it's unlikely you'd be able to measure the time difference even if you could.

Ex:

1)creating the dictionary with no other Python overhead

import random; r = [ random.random() for i in range(20000)]; d = dict.fromkeys(r)

2)Creating the dictionary using a Python for loop
import random; r = [ random.random() for i in range(20000)];d={} ;for k in r: d[k] = None

Tuesday, December 19, 2006

WebSite vs Web Application

WEB APPLICATION:
An application that is delivered using Internet technology and meets one or more of the following conditions:
Utilizes a database (such as Oracle or SQL Server)
Is developed using an application development tool (such as Oracle Internet Developer Suite or Visual Studio)
Extracts data from multi-record files
Requires a constantly running server process (such as Newsgroups and Chatrooms)
Stores input data from data entry screens or web forms
Depending on its requirements, a web application may be an Internet Application or an Intranet Application.

WebSite vs Web Application:
Historically, a website is any site on the internet (whether simple or complex) in which visitors can go. Therefore, whether it's a static site (the visitor can only read information or research a topic,) or whether it's a dynamic site (such as an online e-commerce store that can be managed by the store owner online) it's considered a website. A web application is also considered a website. However, web applications are web-based software programs, often as powerful as software applications made for your home or business computer. For instance, many online e-commerce stores are web applications. They are software programs that run on the web and are accessed via the internet instead of running strictly on your PC

JavaScript: Why parseInt(08) & parseInt(09) is showing the value 0 ?

That's because "08" and "09" are invalid numbers, in octal.
The parseInt() function actually allows two arguments, the string to
parse and a radix, which is optional. This radix value allows you to
convert a binary (base 2), hexadecimal (base 16) or other base string to
a decimal integer. For example
parseInt("FF", 16);
returns 255. This is very useful for parsing things like HTML color values.
Most people aren't aware of the optional radix argument. The problem is
that if you leave it off, the function will doesn't necessarily assume
you want a decimal (base 10) conversion. Instead it checks the input
string (the first argument) and if it starts with "0x" it assumes it's a
hexadecimal value. If it starts with "0" - not followed by an "x" - it
takes it as an octal value. This follows the JavaScript convention for
numeric constants. If you code
var x = 0x18;
alert(x);
it will display 24 which is the decimal equivalent of the hex number
"18". Likewise,
var x = 014;
alert(x);
displays 12 which is the decimal value of the octal number "14".
As you should know, hexadecimal uses the digits 0-9 and the letters A-F,
16 in all. Octal is base 8, so only the digits 0-7 are valid. Hence,
"08" and "09" are not valid octal numbers and the function returns zero
just as it would for "xyz" in decimal - it's not a valid number.
To avoid this, always add the second argument, in this case
parseInt("08", 10);
returns 8 (decimal), as desired.

Monday, December 18, 2006

Enumerate function @ Python

class enumerate(object)

| enumerate(iterable) -> iterator for index, value of iterable

|

| Return an enumerate object. iterable must be an other object that supports

| iteration. The enumerate object yields pairs containing a count (from

| zero) and a value yielded by the iterable argument. enumerate is useful

| for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

|

| Methods defined here:

|

| __getattribute__(...)

| x.__getattribute__('name') <==> x.name

|

| __iter__(...)

| x.__iter__() <==> iter(x)

|

| next(...)

| x.next() -> the next value, or raise StopIteration

|

| ----------------------------------------------------------------------

| Data and other attributes defined here:

|

| __new__ =

| T.__new__(S, ...) -> a new object with type S, a subtype of T

ex::

1)
for index,word in enumerate(range(10)):
... print index,word
...
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9

2)
for index,word in enumerate(range(10)):
... print "%s %f" % (index,word)
...
0 0.000000
1 1.000000
2 2.000000
3 3.000000
4 4.000000
5 5.000000
6 6.000000
7 7.000000
8 8.000000
9 9.000000