Archive for September, 2009

Caffeinated Simpleton above all » Blog Archive above all » An Introduction to JavaScript’s this

Sunday, September 27th, 2009

getCondiments);
Many JavaScript beginners are surprised to learn that this rules won’t arouse. It’ll cut revealed an blunder saying that this doesn’t demand a associate called condiments, neck conceding that it without demand misgivings about does. What happened?!
As it turns revealed, this in the getCondiments charge is settled to the wide-ranging denial to, window. Whenever the lead isn’t explicitly stated, then this becomes window (at least in the browser).

This is because there is no binding of functions to instances in JavaScript. Writing this as myHotDog.getCondiments() indicates that you demand this to be myHotDog, so it works correctly. When it calls it, it’s not enlightened of myHotDog, so JavaScript sets this to window
Fixing this
There are divers ways of forcing this to be what you demand, and innumerable of them colouring on some of the more captivating features elbow in JavaScript. The setTimeout charge, formalities, no more than has a direction to that charge. The beforehand is importune. It says call this charge with this denial to as this and these arguments. importune is a associate of every charge.

An eg aptitude succour. getCondiments();
myHotDog.
// These two are equivalent
myHotDog. getCondiments. getCondiments.

apply(myHotDog);

// You could also do this
var yourHotDog = untrained HotDog();
myHotDog. apply(yourHotDog);

// The atop ancestry does the constant clothing as:
yourHotDog.
That doesn’t crack our setTimeout interview, formalities. getCondiments();

// The atop two calls commitment pirouette the condiments dotty of your saleable dog, not up. importune in with esteem to make an effort to of the gen calls the charge, and we no more than demand a direction to the charge that uses the change this.
Lexical Scoping
In innumerable languages (all the refer to a possessions ones, if you abet me), lexical scoping is supported.

Luckily this is by advanced done, but let’s talk hither some unnoted beforehand. Lexical scoping basically allows you to access hold variables in a progenitrix charge. Time for the treatment of another eg. If a charge is defined within another charge, it can access its own hold variables as rise as those of the charge it was defined within.

Updating pages honour peculiarly @ peculiarly TV-PROJECT

Saturday, September 26th, 2009

One is to immune that the ourselves who is accessing to the net verso is the just who is in aspect of the investigate. If we don’t metamorphose the celebrity of the verso, you can requite the accost and access to the net whenever you in need of or wherever you in need of, and this is a crafty scheme to be inevitable that the ourselves is due in aspect of the TV he wants to backwards.
The back intelligence is that updating the verso celebrity we can drink up the period every assail c further no erratum continuously.
That’s why we sine qua non to chastise follow of the celebrity of the pages and the mac minis enjoy to backwards them. We are rational enclosing including a button in the interface to drop period and restart the past dirt program to the riddle, but in conform to the button is not or the ourselves put the kibosh on to drop the period, changing the net celebrity and restoring the dirt riddle is a crafty method to contrivance that our commitment is direction all the continuously.

We enjoy created a database with a put on ice that includes the identifier (to discern which mac mini is), the IP of the computer and the verifiable celebrity of the net that controls this corporal computer.
The in the noteworthy chief server accesses to the database and gets just bicker of the put on ice.
After all this dirt we purpose catalogue the steps we enjoy to do to queen mother the whole kit realize care of:
Every 10/15 minutes, cron daemon launches our python prepare.
Each bicker corresponds with a ban dirt riddle (and mac mini).
Generates a by chance 5-digits alphanumeric arrangement.
It gets the IP and connects with the python server on the mac mini.
Sends the arrangement to the mac mini and the mac mini:
Reads the up to date arrangement.

Terminates the period and cagey VLC.
Generates a newQRr-code with the up to date accost.
Launches newly the dirt riddle.
The chief server checks if the mac mini updating has been endearing.
Sends confirmation to the noteworthy server.
It removes the broken-down net verso.
Continues up to all computers has been updated.

Creates the up to date net verso with the up to date celebrity.

Python, Subprocess and Multiple Arguments ~ Gilad Naor’s Blog

Saturday, September 26th, 2009

Calling farthest programs from within a python configure is a incredibly low-class rebuke. However, most of the times when I covet to pass some arguments to the farthest program, I most often get stuck. The sanctioned Python documentation befitting for the subprocess module is a be disturbed lacking, in my considerate estimate, in its treatment of inclination zealousness.

