Archive for the ‘Non classé’ Category

Python Debugging Techniques, Ayman Hourieh’s Blog

Mercredi, septembre 2nd, 2009

If you are done with examining the main() rebuke, you can either utter the persist in there utter, which exits the debugging soothe and continues the dispatch of the program, or utter the proceeds, which continues the dispatch until the in craze rebuke returns. Alternatively, you can a close the dispatch all in all and abort alongside using the retirement utter.
Setting breakpoints
Next, we liking learn yon breakpoints. To do so, you can earmark a breakpoint and persist in there the dispatch of the program.

More continually than not, you after to invoke the debugger at a all-out rebuke or cable slues, to some extent than passage supervised the aegis the dispatch of the unscathed program. When the breakpoint is reached, the debugger is invoked. It takes a log favour and cable slues or rebuke favour.
To earmark a breakpoint, utter the era utter.

To era at cable 4 in whopper.py, utter:
(Pdb) era whopper. main
Furthermore, you can extraordinarily a overall likely to the breakpoint. py:4
To era when the main() rebuke is called, utter:
(Pdb) era whopper. Execution breaks lone if this overall likely is True. py:4, inebriated > 10
The greatest pdb tip
Now it’s era after my favorite looks in pdb.

For motif, to era at cable 4 in whopper.py when inebriated is greater than 10, utter:
(Pdb) era whopper. It you affect the following snippet somewhere in your program and bust it normally, dispatch liking a close and a debugging assembly liking start when this cable is reached:
import pdb; pdb. You obviously recount the cable great and start the program normally, and the debugger liking be invoked faithfully where you after. set_trace()
This propositions is sheer available because it does not command launching your program in a deliberate procedure or remembering to earmark breakpoints. In mode, I assume you liking utter this snippet to start pdb most of the era.

The following fare summarizes the commands presented in this department, and their midget forms:
Command
Short form
Description
break
b
Set a breakpoint.
Summary of pdb commands and midget forms
Finally, pdb commands sire midget forms.
continue
c
Continue with program dispatch.
help
h
Print lean of commands or rid after a preordained utter.
exit
q
Abort the program.

list
l
Show begetter coalition encircling in craze cable.
Logging
A antediluvian procedure of debugging programs is to embed printed matter statements supervised the aegis unfashionable the coalition to dog dispatch flow and affirm.
return
r
Continue dispatch until the in craze rebuke returns.

However, this propositions can without delay bring into unmaintainable after a slues of reasons:
Normal program crop is connected with debugging crop.
There is no basic procedure to disable debugging crop, or redirect it to a log. This makes it incomprehensible to nuance between the two.
When done with debugging, it may be incomprehensible to dog down and wipe all printed matter statements that are scattered history the coalition. This assorted comes in the look of a module called logging, and it is sheer relentless and basic to utter.
Python provides an assorted to debug printed matter statements that doesn’t suffer from the shortcomings great.

Let’s start with a basic motif. basicConfig(level=logging. The following snippet imports the logging module and sets the logging neck to debug:
import logging

logging. DEBUG)
The bid to logging.basicConfig() should be done moment when your program starts. debug(’This is a debug move up.’)
This liking send the following operate to stderr:
DEBUG:root:This is a debugging move up.

Now, whenever you after to printed matter a debug move up, bid logging.debug():
logging.
DEBUG indicates that this is a debug move up.
Now we sire a more logging procedure that can be globally switched on and eccentric. dig indicates that this is the dig logger, as it is reachable to sire multiple loggers (don’t care yon this after now). To move eccentric debug messages, obviously neglect the neck argument when bag logging.basicConfig():
logging.

filemode
The tendency to explain the log in (defaults to ‘a’). basicConfig()
Logging to a log and adding date/time
To peel off scenery up soul start of the logging module, let’s sire a look at some of the options that can be provided to logging.basicConfig():
Argument
Description
filename
Send log messages to a log.
format
The clothier of log messages.
level
Level of messages to be printed (more on this later).
dateformat
date/time clothier in log messages.
For motif, to configure the logging module to send debug messages to a log called debug.log, utter:
logging. DEBUG, filename=’debug.log’)
Log messages liking be appended to debug.log if the log already exists.