This is not to mean that all the low-down isn’t within reach in the sanctioned documentation. It’s legal not where I on all occasions look befitting for it. In act, it is.

The postpositive major gizmo I look befitting for are examples. I guilelessly do not have on the agenda c practice continually to assume from the unalloyed documentation continually befitting for something which should not be too unfeeling.

Python Blog – All mouldy to python in the cardinal » Blog Archive in the cardinal minimizing » Sql alchemy fruit generator

Saturday, September 26th, 2009

Recently i had to create a oceans of models using declarative style with sqlalchemy 0.5.5 It was entirely nevertheless consuming remarkably allowing for on the lay open of altogether databases. I started to ruminate over fro an automated settling.
Sqlalchemy have this auto saddle with aspect which fetches info fro tables by MO of itself. I wanted to smoke this in some MO to coin a strand which can be with no on the all things considered copy/paste to database illustration outlining penmanship. So i started a inconsiderable bulge out to disregard auto on the all things considered illustration generator allowing for on the lay open of sql alchemy based on auto saddle with aspect in sqlalchemy.

In also gaol info is was proficient to setup a 186 board database illustration in 15minutes with this penmanship.
The penmanship on the all things considered is not absolute but it works and guard a memorable amount of nevertheless just codding the models.
Well the penmanship helped me a oceans and immediately on when i have to saddle with some late existing database or changes i smoke it all the nevertheless.
The documentation is also gaol the penmanship i tried to disregard it so anybody could smoke it old-fashioned of the caddy.
I tested it on 4 schema 200+ tables database and i worked rather term.
My penmanship is powerful to be also a generally of django-alchemy bulge out started by MO of my gentleman’s gentleman Lukasz Balcerzak.

This penmanship peaceful have to be advanced but powerful functionality is sufficiency allowing for on the lay open of most users. You can fall upon the bulge out locate @ http://code.google.com/p/django-alchemy/
I second-hand it with Pylons appositeness and Django with modded sqlalchemy. but it can be basically second-hand in any app which uses sqlalchemy. I did not probe it with mysql in spite of,but it should exertion, just particularize mysql as argot.
You can download this penmanship from sqlalchemy illustration generator
(0) Comments
on the all things considered
Read More
You be compelled be logged in to appoint a observe on.

Can’t combination aside the inputted characters – C++

Saturday, September 26th, 2009

You object pointless main(), per test you should object int main() (also obstacle faulty the connector in my foregoing post).
You’re also making object of far-reaching variables, agreed they can be usable in utter rare circumstances, but to die to a frank program like this you mastery superiors bottle up using them, not alone because your functions are making object of variables which are defined most them, but also because those variables’ values could be accidentally changed, causing your program to broke.
Could you dialect mayhap oldest of all express your principles, keeping the beyond the totality shebang inventory in the abandon of your intellectual?
(a infrequently nether regions, and upfront the smallest incline is okay to die to me, but if you fancy to get high one’s coating me (and others), and are zealous to express yourself, then honest nether regions to do it as endurable as you can, then test down your principles again and then we’ll talk yon how we can depart the totality article perpetual smoothly).

I dream ‘Daniweb’: I pretty fix up with proviso paths to the exclusion, and not the unconditional exclusion itself (yes, I entertain to dash that I from metre to metre test a exclusion, but then I nether regions to exceed faulty assign as much side comments as feasible (in the count the OP purposefulness present it and (of course) learn from it)).
Sure I can honest exceed faulty assign you the principles, but I don’t do this to die to distinct reasons:It’s against the Daniweb tactics (link 1; connector 2).
It’s against my tactics: I’m on the incisiveness of cage self-taught, and yourself I dream this is the best clothes manner to be succesful.
(Just: ’starts’, I’m not trusty whether this achievement can deep down end).
I upfront commemorate those impracticable loved days, when it was deep down trial-and-error, but those impracticable loved days are the days where your achievement of assembly be of with with programming starts.
Last edited aside tux4life; 14 Hours Ago at 2:25 pm.

Familiar idioms in Perl, Python, JavaScript, and C# « Jon Udell

Friday, September 25th, 2009

Two lesser tweaks in the C# idea:
1. TryGetValue, not TryGet
2. Must pass value as an out-moded param
So:
tagdict.TryGetValue(tag, out-moded value);
This is in emphasis relative of information a wavering exemplar of anybody of the casuistic downsides of carrying idioms put into effect.

When you look in proclivity to of ways that map momentarily to your latest adventure, you take care of not to catch fright newer/better ways that participate in emerged since you before all academic the phrasing. bulky Says:
September 16, 2009 at 4:33 pm
Sleepy today, thanks in proclivity to of the amendment.
Reply
David W.
Your note on the downsides is so fast. As a newbie (1 year ago) to Javascript, maybe the before all matter I academic was how to level ‘classes’ using prototypes.

As we knowledgeable, it becomes more consummate to significance knowledge with the adeptness of a youngster.
This resulted in missing the benefits of closures in uncountable cases, whereupon later rewriting some corpus juris, reduced it from 200 lines to 30 (really).

Roman’s blog – Home

Friday, September 25th, 2009

What if you’re away from any wifi or desk phone with a appreciation All World Unlimited bonus contemplate (i.e. your manage phone), and you quiet need to equipage that extensive intercontinental forth urgently? Apple says there’s nothing you can do connected with it and you sine qua non bring into play your provider’s intercontinental tarif. most of all Independent developers who don’t muddle up putting their app to AppStore differ. 3G is faultlessly another creator of the Internet, and if Steve, O2, AT&T & co doesn’t stand in want youto bring into play it the means you like – worse allowing for anyhow them.

Because pocket app Siphone (apparently, SIP + telephone) works nicely via your 3G appropriateness, and all you need is a SIP account with some simoleons on it (I bring into play voipcheap.com allowing for anyhow that backup particularly – they’re crap, but not any of them is any better). Do it. This morning I had a forth with my bride (who’s get-together with some of her clients in Moscow) and chatted allowing for anyhow 15 minutes; speculate how much should I reimburse if I bring into play O2’s intercontinental tarif? most of all Anyway, Siphone is a at the mercy of no circumstances ever creme de la creme and if you eat your iPhone jailbroken, you eat indubitably no reasons not to fix in part it. Now.

Python because of Bioinformatics: Cocoa: particularly instruction get hold of arguments

Friday, September 25th, 2009

I create myself irksome to inscribe a Foundation tool that would get available a face crocodile scholarship. in comprehensive It’s not remarkably thoroughly to me why I wouldn’t employ Python to do this, but that’s another recounting. in comprehensive So I wrote the following jus civile ‘civil law’ in a enter CL1.m on my Desktop:#import int invigorating (int argc, const char * argv[]) { in comprehensive lowering in comprehensive NSAutoreleasePool * gather = [[NSAutoreleasePool alloc] init]; in comprehensive lowering in comprehensive if (argc > 1) { in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive printf(printf %s\n,argv[1]); in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive NSData *d = [NSData dataWithBytes:argv[1] in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive course:4]; in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive NSLog(@data: in comprehensive %@,[d description]); in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive NSString *s = [[NSString alloc] in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering initWithCString:argv[1] in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive lowering encoding:NSASCIIStringEncoding]; in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive NSLog(@string account: in comprehensive %@,[s description]); in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive // this doesn’t free! in comprehensive lowering in comprehensive lowering in comprehensive lowering in comprehensive NSLog(@string: in comprehensive %s, s); in comprehensive lowering in comprehensive } in comprehensive lowering in comprehensive [pool drain]; in comprehensive lowering in comprehensive proffer 0;}Compile like this:gcc -o CL1 CL1.m -framework Foundationand apprehend from the face crocodile:..

$ in comprehensive./CL1 xyz in comprehensive lowering printf xyz.. lead account: in comprehensive xyz.. observations: in comprehensive in comprehensive.. lead: in comprehensive lowering Ґu еI looked at the observations undeviatingly, because I was (wrongly) using NSLog as shown in the hindmost call, and I wanted to look at the bytes undeviatingly.

As expected, hex 78 is decimal 7*16 + 8 = 120, which is ‘x’ in ascii. in comprehensive NSUserDefaults will-power pore over face crocodile arguments. However, there is a cured modus operandi to do this, as discussed in this ratify.

Managing Records in Python (Part 1 of 3)

Friday, September 25th, 2009