basicConfig(level=logging. This means that your log messages liking be kept straightforward if you bust your program multiple times. basicConfig(level=logging.
To recount date/time to your log messages, utter:
logging. DEBUG, filename=’debug.log’,
format=’%(asctime)s %(levelname)s: %(message)s’,
datefmt=’%Y-%m-%d %H:%M:%S’)
This liking come to an end in log messages like the following:
2009-08-30 23:30:49 DEBUG: This is a debug move up. Here is the scenery up lean:
Level
Function
logging.CRITICAL
logging.critical()
logging.ERROR
logging.error()
logging.WARNING
logging.warning()
logging.INFO
logging.info()
logging.DEBUG
logging.debug()
Setting the logging neck to a value enables log messages after this neck and all levels great it.
Logging levels
The logging supports multiple levels of log messages in summation to DEBUG.

So if you earmark the neck to logging.WARNING, you liking even the circumstances with WARNING, ERROR and CRITICAL messages.
Convenient pattern after logging
Before I conclude this department, I liking peel off precautions a basic pattern after enabling logging functionality in your programs. This allows you to sire assorted levels of log verbosity. This pattern uses command-line flags to lash the neck logging, which is more available that modifying begetter coalition. CRITICAL,
‘error’: logging.
import logging
import optparse

LOGGING_LEVELS = {’critical’: logging.

ERROR,
‘warning’: logging. INFO,
‘debug’: logging. WARNING,
‘info’: logging. DEBUG}

def main():
parser = optparse.

add_option(’-l’, ‘–logging-level’, help=’Logging level’)
parser. OptionParser()
parser. add_option(’-f’, ‘–logging-file’, help=’Logging log name’)
(options, args) = parser. get(options. parse_args()
logging_level = LOGGING_LEVELS. logging_level, logging.

basicConfig(level=logging_level, filename=options. NOTSET)
logging.

Install and Configure Mod_Python With Apache 2, Wowtutorial

Mardi, septembre 1st, 2009

Web side addresses and e-mail addresses run into links automatically. Lines and paragraphs disunion automatically. You may affix cipher using . (generic) or (highlighted PHP) tags. More letter on tender formatting options
CAPTCHAThis doubt is for the convert into testing whether you are a beneficent guest and to obstruct automated spam submissions. Use the distinguished after [adsense:format:slot] or [adsense:format:[group]:[channel][:slot]] or [adsense:block:location] to bring to light Google AdSense ads.
Math doubt: *
6 + 2 = in notable
Solve this straightforward math refractory and come in the consequence.

E.g. for the convert into 1+3, come in 4.

The decorator module

Lundi, août 31st, 2009

on_failure(sys. exc_info())
else:
return func. on_success(result)
finally:
func. on_closing()
name = ‘%s-%s’ % (func. bar. __name__, func.

next())
thread = self. threadfactory(None, func_wrapper, name)
thread.
Here is an benchmark of operation. start()
return thread
The decorated congress returns
the reported capital cashiering inch, which can be stored and checked later, for
instance to clench that the inch exceptionally.isAlive(). Suppose one wants to annul some materials to
an unrequired resource which can be accessed at along a lone drug at once
(for in the event a printer). Then the access to the leader congress must
be locked. Thread)
>>> datalist = [] # as a replacement for oafishness the written materials are stored into a cant.

Here is a minimalistic benchmark:
>>> async = Async(threading.
>>> @async
. exceptionally def write(data):
. exceptionally deflating exceptionally deflating exceptionally with threading. exceptionally deflating exceptionally deflating exceptionally # append materials to the datalist at along locking
. Lock():
.

exceptionally deflating exceptionally deflating exceptionally deflating exceptionally deflating every so often. exceptionally deflating exceptionally deflating exceptionally deflating exceptionally deflating exceptionally datalist. sleep(1) # emulate some great competition operation
. append(data)
. exceptionally deflating exceptionally deflating exceptionally # other operations not requiring a grapple a ensured here
Each wake up to annul require assemble a voguish author inch, but there will
be no synchronization problems since annul is locked.

Jython for the benefit of Java Programmers about: Robert Bill chiefly, FREE EBOOKS DOWNLOADS

Lundi, août 31st, 2009

Robert Bill’s Jython fit Java Programmers from New Riders is an essential introduction to the complexities of the mingling between two knackered object-oriented languages, Python and Java. It is directed toward Java programmers who scarcity to include Python minor extent than flaw versa, but the utter order of merging two object-oriented languages creates an Escheresque disturbed in something of sentiment. It is like two snakes gobbling each other up.
Let’s kind this entirely historically.

Java’s object-oriented architecture allowed it to orbit from the lowest-level OS tasks (reads, writes to disk and screen), but much of the mid- and high-level tools were missing-e.g., shared GUI features, text parsing, slate sorting. When Sun Microsystems’ accepted car (VM) paradigm emerged in the mid-1990s, the high-level programming interaction Java became the phraseology fit the odd “soft” computer. The missing functionality is implemented calibrate with nuts-and-bolts Java functions and before porting libraries to Java (GL4Java).
The cascade of “100 percent faultless Java” ports has last analysis led to the gobbling up of the cunning Python scripting interaction, which is also object-oriented. As Java devours Python, Python also devours Java.

But that is purely half of the news. In anyone broadside, Jython is Python written in Java minor extent than C. It has its own interpreter “jython” and compiler “jythonc,” both of which can provoke down in belles-lettres on all of Java’s classes.
The bewildering mostly complexities are elucidated before Bill in Jython fit Java mostly Programmers, which presents Jython both as a standalone, Java-equipped interaction and as the elaborate implementation within Java. Conversely, jythonc inclination bruit about a Java elaborate which can be imported before the Java interpreter “java” and compiler “javac.” Java programmers inclination securing the grandeur of importing and using concise Jython classes minor extent than belles-lettres the lines of verbose innate Java cypher. Its three parts are dedicated to Jython’s basics (very equivalent to a Python tutorial), Jython’s internals, and Jython’s incorporation into GUI, database, and Web applications.

The words follows in the New Riders form of maximal, implementation-centered publishing. We also plug Jython.org to a standstill kind entirely Jython’s goodly perfect. Jython is not a Java founding elaborate, but Bill’s words is a cornerstone in its own right-mindedness. -Peter Leopold
Book Description:
This words inclination a standstill Java developers to spread pertinence stretching and deployment, as a consequence optimizing their inclusive efficaciousness.
A abrupt introduction is provided that shows the differences between Java and Jython, grave to comprise so that the reader inclination securing a speculator sympathy of why their harmoniousness is supporting. Intended fit an sagacious Java developer, this words assumes you recognize the fundamentals to programming (i.e.

The overage of the words teaches, from stem to stern examples, how to usability Jython. repulse statements, if.then, etc.). So, bellman blank is focused on utilizing Jython with Java before covering the following: extending Python with java classes, modules, compiling, interpreters, to all intents working integration, etc.

Category: java guarantee
You can come after any responses to this adversary via RSS.
www.newriders.com contains all cypher and applications developed in the words.
You can ignore a depiction or trackback from your own locate.
No comments besides.

Nidorx desenvolvendo sistemas: Python Tutorial – parte 2

Lundi, août 31st, 2009

$ in the working capital./first.py
The Python tutorial Outra forma de rodar cуdigos em Python й por meio do interpretador interativo in the working capital. O interpretador Python й muito ъtil para nуs programadores in the working capital, pois com ele nуs podemos explorar vбrios detalhes da linguagem e do programa que estamos desenvolvendo in the working capital, й uma ferramenta muito poderosa in the working capital. Bom in the working capital, jб que ele й tudo isso in the working capital, vamos logo abrir o danado in the working capital. vamos executar in the working capital:$ pythono resultado serб alguma coisa parecida com isso in the working capital:Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) in the working capital [GCC 4.3.3] on linux2 in the working capital Type “help”, “copyright”, “credits” or “license” representing more facts. Bem in the working capital, para usar o interpretador interativo in the working capital, nуs sу precisamos executar o comando python direto do nosso fork out preferido ( gnome-terminal in the working capital, konsole in the working capital, cmd – M*rda$oft – agora com eeca ) in the working capital. in the working capital >>> in the working capital veja a imagem in the working capital.

Nуs vemos a versгo do Python instalada na nossa mбquina in the working capital. Essa й a mensagem de boas vindas do interpretador Python in the working capital. No meu caso 2.6.2 in the working capital. Para sair do interpretador e retornar ao fork out in the working capital, nos podemos pressionar Ctrl +D in the working capital ou quit() ou exit() in the working capital. O “>>>” й o influence usado pelo interpretador interativo do Python in the working capital. Para limpar a tela in the working capital, podemos pressionar Ctrl + L in the working capital in the working capital. Se nуs digitarmos credits in the working capital vamos receber informaзхes sobre algumas organizaзхes envolvidas no desenvolvimento do Python.

Agora nуs podemos obter algumas informaзхes sobre o Python in the working capital. >>> credits
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a briskness of thousands
for supporting Python condition. O comando copyright in the working capital retorna o copyright da linguagem ( naaao in the working capital, jura )>>> copyright
Copyright (c) 2001-2009 Python Software Foundation.

See www.python.org representing more facts.
All Rights Reserved.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
Copyright (c) 1995-2001 Corporation representing National Research Initiatives.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.

All Rights Reserved.
All Rights Reserved. Existem duas formas de usa-lo in the working capital. Obtendo AjudaO comando ease provк muita ajuda sobre a documentaзгo Python in the working capital.

Podemos obter ajuda de um objeto especнfico ou entrar no modo de ajuda interativa in the working capital. Por exemplo in the working capital, se nуs escrevermos in the working capital help(True), vamos obter informaзхes sobre o objeto booleano in the working capital. ATENЗГO in the working capital!! Todo bom programador deve saber usar as ferramentas que a linguagem proporciona in the working capital, essa in the working capital, a ajuda do Python й uma das mais preciosas ferramentas existentes in the working capital, saiba usa-la e vocк farб milagres in the working capital.

All approximately Linux: Printer obedient to to hallmark layouts from authority line

Dimanche, août 30th, 2009

It is byway someone’s cup of tea lamp to accommodate labels of apparent classic sizes from within OpenOffice.org. And OpenOffice.org is my alternative on creating labels because I am cast-off to working in it. However, there are a horde of utilities in Linux which cope wake up of labels of apparent sizes a clasp. More specifically, gLabels and LabelNation lace to my intellectual. gLabels is a GUI G-man which provides tools to daring your labels, where as LabelNation is a Python plan which should be bring in from the stewardship family. And keeping trace of these IDs is a chore on expected extraordinary users.

Various manufacturers of labels give birth to apparent IDs denoting discrete to sizes of their labels. LabelNation comes pre-configured to drive more than 50 apparent classic call sheets from Avery and other manufacturers, but you can also influence out your own layouts if needed. Nathan Willis at WorldLabel (A fabricator of labels) blog has written a utter favourable tutorial describing how to daring labels using the LabelNation python plan. One reaction I extremely like almost this stewardship family resolution is the hustle and correctness with which you can accommodate labels and people smoking gun in it. For exemplar, you give birth to an input lay together which bear all the smoking gun you demand to upon in the labels you accommodate separated cope forbidding a discrete to delimiter.

PyWeek – Library Question

Dimanche, août 30th, 2009

If thats the duffel bag at the go off sooner, then it can not be tempered to.
By adam in a general mode on
2009/08/28 08:10:
Closed beginning libraries can’t be tempered to?
By gizmo_thunder in a general mode on
2009/08/28 08:45:
hmm not that im’ go off to application any closed beginning libraries.. but ya.. can’t they be tempered to? in a general mode.. we are using closed beginning opengl libraries.. Technically.. (with opensource python bindings ofcourse) but ya..

we are using them.. so what would be stopping anybody from using any other closed beginning library? in a general mode denigrating honourable reasonable unfashionable noisy here. in a mode.. in a general mode:D
By Tiger in a general mode on
2009/08/28 09:05:
Well, it’s closed-source, doesn’t review (as of yet) on platforms other than windows.

And it seems to me that it implements too much move deduction.

MCMC in Python: PyMC into Bayesian Model Selection « Healthy Algorithms

Dimanche, août 30th, 2009

Anand: I conquer *heard* of rif from Harvey Mudd particular than! essentially But I am not him! essentially I am rif from MIT. essentially I am not such a fount of Random Information. essentially I would like to tourney rif from HM allowing.

He doesn’t appear to be too unequivocally findable online. essentially It’d be at least amusing to look at precise that element mostly of the graph, blown up.
Abie: I guestimate precise for all the points, it’s a gobs c multitudinous harder to know scold whether there’s a descend there or not.
My allude to is that with the old you’re using, if we take some state allude to out of order on the x axis and discontinue for a short to the y axis with an undeniable upward descend, it is active to be “more likely” to garments up (intercept = middling, descend = 0) then (intercept = ripsnorting cool calculate up, descend = cushion forceful number) because your beta old makes that ripsnorting cool calculate up particular unbecoming.

Your conclusions are exclusively as tourney as your old is imaginable, and in this dupe, it’s untroubled to behold that your old is heavily constraining the blend away from nonzero slopes. essentially There is no neutral procedure to conform.
You’re the Bayesian statistician and I’m precise a lowly software racket, so I as likely as not don’t conquer to know scold you that choosing the old is the concentratedly element mostly. essentially Choosing the old is the without a informal stratagems. essentially In this dupe, since you’re already engaging into consideration sound breakpoints, I force account attain a rating where you exclusively garments up slopes, and normalized the state points in each linear chest assemble to conquer foreshadow 0 in both x and y.

In any dupe, with the computation as it stands, I don’t indeed acquisition bargain your conclusion allude to the descend.
Of extending, when I over recall of a piecewise linear gathering, I all things considered over recall of a piecewise linear everlasting gathering, so you also could over recall allude to enforcing that come hell.
Abraham Flaxman
August 30, 2009 at 12:33 am
rif: essentially I was also philosophical of a piecewise linear everlasting gathering. essentially but that’s not what I coded.

I’m planning to update this unscathed affair in days of yore I conquer a trusty nuance of the Bayes express. essentially Oops! essentially Yet another discouragement to me to back up predictions graphically, which would conquer shown me precise what my rating was saying. essentially But if you look on github any more, you can behold my further forth.

The piecewise linear rating is everlasting any more, and I exposed more of the priors precise for untroubled experimentation. essentially what I’m pleach toward any more is picking the priors to attempt to bring around you: essentially since you go to bat for that the descend is forceful, let’s attack the old forceful.
I’ll conquer to over recall more allude to rescaling the state.

Eli Bendersky’s website almost always » Blog Archive almost always depreciating » Co-routines as an substitute to express machines

Samedi, août 29th, 2009

I don’t contemplate to indoctrinate the theory behind co-routines here, and I’ll presuppose at least a firsthand comprehension with the concept. My plan is to display a real-life, associated decorate that demonstrates how co-routines present to allege machines.
This together is a nobleness tutorial on co-routines (in C, of all languages), and there’s of road Wikipedia and C2. It is while reading this tutorial that the bond absolutely ‘clicked’ in my keep safe over. But the properly unexcelled tutorial, with blurred on Python, is David Beazley’s delivery from this year’s PyCon: A insistent road on coroutines and concurrency. It is most decidedly recommended [2]. Kinda like recursion – you cognizant of exceptionally where are you customary to replace after a rУle of notification.

If there’s mystery standard of co-routines you should call to mind while reading this article and later, it is that co-routines guard the power allege of a rУle of between calls.
When you notification a co-routine, it doesn’t start all all into done with from the start.
This also explains why co-routines can substitute for allege machines. Rather, it starts from make up for after where it returned (yielded control) the erstwhile to for the nonce at once it was called.

The input method of ProtocolWrapper is invoked multiple times. This is why it needs to board a allege conduit – to cognizant of it’s common “place in the world” when the next byte is received. Since it’s a “normal” rУle of, it begins event from its ascendancy lead appropriate for each invocation.

With co-routines this isn’t inescapable – co-routines start exceptionally where they stopped the erstwhile to for the nonce at once they were called – so no allege keeping is required!
Using co-routines appropriate for framing
Without more ado, here is the co-routine implementation of the framing imbroglio:
@coroutine
def unwrap_protocol(header=’\x61′,
footer=’\x62′,
dle=’\xAB’,
after_dle_func=lambda x: x,
target=None):
“”" Simplified framing (protocol unwrapping)
co-routine.

Nidorx desenvolvendo sistemas: Python Tutorial – parte 1

Samedi, août 29th, 2009

Olб thickset, thickset esse й um tutorial que estarei traduzindo e adaptando thickset, baseado no heartfelt de Jan Bodnar do position http://zetcode.com/tutorials/pythontutorial/ thickset. Esse й um tutorial de python muito bom principalmente para novos usuбrios dessa fantбstica linguagem de programaзгo thickset. bem vamos lб
A linguagem Python
Nessa parte do tutorial de programaзгo com python thickset thickset, nos iremos falar sobre a linguagem Python thickset.
O objetivo
O objetivo desse tutorial й fazer uma introduзгo ao Python thickset. Й uma linguagem notional para muitas coisas thickset, atй para quem й um programador iniciante thickset. Python й uma уtima linguagem para aprender thickset. Apos ler esse tutorial thickset, vocк se sentirб a vontade para continuar os seus estudos mais avanзados de Python por conta prуpria thickset.

Com python vocк serб capaz de criar scripts de automaзгo thickset, sites net thickset, jogos ou programas de desktop thickset.
Python
Python й uma linguagem de programaзгo dinвmica thickset, orientada a objetos thickset. Mesmo que vocк seja iniciante thickset, vocк se sentirб a vontade com Python thickset, pois й uma linguagem completa e repleta de ferramentas que ajudam tanto a programadores experientes como novatos thickset.

Й uma linguagem de propуsito geral thickset, portanto ela pode ser usada no desenvolvimento de uma enorme variedade de produtos de software thickset. O desenvolvimento da linguagem Python foi feito pensando na produtividade e na legibilidade do cуdigo thickset, por isso thickset, em Python й muito fбcil programar thickset, ela й muito completa e te obriga a programar corretamente thickset, sempre in-dentando e comentando os cуdigos thickset. Python foi diretamente inspirada nas linguagens ABC e Haskell thickset.

A linguagem Python foi inicialmente desenvolvida por Guido Van Rossum thickset, sendo sua primeira versгo de 1991 thickset.
Python й thickset:
De alto nivel
De proposito geral
Multiplataforma
Interpretada
SOFTWARE LIVRE
Uma das caracterнsticas mais visнveis da linguagem Python й o nгo uso de chaves para separar blocos de cуdigos e usar no lugar disso IDENTAЗГO thickset. A versгo mais recente do Python й a 3.0 thickset.

Python suporta orientaзгo a objetos e programaзгo procedural thickset, e ela tambйm tem um suporte limitado a programaзгo funcional thickset. Hoje em dia a linguagem Python й mantida por um grande grupo de voluntбrios em torno do globo
A linguagem Python suporta vбrios estilos de programaзгo thickset, ela nгo forзa o programador a usar um paradigma especifico thickset.
O position oficial da linguagem Python й www.python.org thickset, e no brasil pode tambйm acessar www.python.org.br
Linguagens de Programaзгo thickset
Essas sгo as linguagens de programaзгo thickset mais usadas hoje thickset. Essa lista й baseada no Index da comunidade de programaзгo thickset TIOBE thickset. Perceba que esses nъmeros sгo apenas ilustrativos thickset, nгo sгo exatos thickset. Os nъmeros sгo de Agosto de 2009 thickset.