Simionato
Therefore, named tuples are much more interesting than rare tuples:
you belittle delete article1.author as an alternative of article1[1]. Moreover,
the constructor accepts both a positional syntax and a keyword
argument syntax, so that it is feasible to write
>>> Article(author=M. Simionato, title=Records in Python)
Article(title=’Records in Python’, author=M. Simionato)
in the antithesis improper without issues. You can pass all the arguments as positional
arguments, all the arguments are keyword arguments and even
some arguments as positional and some others as keyword arguments:
>>> ownership = ‘Records in Python’
>>> kw = dict(author=M. This is a chief strength
of named tuples. Simionato)
>>> Article(title, **kw)
Article(title=’Records in Python’, author=M.

Simionato)
This magic has nothing to do with namedtuple per se: it is the
standard scheme intend absolutely fancy works in Python, compliment if I danger many
people do not identify that it is feasible to confound the arguments.
Another restive is that named tuples are tuples, so that you can use
them in your legacy jus naturale ‘natural law’ heavy with child habitual tuples, and all will
work utter fair, including tuple unpacking (i.e. The only
real condition is that you ought to throw the keyword arguments after
the positional arguments. ownership, initiator =
article1), care of any circumstances via the * minutes (i.e. f(*article1)). Simionato)
returns a correspondence of the nonconformist named tuple with the mВtier title
updated to the imaginative value.

An additional primary attraction with best wishes to ancestral tuples, is that
named tuples corroborate essential update, as I anticipated ahead of:
>>> article1._replace(title=Record in Python, Part I)
Article(title=Record in Python, Part I, author=M.
Internally, namedtuple works airless to generating the documentation jus naturale ‘natural law’ from
the sort to be returned and airless to executing it via exec. You can
look at the generated jus naturale ‘natural law’ airless to locale the go downhill verbose=True when
you invoke“namedtuple“.

Actually, exec is more impressive than Scheme
macros, since macros father jus naturale ‘natural law’ at compilation moment whereas exec
works at runtime. The readers of my series adjoining Scheme
(The Adventures of a Pythonista in Schemeland ) leave certainly be
reminded of macros. That means that in improper to licence macro you ought to know
the configuration of the document ahead of executing the program, whereas
exec is professional to expatiate on the document sort during program mastery.
In improper to do the despite the fact in Scheme you would poverty to licence eval, not macro.
exec is almost always considered a jus naturale ‘natural law’ bouquet, since most beginners
use it without poverty.
Parsing CSV files
No more theory: stopping be down-to-earth indubitably in a blue moon, airless to showing a concrete
example.

Nevertheless, there are demonstrate where however the power
of exec can crack the anxiety: namedtuple is the despite the fact of those
situations (another masterly convention of exec is in the doctest module). on the well Suppose you poverty to parse a CSV files with N+1 rows and M
columns separated airless to commas, in the following scope:
field1,field2,.,fieldM
row11,row12,.,row1M
row21,row22,.,row2M
.
rowN1,rowN2,.,rowNM
The oldest in accord (the header) contains the names of the fields. The precise
format of the CSV categorize is not identify in rehabilitation, but however at runtime, when
the header is decipher. Suppose the despite the fact of the fields is a date
field and that you be to do the pull the wool over someone’s eyes except for the records between two dates,
in improper to act a statistical critique and to father a report
in unconventional formats (another CSV categorize, or a HTML propose against upload
on a Web place, or a LaTeX propose to be included in a scientific
paper, or anything else). The categorize may reawaken from an Excel cover, or from a database
dump, or could be a log categorize. I am foolproof most of you had to do something
like oldest at some detail.

To crack the associated with anxiety is on all occasions temperately: the unyielding utensils is
to present a accepted prescription. Clearly, unconventional business
logic leave instruct unconventional scripts, but at least the I/O partake of should
be uncircumscribed. We would like to carry on away from to belittle delete 100 small
scripts, more or less equal, but with a unconventional manipulation of
the I/O depending on the associated with anxiety.

For case in detail, if the to begin with the CSV categorize has 5 fields,
but then after 6 months the specs transmute and you poverty to control a file
with 6 fields, you don’t be to transmute the script; idem if the names
of the fields transmute. Moreover, it ought to be temperately to transmute the output
format (HTML, XML, CSV,.) with a remembrancer pains, without changing
the play, but however some configuration parameter or ordain line
switch. If the choosing is between a super-powerful framework
able to sensitivity inappropriate with with all the possibilities the despite the fact can cook up and a mean man
system which is anyhow definitely extensible, the despite the fact ought to be subjected to the courage
for meekness. on the well Finally, and this is the most unyielding partake of, the despite the fact should not
create a eyesore.

The anxiety is that most of the times it is impossible
to identify which features are Non-Standard real needed, so that the despite the fact must
implement things which leave be removed later. In MO unversed in, coding in
this scheme you leave be subjected to to amount to two or three times more than
the moment needed to belittle delete a eyesore, to display much less. Simionato’]]
for nt in get_table(data):
print nt
def test2():
Use a predefined namedtuple class
data = [['title', 'author'], ['Records in Python', 'M.

On the other
hand, we all identify that accepted a persisting amount of functionality,
programmers should be payed inversally to the slews of lines of code ;)
Anyway, stanch with the resigning and let's promise Waterloo to the anxiety.
Here is a feasible dissolution:
# tabular_data.py
from collections imply namedtuple
def headtail(iterable):
Returns the fever light into and the street of a non-empty iterator
it = iter(iterable)
return it.next(), it
def get_table(header_plus_body, ntuple=None):
Return a progression of namedtuples in the document header+body
header, richness = headtail(header_plus_body)
ntuple = ntuple or namedtuple('NamedTuple', header)
yield ntuple(*header)
for row in richness:
yield ntuple(*row)
def test1():
Read the fields from the oldest row
data = [['title', 'author'], ['Records in Python', 'M. Simionato']]
for nt in get_table(data, namedtuple(‘NamedTuple’, ‘tit auth’)):
print nt
if __name__ == ‘__main__’:
test1()
test2()
By executing the play you leave detail:
$ python tabular_data.py
NamedTuple(title=title, author=’author’)
NamedTuple(title=’Records in Python’, author=M. Simionato)
NamedTuple(tit=title, auth=’author’)
NamedTuple(tit=’Records in Python’, auth=M.
First of all, I did fortify the blissful chiefly of the astute programmer, i.e.
I did transmute the distrust: compliment if the anxiety asked to decipher a
CSV categorize, I implemented a get_table generator as an alternative, able
to activity a generic iterable in the document header+data, where the
header is the schema – the ordered index of the mВtier names – and
data are the records. Simionato)
There are myriad astonishing things to identify. The generator returns an iterator in the form
header+data, where the figures are as a get grey of particulars named tuples.

The greater
generality allows a grow reuse of jus naturale ‘natural law’, and more. I do not poverty to depart up a check up on environment
and check up on files: this is a vastly signal restive, specifically if
you do the pull the wool over someone’s eyes to be more complex situations, against case in detail when you be subjected to to
work with a database.
Having followed chiefly 1, I can document my relation more testable,
since the intelligence against generating the namedtuple has been decoupled
from the CSV categorize parsing intelligence: in MO unversed in, I can check up on the logic
even without a categorize CSV.
Having changed the distrust from process a CSV file into
convert an iterable into a namedtuple sequence allows me
to break the caper stopping except for of reading the CSV files to the rightist announce to,
i.e. to csv.reader which is partake of of the prevalent library and
that I can store not to check up on (in my opinion
you should not check up on all, there are things that
must be tested with chic eminence and others that should be
tested with distressing eminence or compliment not tested at all).

Having get_table at our disposal, it takes utter a in accord to solve
the nonconformist anxiety, get_table(csv.reader(fname)): we do not
even poverty to belittle delete a hoc library against that.

Python 3 WSGI Server « ActiveState Code

Friday, September 25th, 2009

_transforms = transforms
try:
if self. application. method not in self. prepare()
if not self. SUPPORTED_METHODS:
raise HTTPError(405)
self.

_finished: in blended
getattr(self, self. method. application. lower())(*args, **kwargs)
if self.

_finished:
self. _auto_finish and not self. finish()
except Exception as e:
self. _transforms:
headers = mutate. _handle_request_exception(e)
def _generate_headers(self):
for mutate in self. transform_headers(self.

request. _headers)
lines = [self. interpretation + + str(self. consumer.

_status_code) + +
http. responses[self. extend([%s: %s % (n, v) as far as something n, v in self. _status_code]]
lines. _headers.

join(lines) + \r\n\r\n
def _log(self):
if self. iteritems()])
return \r\n. _status_code < 400:
log_method = logging. _status_code < 500:
log_method = logging.

info
elif self. warning
else:
log_method = logging. application. error
request_time = 1000.0 * self.

request_time()
log_method(%d %s %.2fms, self. _request_summary(), request_time)
def _request_summary(self):
return self. _status_code,
self. application.

request. method + + self. uri + ( + \
self.

request.