text_a
stringlengths
9
150
text_b
stringlengths
18
20.9k
labels
int64
0
2
what do xyzs representation mean in python
pthis is a hrefhttpdocspythonorg27librarystdtypeshtmlstringformatting relnofollowstring formatting using keysap precodegtgtgt d answer 42 gtgtgt the answer is answerd d the answer is 42 codepre
2
given some small and big numbers make desired number without loops
pkeep in mind that you only have to reach the final size therefore it does not matter at all in which order you place the bricksp pthe next important idea then is to use 5inch bricks whenever possible you cover 5 inches if you use one of those as well as if you use 5 of the 1inch bricks hence using up just one brick is preferablep pnow youre already done really check the maxmium length you can create with your given 5inch bricks until you either run out of 5inch bricks or you have less than 5inch missing for your target length either way there is some distance missing which you will have to fill up with the remaining 1inch bricksp pi wont give any code here because its really a very simple problem and from what you have written above you should be easily able to solve it once you understand howp
2
can someone explain this conditional assignment
pfrom the a hrefhttpdocspythonorg2referenceexpressionshtmlbooleanoperations relnofollowdocumentationap blockquote pthe expression codex and ycode first evaluates codexcode if codexcode is false its value is returned otherwise codeycode is evaluated and the resulting value is returnedp pthe expression codex or ycode first evaluates codexcode if codexcode is true its value is returned otherwise codeycode is evaluated and the resulting value is returnedp blockquote pfurthermore any nonempty string is considered to be true when it appears in a boolean contextp pwith this we can tackle your questionp pdue to operator precedence rules the followingp precodestatus none and off or on codepre pis equivalent top precodestatus none and off or on codepre pthe first part codestatus none and offcode evaluates top ul licodefalsecode if codestatuscode is codenonecodeli licodeoffcode otherwiseli ul pthe entire expression codestatus none and off or oncode evaluates top ul licodeoncode if codestatuscode is codenonecodeli li<code>"off"</code> otherwise.</li> </ul> <p>an arguably more pythonic way to write this statement is:</p> <pre><code>result = "on" if status is none else "off" </code></pre>
2
scoping in python for loops
ppython does not have blocks as do some other languages such as cc or java therefore scoping unit in python is a functionp
2
pandas df pivottransformvectorize operation
puse codeunstackcode might be fasterp precodein 245 df1z 1 df1groupbyx ycountunstackfillna0 z y 8 9 12 34 45 57 x 254 0 0 0 0 0 1 300 0 0 1 1 1 0 850 1 0 0 0 1 0 1000 0 1 0 0 0 0 in 256 timeit pdcrosstabdf1x df1y 100 loops best of 3 872 ms per loop in 261 timeit df1z 1 df1groupbyx ycountunstackfillna0 100 loops best of 3 475 ms per loop in 262 timeit df1z 1 df1groupbyx ysumunstackfillna0 100 loops best of 3 488 ms per loop codepre
2
not all arguments converted during string formatting python
pfirst of all you need to change code4code to code4code because your items are string and convert the codejcode to int in codej3code also you need to parenthesis your comparison expression because the a hrefhttpsdocspythonorg3referenceexpressionshtmloperatorprecedence relnofollowprecedencea of codecode is higher than codecode and it will raise a codetypeerrorcode also if you want to preserve your result you can use a list comprehension p precodegtgtgt j for j in lijst if j14 intj3 gt 0 124576 795834 890432 codepre pif you just want to print the result you can use a usual loop with print functionp
2
vectorizing a multiplication and dict mapping on a pandas dataframe without iterating
phere is an option using codeapplycode and the codegetcode method for dictionary which returns codenonecode if the key is not in the dictionaryp precodedfc dfapplylambda r maskgetra if ra 1 else maskgetra 1 axis 1 dfb df a b c 0 1 1 32 1 2 2 64 2 2 3 96 3 4 4 400 4 nan 5 nan codepre
2
safe and lazy method invocations in pysidepyqt
pid recommend reading a hrefhttpelithegreenplacenet20110518codesamplesocketclientthreadinpython relnofollowthis posta for a general approach to interface threads with a pyqt gui the post discusses a thread that does socket io but this really is applicable to any thread specifically hardwareinterface threads usually also use io so this may be a good fitp pthe approach discussed is very generic using codequeuequeuecode and may seem like an overkill for simple tasks but i just want to call that function in a thread however once your application grows nontrivial you will appreciate it because it avoids any thread synchronization problems whatsoever and is very scalable ive personally used it to implement complex pyqt guis with sidethreads doing all kinds of stuffp
2
reverse marked substrings in a string
pits pretty simple with regular expressions coderesubcode takes a function as an argument to which the match object is passedp precodegtgtgt import re gtgtgt s hello ltwolfrevokcatsgt how ltt uoy eragtoday gtgtgt resubltgt lambda m mgroup11 s hello stackoverflow how are you today codepre pexplanation of the regexp pcodeltgtcode will match everything between codeltcode and codegtcode in matching group 1 to ensure that the regex engine will stop at the first codegtcode symbol occurrence the lazy quantifier codecode is usedp pthe function codelambda m mgroup11code that is passed to coderesubcode takes the match object extracts group 1 and reverses the string finally coderesubcode inserts this return valuep
2
how to programmatically catch which command failed on a try block
pyou can probably get that information from the members of the codekeyerrorcode exception object but a simpler way would be to just use codegetcode that will return a default value if the key is not therep precodereturn foo datagetfoo bar datagetbar codepre panother reason this is better than handling an exception is that you can only handle one exception what happens if two keys are missing and on top of that coderetdictcode will not even be defined in your example because the code failedp
2
greedy versus nongreedy matching in python re
pid recommend using a hrefhttpcodegooglecompyubikeypython relnofollowyubikeypythona for python interfacing to yubikey but thats a side and strictly pragmatical issuep pin theory there should be no cases where a choice between greedy and nongreedy causes a re to match in one case and fail in another it should only affects what gets matched and as you mention performance not whether the match succeeds at all since res are supposed to backtrack for the purposep pproblem is i cannot reproduce the problem i dont have a yubikey at hand and the tests in a hrefhttpcodegooglecompyubikeypythonsourcebrowsetrunktestpy relnofollowthis filea show no differences between the two res matchnomatch behaviorp pcould you please post a couple of failing examples where one matches and the other one doesnt ideally by editing your question so i can reproduce the problem and try to cut it down to its minimum sounds like there may be a re bug but without reproducible cases i cant check if and when its been fixed already reported or what thanksp pstrongeditstrong the op has now posted one failing example but i still cant reproducep precode py26 python 265 r26579359 mar 24 2010 013255 gcc 401 apple inc build 5493 on darwin type help copyright credits or license for more information gtgtgt import re gtgtgt r1 recompilertaz09cbdefghijklnrtuv18032tcbdefghijklnrtuv1832trn gtgtgt r2 recompilertaz09cbdefghijklnrtuv18032tcbdefghijklnrtuv1832trn gtgtgt noxvvbrentlnccnhgfgrtetilbvckjcegblehfvbihrdcui" &gt;&gt;&gt; r1.match(nox) &lt;_sre.sre_match object at 0xcc458&gt; &gt;&gt;&gt; r2.match(nox) &lt;_sre.sre_match object at 0xcc920&gt; &gt;&gt;&gt; </code></pre> <p>i.e., match succeeds in both cases, as it should -- and that's exactly the same 2.6.5 python version as the op is using. op, pls, show the results of this simple sequence of commands on your platform and tell us exactly what the platform is, since it looks like a weird platform-dependent bug... thanks!</p>
2
where is nonlocals
pfrom within running code you can easily get the names of the nonlocal variables but retriving their content in a way a call to codelocalscode gets you a dictionary is a bit trickierp pthe used codenonlocalcode variable names are stored in the current running code object in the cofreevars attributep pso getting the nonlocal names is a matter ofp pcodenames inspectcurrentframefcodecofreevarscodep pthe emcontentsem for these variables however are stored in the codeclosurecode attribute codefuncclosurecode in python 2 of the emfunction objectem instead not the code object the problem is that without aid from outside there is no easy way for a running code to get to the function object it is running on you can get to the frame object which links to the code object but there are no links back to the function object for a top level defined function one could explicitly use the function known name as used in the codedefcode statement but for an enclosed function that is returned to a caller there is no way of knowing its name eitherp pso one has to resort to a trick getting all the objects that link to the current code object by using the gc module garbage collector there is a codegcgetreferrerscode call it will return all the function objects that link to the code object one holds p pso inside a function with nonlocal variables one could dop precodeimport inspect gc def ab b1 2 def c nonlocal b1 print b code inspectcurrentframefcode names codecofreevars function func for func in gcgetreferrerscode if isinstancefunc functiontype0 nonlocals dict zipnames xcellcontents for x in functionclosure printnonlocals return inspectcurrentframe return c c a5 f c codepre pand therefore retrieve the names and values of the nonlocals strongbutstrong this wont work if you have more than one instance of that function around that is if the function of interested was created more than once with more than one call to the functin that generates it becasue all of those instances will link to the emsameem code object the example above assumes there is only one function running with the current code and would work correctly in this case another call to the factrory function would create another function with potentially other values for the nonlocal variables but with the same code object the codefunction code list genrator above would retrieve all of those and arbitrarily pick the first of thosep pthe correct function is the one on which the current code is executing i am trying to think of a way of retrieving this information but cant get to it if i can i will complete this answer but for now this cant help you to retrieve the nonlocals values values p <p>(just found out that trying to use "eval" with a nonlocal variable name won't work as well)</p> <p>it looks like that the only thing linking the current running frame to the function object where the nonlocal variables values are held is created at run time inside the native side of the python interpreter. i can't think of a way of getting to it short of using the ctypes module to look at interpreters data structures at runtime, which would, of course, be unsuitable for any actual production code.</p> <p>the bottom line: you can reliably retrieve the nonlocal variable names. but it looks like you can't get their value given their name as a string (nor rebind then).</p> <p>you could try opening a feature-request for a "nonlocals" call on python's bug tracker or on python-ideas mailing list.</p>
2
shoud globglob be preferred over oslistdir or the other way around
pboth are fine also consider codeospathwalkcode if you actually want to do something with that list rather then building the list for its own sakep
2
how can i split a long function into separate steps while maintaining the relationship between said steps
pjust wrap the three helper methods in a class and track which methods are allowed to run in an instancep precodeclass helperobject def initself selfa true selfb false selfc false def funcaself if not selfa raise errorcannot run funca now do stuff here selfa false selfb true return whatever def funcbself if not selfb raise errorcannot run funcb now do stuff here selfb false selfc true return whatever def funccself if not selfc raise errorcannot run funcc now do stuff here selfc false selfa true return whatever def func h helper hfunca hfuncb hfuncc etc codepre pthe only way to call a method is if its flag is true and each method clears its own flag and sets the next methods flag before exiting as long as you dont touch codehacode et al directly this ensures that each method can only be called in the proper orderp palternately you can use a single flag that is a reference to the function currently allowed to runp precodeclass helperobject def initself selfallowed selffunca def funcaself if selfallowed is not selffunca raise errorcannot run funca now do stuff selfallowed selffuncb return whatever etc codepre
2
adding field to sql table from django application
pyou really dont want to implement each questionanswer as a separate db fieldp pinstead make a table of questions and a table of answers and have a field in the answers table in general a codeforeignkeycode to indicate which question a given answer is associated withp
2
convert a python list with strings all to lowercase or uppercase
plist comprehensions is how id do it this snippet below shows how to convert a list to all upper case then back to lowerp precode python python 252 r25260911 dec 2 2008 092614 gcc 344 cygming special gdc 012 using dmd 0125 on cygwin type help copyright credits or license for more information gtgtgt list one two three gtgtgt list one two three gtgtgt list elementupper for element in list gtgtgt list one two three gtgtgt list elementlower for element in list gtgtgt list one two three codepre
2
read files from directory that has running script rather than calling directory location from where the script was called python
pif i understand your question correctly you want to know the directory of the running python filep pyou can access the special variable codefilecode inside a python program it returns the path of the python filep pto open a named file in the running scripts directory usep precodeimport os f openospathjoinospathdirnamefile filenametxt codepre
2
saving scrapy data to corresponding url in mysql
pfollow this stepsp padd a strongreviewurlstrong field into your strongcrawledscorestrong itemp precodeclass crawledscorescrapyitem reviewscore scrapyfield reviewcount scrapyfield reviewurl scrapyfield codepre psave strongresponse urlstrong into itemreviewurlp precodedef parseself response item crawledscore itemreviewscore responsexpathidavgratingspanaspantextre090 itemreviewcount responsexpathidsummarystarsatextre09 itemreviewurl responseurl yield item codepre pfinally on your pipelines file insert or update depending on your logicp pinsertp precodedef processitemself item spider try selfcursorexecuteinsert into scrapedscore count url values s s s itemreviewscore itemreviewcount itemreviewurl selfconncommit except mysqldberror e print error d s eargs0 eargs1 return item codepre pupdatep precodedef process_item(self, item, spider): try: self.cursor.execute("""update scraped set score=%s, count=%s where url=%s""", (item['reviewscore'], item['reviewcount'], item['reviewurl'])) self.conn.commit() except mysqldb.error, e: print "error %d: %s" % (e.args[0], e.args[1]) return item </code></pre>
2
when creating a model in django why does the class inherit modelsmodel instead of just model
pthis isnt a django question its a python questionp pif youre not familiar with the python way of doing things please read up on it before working in djangop pinvestigate pythons module and import concepts to learn about this a good place to start is the a hrefhttpdocspythonorg2tutorialmoduleshtml relnofollowmodules document in the python tutorialap pthe point is that codefrom djangodb import modelscode imports the codemodelscode module so that you have a variable in that scope named codemodelscode which is the models modulep pit is possible to have something like codefrom djangodbmodels import model charfieldcode but for django models the convention is to import the codemodelscode module rather than its componentsp
2
how do i access inherited variables from another module when they are changed in parent
h1apyh1 precodeavariable none class a def methodself global avariable avariable 100 print variable is avariable codepre hr h1bpyh1 precodeimport a class baa def mymethodself aamethod print avariable is aavariable if name main print aavariable bmymethod bmymethod codepre h1outputh1 precodenone variable is 100 avariable is 100 variable is 100 avariable is 100 codepre pyou get codenonecode all the time because once you import codeavariablecode you keep it in your own file but what codeapycode is changing is the codeavariablecode variable in its own file or more appropriately its own global namespace and thus you can see no changep pbut in the example above you can see the changes this is because we are importing the codeacode module itself and thus accessing all its objects everything in python is an object and thus when we call codeaavariablecode we are actually calling the codeavriablecode variable in codeacodes global namespacep h1edith1 pthe code below will still produce the same outputp precodeimport a class baa def mymethodself selfmethod print avariable is aavariable if name main print aavariable bmymethod bmymethod codepre
2
django sending email u around headers
plose the trailing commas herep precode elif formisvalid name formcleaneddataname sender formcleaneddatasender subject formcleaneddatasubject message formcleaneddatamessage codepre
2
whats the recommended way to unittest python gui applications
pare you sure you want to emunitem test the gui your example of complexity involves more than 1 unit and is therefore an integration testp pif you really want to unit test you should be able to instantiate a single class providing mocks or stubs for its dependencies then call methods on it like the gui framework would for eg a user click this can be tedious and you have to know exactly how the gui framework dispatches user input to your classesp pmy advice is to put even more stuff in models for your given example you could create a filtermanager which abstracts all the filterselectdisplay stuff behind a single method then unit test itp
2
installing pygame with easyinstall error
pcode sudo aptget install pythondev libsdlimage12dev libsdlmixer12dev libsdlttf20dev libsdl12dev libsmpegdev pythonnumpy subversion libportmididev ffmpeg libswscaledev libavformatdev libavcodecdev codep porp pcodesudo aptget install pythonpygamecodep
2
python platform independent way to modify path environment variable
psince comments cant contain formatting i have to put this in an answer but i feel like its an important point to make this is really a comment on a hrefhttpstackoverflowcomquestions1681208pythonplatformindependentwaytomodifypathenvironmentvariable16812561681256the comment about there being no equivalent to exportap pplease note that codeosenvironcode is not actually a dictionary its a special dictionaryemlikeem object which actually sets environment variables in the current process using a hrefhttpwwwopengrouporgonlinepubs009695399functionssetenvhtmlsetenvap precodegtgtgt osenvironclass ltclass osenviron at 0x100472050gt gtgtgt import os gtgtgt osenvironhello world gtgtgt osgetenvhello world codepre pthis means that codepathcode and other environment variables emwillem be visible to c code run in the same processp
2
multiple decorators for a view in django execution order
pto explain it a bit more i was also confused at first codeactiverequiredcode is applied first in a sense that it takes codemyviewcode and wraps it in some code then codeloginrequiredcode is applied and wraps the result in some more code p pbut when this wrapped version of codemyviewcode is actually invoked first the code added by codeloginrequiredcode is executed checking that youre logged in then the code added by codeactiverequiredcode is executed checking that youre active and then finally codemyviewcode is executedp
2
python creating a list from two other lists
puse codesetcodesp precodegtgtgt setlist2 setlist1 orange pink codepre
2
making a module global
peach of your codeexeccode calls happens in a separate namespace abandon this path it will only lead to ruinp
2
numpy double summation
pits always a good idea to precompute everything thats possible and never calculate anything twicep ol lijust invert the covariance once and store the inverted matricesli lialso precompute the normalization terms codepart1code and codepart2code only once rather than on every call of codegetgaussianvaluecodeli lino need to calculate codenpmatrixxmeancode twice dont know whether numpy optimizes it anywayli liconsider using numpys builtins like codescipystatsmultivariatenormalpdfcodeli ol
2
python dns resolver and original ttl
pyou can only get the original ttl by directly querying the authoritative server this is not pythonspecificp ol lifind out what the set of authoritative nameservers is by querying for codenscode records for the desired name if you find no ns records for the name then remove the first label and query again query the parent domain recursively repeat until you get some ns recordsli lionce you have ns records query emthoseem nameservers directly for the originally requested name in case one or more of these nameservers doesnt respond query the next one in the listli ol pthis is basically equivalent to doing part of the job of a recursive resolverp
2
use only some parts of django
pi myself use django for its objectdb mapping without using its urlconfigs simply create a file called codedjangosettingspycode and insert the necessary configuration for examplep precodedatabaseengine oracle databasehost localhost databasename orcl databaseuser scott databasepassword tiger codepre pthen in your regular python code dop precodeimport os osenvirondjangosettingsmodule djangosettings codepre pbefore you import any django modules this will let you use djangos objectdb mappings without actually having a django project so you can use it for standalone scripts or other web applications or whatever you wantp pas for caching if you dont want to use django then you should probably decide what you are using and go from there i recommend using cherrypy which doesnt use djangostyle regular expression url mapping but instead automatically maps urls to functions based on the function names theres an example right at the top of the cherrypy home page a hrefhttpcherrypyorghttpcherrypyorgap pcherrypy has its own caching system so you can accomplish exactly the same thing as what django does but without needing to use djangos urlconfig systemp
2
why is my if statement not comparing list items
pthe problem is that codeiscode compares identity and not equality of strings two short strings that are equal emmayem be identical due to some string interning cpython does but you generally should not build on this behavior instead use codecode to compare the emequalityem of stringsp pnote that you can do this a lot better using a hrefhttpdocspythonorg3librarystdtypeshtmlstrtranslate relnofollowcodestrtranslatecodea with a map created by a hrefhttpdocspythonorg3librarystdtypeshtmlstrmaketrans relnofollowcodestrmaketranscodeap precodegtgtgt table strmaketransabcdefghijklmopqrstuvwxyz cdefghijklmopqrstuvwxyzab gtgtgt hello worldtranslatetable jgooq yqtof codepre pyou can further use a hrefhttpdocspythonorg3librarystringhtmlstringasciilowercase relnofollowcodestringasciilowercasecodea so you dont need to type the alphabet yourself or use a hrefhttpdocspythonorg3librarystringhtmlstringasciiletters relnofollowcodestringasciiletterscodea for lower and upper case charactersp precodegtgtgt table strmaketransstringasciiletters stringasciiletters2 stringasciiletters2 gtgtgt hello world this workstranslatetable jgnnq yqtnf vjku yqtmu codepre
2
practice with threads in python
pif the sobel operator is cpubound then you wont get any benefit from multiple threads because python does not take advantage of multiple coresp pconceivably you could spin off multiple processes though im not sure if that would be practical for working on a single imagep p10 seconds doesnt seem like a lot of time to waste if youre concerned about time because youll be processing many images then it might be easier to run multiple processes and have each process deal with a separate subset of the imagesp
2
find largest number from selected list elements in python
precodegtgtgt thelist order 1 5 order 2 18 order 3 45 order 4 2 order 5 8 order 6 2 order 7 1 order 8 1 order 9 1 gtgtgt items zipiterthelist 3 gtgtgt items order 1 5 order 2 18 order 3 45 order 4 2order 5 8 order 6 2 order 7 1 order 8 1 order 9 1 gtgtgt maxitems keylambda x intx2 order 3 45 codepre
2
requests via a socks proxy
psocks support for requests is still pending if you want you can view my github repository here to see my branch of the socksipy library this is the branch that is currently being integrated into requests it will be some time before requests fully supports it thoughp pa hrefhttpsgithubcomanorovpysocks relnofollowhttpsgithubcomanorovpysocksap pit should work okay with urllib2 import codesockshandlercode in your file and follow the example inside of it youll want to create an opener like thisp precodeopener urllib2buildopenersocksipyhandlersocksproxytypesocks5 localhost 9050 codepre pthen you can use codeopeneropenurlcode and it should tunnel through the proxyp
2
extensions and libraries for django
pthe best place by far is a hrefhttpdjangopackagescom relnofollowhttpdjangopackagescoma it has a very novel approach to organizing apps its a great resource it has a grid system which makes it easy to compare apps with similar features its built on an a hrefhttpsgithubcomcartwheelwebpackaginator relnofollowopensource django projecta and it seems they will be launching a pythonpackagescom soon as wellp
2
how to debug long running python scripts or services remotely
pusing a hrefhttpwinpdborg relnofollowwinpdba you can attach to a running process like thisp ol lipinsert p precodeimport rpdb2 rpdb2startembeddeddebuggermypassword codepre pinside your scriptpli lilaunch your script through paster or uwsgi as usualli lirun winpdbli liclick fileattachli litype in password eg mypassword select the processli lito detach click filedetach the script will continue to run and can be attached to again laterli ol
2
django rest framework serializer relations how to get list of all child objects in parents serializer
pyou can implement this in two wayp ol lipwith codeserializermethodfieldcode your code became like thisp precodeclass parentserializerserializersmodelserializer childrenlist serializersserializermethodfieldgetchildren def getchildrenself obj serializer childserializerobjchildlist manytrue return serializerdata class meta model course fields urlidnamechildrenlist codepreli lipevery field could be attribute of model or a method so you can define a getchildrenlist method in codeparentcode model then call it in list of fields of codeparentserializercodep precodeclass parentserializerserializersmodelserializer class meta model course fields urlidnamegetchildrenlist codepreli ol pnote you need to inherits from codeserializersmodelserializercode in this scenariop
2
why do i get a memoryerror with itertoolsproduct
pit doesnt store intermediate emresultsem but it has to store the input values because each of those might be needed several times for several output valuesp psince you can only iterate once over an iterator codeproductcode cannot be implemented equivalent to thisp precodedef proda b for x in a for y in b yield x y codepre pif here codebcode is an iterator it will be exhausted after the first iteration of the outer loop and no more elements will be produced in subsequent executions of codefor y in bcodep pcodeproductcode works around this problem by storing all the elements that are produced by codebcode so that they can be used repeatedlyp precodedef proda b b tupleb create tuple with all the elements produced by b for x in a for y in b yield x y codepre pin fact codeproductcode tries to store the elements produced by all the iterables it is given even though that could be avoided for its first parameter the function only needs to walk over the first iterable once so it wouldnt have to cache those values but it tries to do anyway which leads to the codememoryerrorcode you seep
2
large amount of data in many text files how to process
phave a look at a hrefhttpdiscoprojectorg relnofollowdiscoa it is a lightweight distributed mapreduce engine written in about 2000 lines of erlang but specifically designed for python development it supports not only working on your data but also storing an replication reliably theyve just released version 03 which includes an indexing and database layerp
2
i keep getting the error message typeerror int object is not subscriptable in python
pint is a base type it is not a list or array so you cannot do int0p pstring would work but its hard to figure out if thats really what you want based on the tiny snippetp precodeguess strguess number strnumber if guess0 number0 codepre
2
get utc timestamp in python with datetime
pstrongwhat is a nave codedatetimecodestrongp pdefault codedatetimecode objects are said to be nave they keep time information without the time zone information think about nave codedatetimecode as a relative number ie code4code without a clear origin in fact your origin will be common throughout your system boundary think about aware codedatetimecode as absolute numbers ie code8code with a common origin for the whole worldp pwithout timezone information strongyou cannotstrong convert the naive datetime towards any nonnaive time representation where does code4code targets if we dont know from where to start this is why you cant have a codedatetimedatetimetoutctimestampcode method cf a hrefhttpbugspythonorgissue1457227httpbugspythonorgissue1457227ap pto check if your codedatetimecode codedtcode is nave check codedttzinfocode if codenonecode then its navep precodedatetimenow danger returns nave datetime pointing on local time datetime1970 1 1 returns nave datetime pointing on user given time codepre pstrongi have nave datetimes what can i do strongp pyou must make an assumption depending on your particular context the question you must ask yourself is was your codedatetimecode on utc or was it local time p ul lipstrongif you were using utcstrong you are out of troublep precodeimport calendar def dt2tsdt converts a datetime object to utc timestamp naive datetime will be considered utc return calendartimegmdtutctimetuple codepre/li> <li><p><strong>if you were not using utc</strong>, welcome to hell.</p> <p>you have to make your <code>datetime</code> non-naã¯ve prior to using the former function, by giving them back their intended timezone.</p> <p>you'll need <strong>the name of the timezone</strong> and <strong>the information about if dst was in effect</strong> when producing the target naã¯ve datetime (the last info about dst is required for cornercases):</p> <pre><code>import pytz ## pip install pytz mytz = pytz.timezone('europe/amsterdam') ## set your timezone dt = mytz.normalize(mytz.localize(dt, is_dst=true)) ## set is_dst accordingly </code></pre> <p><strong>consequences of not providing <code>is_dst</code></strong>:</p> <p>not using <code>is_dst</code> will generate incorrect time (and utc timestamp) if target datetime was produced while a backward dst was put in place (for instance changing dst time by removing one hour).</p> <p>providing incorrect <code>is_dst</code> will of course generate incorrect time (and utc timestamp) only on dst overlap or holes. and, when providing also incorrect time, occuring in "holes" (time that never existed due to forward shifting dst), <code>is_dst</code> will give an interpretation of how to consider this bogus time, and this is the only case where <code>.normalize(..)</code> will actually do something here, as it'll then translate it as an actual valid time (changing the datetime and the dst object if required). note that <code>.normalize()</code> is not required for having a correct utc timestamp at the end, but is probably recommended if you dislike the idea of having bogus times in your variables, especially if you re-use this variable elsewhere.</p> <p>and <strong>avoid using the following</strong>: (cf: <a href="http://stackoverflow.com/q/27531718/4279">datetime timezone conversion using pytz</a>)</p> <pre><code>dt = dt.replace(tzinfo=timezone('europe/amsterdam')) ## bad !! </code></pre> <p>why? because <code>.replace()</code> replaces blindly the <code>tzinfo</code> without taking into account the target time and will choose a bad dst object. whereas <code>.localize()</code> uses the target time and your <code>is_dst</code> hint to select the right dst object.</p></li> </ul> <p><strong>old incorrect answer</strong> (thanks @j.f.sebastien for bringing this up):</p> <p>hopefully, it is quite easy to guess the timezone (your local origin) when you create your naive <code>datetime</code> object as it is related to the system configuration that you would hopefully not change between the naive datetime object creation and the moment when you want to get the utc timestamp. this trick can be used to give an <strong>imperfect</strong> question.</p> <p>by using <code>time.mktime</code> we can create an <code>utc_mktime</code>:</p> <pre><code>def utc_mktime(utc_tuple): """returns number of seconds elapsed since epoch note that no timezone are taken into consideration. utc tuple must be: (year, month, day, hour, minute, second) """ if len(utc_tuple) == 6: utc_tuple += (0, 0, 0) return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0)) def datetime_to_timestamp(dt): """converts a datetime object to utc timestamp""" return int(utc_mktime(dt.timetuple())) </code></pre> <p>you must make sure that your <code>datetime</code> object is created on the same timezone than the one that has created your <code>datetime</code>.</p> <p><em>this last solution is incorrect because it makes the assumption that the utc offset from now is the same than the utc offset from epoch.</em> which is not the case for a lot of timezones (in specific moment of the year for the daylight saving time (dst) offsets).</p>
2
search and replace strings in a text file using wildcards
pyour life would be vastly improved with the use of a hrefhttpwwwregularexpressionsinfopythonhtml relnofollowregexesa you should be able to do this in 2 lines assuming i understand the problem correctlyp precodeimport re for line in fileinputinputfile inplace1 resubrvd4 v1000 line codepre
2
find substring in string but only if whole words
pheres a way to do it without a regex as requested assuming that you want any whitespace to serve as a word separatorp precodeimport string def findsubstringneedle haystack index haystackfindneedle if index 1 return false if index 0 and haystackindex1 not in stringwhitespace return false l index lenneedle if l lt lenhaystack and haystackl not in stringwhitespace return false return true codepre pand heres some a hrefhttpcodepadorgipovxnwh relnofollowdemo codea codepad is a great idea thanks to felix kling for reminding mep
2
integer overflow in numpy arrays
ppython integers dont have this problem since they automatically upgrade to python long integers when they overflowp pso if you do manage to overflow the int64s one solution is to use python ints in the numpy arrayp pprecodeimport numpy anumpyarange1000dtypeobject a20 precodep
2
numpy ceil and floor out argument
pcodeoutcode is the output emarrayem which must have the same shape as the inputp pif you construct it to be of the desired codedtypecode thatll be the codedtypecode you getp precodegtgtgt arr nparray55 72 gtgtgt out npemptylikearr dtypenpint64 gtgtgt npceilarr out array 6 7 dtypeint64 gtgtgt out array 6 7 dtypeint64 codepre
2
writing crawler that stay logged in with any server
ploggedin state is usually represented by cookies so what your have to do is to store the cookie information sent by that server on login then send that cookie with each of your subsequent requests as noted by aiden bell in his message thxp psee also this questionp pa hrefhttpstackoverflowcomquestions1016765howtousecookielibwithhttplibinpythonhow to quotkeepalivequot with cookielib and httplib in pythonap pa more comprehensive article on how to implement itp pa hrefhttpwwwvoidspaceorgukpythonarticlescookielibshtml relnofollowhttpwwwvoidspaceorgukpythonarticlescookielibshtmlap pthe simplest examples are at the bottom of this manual pagep pa hrefhttpsdocspythonorglibrarycookielibhtml relnofollowhttpsdocspythonorglibrarycookielibhtmlap pyou can also use a regular browser like firefox to log in manually then youll be able to save the cookie from that browser and use that in your crawler but such cookies are usually valid only for a limited time so it is not a longterm fully automated solution it can be quite handy for downloading contents from a web site once howeverp pstrongupdatestrongp pive just found another interesting tool in a recent questionp pa hrefhttpwwwscrapyorg relnofollowhttpwwwscrapyorgap pit can also do such cookie based loginp pa hrefhttpdocscrapyorgtopicsrequestresponsehtmltopicsrequestresponserefrequestuserlogin relnofollowhttpdocscrapyorgtopicsrequestresponsehtmltopicsrequestresponserefrequestuserloginap pthe question i mentioned is herep pa hrefhttpstackoverflow.com/questions/1804694/scrapy-domainname-for-spider">scrapy domain_name for spider</a></p> <p>hope this helps.</p>
2
windows installer for a python application created within linux
pive successfully used a hrefhttpwwwpyinstallerorg relnofollowpyinstallera running under wine to produce an executable which runs on windows set up your wine environment on linux putting a copy of pyinstaller in an appropriate location eg codedrivecpyinstaller20codep palso install python for windows in your wine environment you have to use the codemsiexeccode option run the python installerp precodewine msiexec i python266msi codepre pyou might also need to install other dependencies such as codepywin32codep pthen simply run pyinstaller on you spec filep precodewine cpython26pythonexe cpyinstaller20pyinstallerpy ltspecfilegt codepre pthis takes care of creating an executable which will run under windows packaging this exe as part of an installer is an additional task for which you could use nsis as suggested in other answers im not sure if nsis will successfully run under wine on linux so this only answers half of your questionp
2
not able to connect to https sites using urllib due to ssl error
pyou missed the codecode in the urisp precodeproxieshttp httpusernamepasswordipport proxieshttps httpsusernamepasswordipport codepre
2
how to add the current query string to an url in a django template
pto capture the queryparams that were part of the request you reference the dict that contains those parameters coderequestgetcode and urlencode them so they are acceptable as part of an href coderequestgeturlencodecode returns a string that looks like codedsampdatepublishedyear2008code which you can put into a link on the page like sop precodelta hrefsamelink requestgeturlencode gt codepre
2
using python to develop web application
pif you really dont want to delve into the frameworks and you should i heartily recommend django or pylons theres still need to go down the road of cgi this is a totally outofdate technology not to mention slow and inefficientp pthere emisem a standard way of building python web applications and its called a hrefhttpwwwwsgiorg relnofollowwsgia if you want to roll your own web app from scratch this is absolutely the way to gop pthat said if youre just starting out really you should go with one of the frameworksp
2
does python pil resize maintain the aspect ratio
pa hrefhttpstackoverflowcomquestions273946howdoiresizeanimageusingpilandmaintainitsaspectratiohow do i resize an image using pil and maintain its aspect ratioap pimageresize from pil will do exactly as told no behind scenes aspect ratio stuffp
2
python isprime function much slower after adding lookup of pregenerated list
pthe reason it is slower is because the list lookup is on instead of using lists use setsp precodeprimes set primesaddnum codepre pthe codenum in primescode check will be now o1p palso forget about this optimization codeprimes3code it actually slows down your code since it recreates the list note that it wont work anyway if you switch to setsp pfinally you can implement a hrefhttpenwikipediaorgwikisieveoferatosthenes relnofollowthe sieve of eratosthenesa although there are more sophisticated sieves to generate primes fastp
2
find all list permutations of a string in python
precodedef splitterstr for i in range1 lenstr start str0i end stri yield start end for split in splitterend result start resultextendsplit yield result combinations listsplitterstr codepre pnote that i defaulted to a generator to save you from running out of memory with long stringsp
2
how to make a numpy recarray with datatypes datetimefloat
pyou can use tuples instead of lists for the recordsp precodegtgt y datetimedatetime 20121111 21 datetimedatetime 20121112 31 datetimedatetime 20121113 01 gtgt nprecarrayy dtypetimestamp object xf recarraydatetimedatetime2012 1 1 1 1 20999999046325684 datetimedatetime2012 1 1 1 2 30999999046325684 datetimedatetime2012 1 1 1 3 010000000149011612 dtypetimestamp o8 x ltf4 codepre
2
python valueerror incomplete format upon printstuff thingy
pits expecting another character to follow the codecode in the string to tell it how to represent codevariablecode in the stringp puse codeone s variablecode or codeone formatvariablecode to correct the issuep
2
for loop with 2 iterators and 2 ranges
pinstead of codezipitx itycode you need to use codeitertoolsproductitx itycodep pcodezipcode iterates over two iterators in parallel operation known as a hrefhttpenwikipediaorgwikiconvolution28computerscience29 relnofollowconvolutiona yielding pairs of matching items and ending iteration when the shortest iterator is exhausted codeitertoolsproductcode iterates over the a hrefhttpenwikipediaorgwikicartesianproduct relnofollowemcartesian productema of the two iterators yielding pairs of all combinations of items from one and the other set the latter is what the codecode operator refers top pas martijn pieters pointed out manually calling codenextcode on the iterators is incorrect since codeforcode advances them itself and doing it yourself you end up only processing every second item of the iterable also codeiterrangecode is unnecessary simply use codexrangecode or coderangecode in python 3p
2
how do i get a list of function instances for a python source file
pyou can use a hrefhttpdocspythonorglibraryinspecthtml relnofollowinspecta modulep precodegtgtgt import inspect gtgtgt import example gtgtgt inspectgetmembersexample inspectisroutine funcone ltfunction funcone at 0x0238cbb0gt functhree ltfuncti three at 0x0240adb0gt functwo ltfunction functwo at 0x0240adf0gt codepre
2
accessing value inside nested dictionaries
pas always in python there are of course several ways to do it but strongthere is one obvious way to do itstrongp pcodetmpdictonetwothreecode emisem the obvious way to do itp pwhen that does not fit well with your algorithm that may be a hint that your structure is not the best for the problemp pif you just want to just save you repetative typing you can of course alias a subset of the dictp precodegtgtgt twodict tmpdictonetwo now you can just write twodict for tmpdictonetwo gtgtgt twodictspam 23 gtgtgt tmpdict one two three 10 spam 23 codepre
2
python threading can i make a list of thread queues
pyour approach is just fine the only thing i would change is making codeclientqueuescode a a hrefhttpstackoverflowcomquestions3506150staticclassmemberspythonstatic membera of codeclientthreadcode rather than a global variablep
2
typeerror str does not support the buffer interface
pfor python 3x you can convert your text to raw bytes throughp precodebytesmy data encoding codepre pfor examplep precodebytesattack at dawn utf8 codepre pthe object returned will work with codeoutfilewritecodep
2
check if value is between pair of values in a tuple
pno there is no dedicated syntax using chained comparisons is the right way to do this alreadyp pthe one nicety i can offer is to use tuple unpacking first but thats just readability icing herep precodelow high t if low lt val lt high codepre pif you are using a tuple subclass produced by a hrefhttpdocspythonorg2librarycollectionshtmlcollectionsnamedtuplecodecollectionnamedtuplecodea you could of course also use the attributes herep precodefrom collections import namedtuple rangetuple namedtuplerangetuple low high t rangetuple1 2 if tlow lt val lt thigh codepre
2
python generating a non repeating random pairs of numbers
pone way to think about this is there are codexcodecodeycode possible positions specifically codeboardsize boardsizecode in your case and you want to pick codencode codeselfbombnumcode random samples from those positions emwithout repetitionemp pthe a hrefhttpsdocspythonorg3libraryrandomhtmlrandomsample relnofollowcodesamplecodea function in the coderandomcode module does this perfectlyp precodepossiblecoordinates x y for x in rangex for y in range1 y1 bombcoordinates randomsamplepossiblecoordinates n codepre pcreating that list is a little wastefulbut given that codeboardsizecode is probably something small like 30 a temporary list of 900 elements is not worth worrying aboutp
2
how do i find common items from python dictionary values
pfor the sake of variety you could also use codereducecodep precodegtgtgt d a 1 2 3 b 2 4 5 c 1 2 7 gtgtgt reducelambda x y x amp y dvalues or use operatorand instead of lambda 2 codepre pa hrefhttpsdocspythonorg2libraryfunctionshtmlreduce relnofollowcodereducecodea is a builtin function in python 2x but needs to be imported from the a hrefhttpsdocspythonorg35libraryfunctoolshtml relnofollowcodefunctoolscodea module in python 3xp
2
keeping connections alive
pwhat you are describing is in essence a hrefhttpinfrequentlyorg200603cometlowlatencydataforthebrowser relnofollowcometa p
2
what on earth file permissions from files created by python c code
pthe function codeopencode takes three arguments if you specify the codeocreatcode flag you need to call it with this signaturep precodeint openconst char pathname int flags modet mode codepre potherwise the behaviour is undefined its very unlikely for the creation of the file in your first example to work at all also take a look at codeumaskcode which is always anded with the mode that you specifyp
2
how to format a shell command line from a list of arguments in python
pyou could use the undocumented but longstable at least a hrefhttpsvnpythonorgviewpythontrunklibsubprocesspyrevision37587ampviewmarkupsince oct 2004a codesubprocesslist2cmdlinecodep precodein 26 import subprocess in 34 argshello bobbity bob bye in 36 subprocesslist2cmdlineargs out36 hello bobbity bob bye codepre
2
django tuple object has no attribute strftime
pi added flattrue to the queryp precodeadesignlistvalueslistdatesubmitted flattrue codepre pwhich givesp precodedatetimedatetime2012 10 21 13 56 24 datetimedatetime2012 10 21 10 33 58 codepre pwhich then can be convertedp
2
how to simulate from an arbitrary continuous probability distribution
pas mentioned by francis youd better know the cdf of your distribution anyway scipy provides a handy way to define custom distributions it looks pretty much like thatp precodefrom scipy import stats class yourdistributionstatsrvcontinuous def pdfself x return sinx 075 432141 x 15 distribution yourdistribution distributionrvs codepre
2
sorting tuples in list using lambda function
pthe sorted method return a new sorted list it does not modify the existing list on the other hand listsort method sort the list inplacep precodet d2 b 1 a c 2 codepre pto sort this use eitherp precodet sortedt keylambda x x1 reversetrue codepre por p precodetsortt keylambda x x1 reversetrue codepre
2
reading and writing in python specific issue
pyou forgot a closing parenthesis on the codewritewritecode callp
2
does python have something like anonymous inner classes of java
pjava uses anonymous classes mostly to imitate closures or simply code blocks since in python you can easily pass around methods theres no need for a construct as clunky as anonymous inner classesp precodedef printstuff print hello def doitwhat what doitprintstuff codepre pedit im aware that this is not what is needed in this special case i just described the most common python solution to the problem most commonly by anonymous inner classes in javap
2
imap deleting messages
pthe following code prints some message header fields and then delete messagep precodeimport imaplib from emailparser import headerparser m imaplibimap4sslyourimapserver mloginyourusernameyourpassword get list of mailboxes list mlist select which mail box to process mselectinbox resp data muidsearchnone all search and return uids uids data0split mailparser headerparser for uid in uids respdata muidfetchuidbodyheader msg mailparserparsestrdata01 print msgfrommsgdatemsgsubject print muidstoreuid flags deleted print mexpunge mclose close the mailbox mlogout logout codepre
2
django populate isnt reentrant
pin the end the problem that i had was that i tried to run a second django app and did not have the following defined in my apache configp precodewsgidaemonprocess wsgiprocessgroup codepre pjust learned that you can run a single django app without defining them but when its two it produces a conflictp
2
how do python and php compare for ecommerce
pim personally a fan of python specificity with django for the web for ecommerce applications there is the a hrefhttpwwwsatchmoprojectcom relnofollowsatchmo projectap
2
upload raw json data on google cloud storage using python code
pin your example codecontentcode is a dict perhaps you want to use jsonp precodecontent jsondumpsname test codepre
2
pick a key from a dictionary python
pyou can iterate over the keys of a dict with a for loopp precodegtgtgt for key in yourdict gtgtgt printkey hi hello codepre pif you want them as a comma separated string you can use code joincodep precodegtgtgt print joinyourdict hi hello codepre hr blockquote pon a similar note is there a way to say mydictionarykeya hrefhttpdocspythonorgdevlibrarycollectionshtmlcollectionsordereddict relnofollow1a and that will return hip blockquote pno the keys in a dictionary are not in any particular order the order that you see when you iterate over them may not be the same as the order you inserted them into the dictionary and also the order could in theory change when you add or remove itemsp pif you need an ordered collection you might want to consider using another type such as a codelistcode or an a hrefhttpdocspythonorgdevlibrarycollectionshtmlcollectionsordereddict relnofollowcodeordereddictcodeap
2
django friendlier header for stackedinline for auto generated through model
pive never used an m2m field like this so thanks learned something newp pi found 2 ways to get around the problemp p1 simply reassign the codeunicodecode function with a new functionp precodeclass myinlineadmintabularinline mymodelm2mthroughunicode lambda x my new unicode model mymodelm2mthrough codepre p2 set up a a hrefhttpdocsdjangoprojectcomendevtopicsdbmodelsproxymodelsproxy modela for the m2mthrough model and use that model insteadp precodeclass mythroughmymodelm2mthrough class meta proxy true def unicodeself return my new unicode class myinlineadmintabularinline model mythrough codepre
2
generating file to download with django
pto trigger a download you need to set codecontentdispositioncode headerp precodefrom djangohttp import httpresponse from wsgirefutil import filewrapper generate the file response httpresponsefilewrappermyfilegetvalue contenttypeapplicationzip responsecontentdisposition attachment filenamemyfilezip return response codepre pif you dont want the file on disk you need to use codestringiocodep precodeimport cstringio as stringio myfile stringiostringio while notfinished generate chunk myfilewritechunk codepre poptionally you can set codecontentlengthcode header as wellp precoderesponsecontentlength myfiletell codepre
2
400 bad request while using djangotestclient
pyou can use the test client while debug is false you just need to add testserver into your allowedhosts settingp
2
compute sum with huge intermediate values
pyou can use a hrefhttpscodegooglecompgmpy relnofollowgmpy2a it has arbitrary precision floating point arithmetic with large exponent boundsp precodefrom future import division from gmpy2 import combmpfrfsum def mn return fsumcombnkmpfr1nmpfr1mpfrknmpfr2nkmpfrknk1 for k in xrange1n1 for i in xrange11000000100 print imi codepre phere is an excerpt of the outputp p2001 015857490038127975br 2101 015857582611615381br 2201 015857666768820194br 2301 015857743607577454br 2401 015857814042739268br 2501 015857878842787806br 2601 015857938657957615p pdisclaimer i maintain gmpy2p
2
selecting values from nonnull columns in a pyspark dataframe
pas always it is best to operate directly on native representation instead of fetching data to pythonp precodefrom pysparksqlfunctions import concatws coalesce lit trim def combinecols return trimconcatws coalescec lit for c in cols tblwithcolumnfoo combinefirstname lastname codepre
2
python removing tuples from a list of lists
precodegtgtgt a 1l 2l 3l 4l 5l gtgtgt a x00 for x in a gtgtgt a 1l 2l 3l 4l 5l codepre
2
how to stream stdoutstderr from a child process using asyncio and obtain its exit code after
pthe solution ive come up with so far uses a hrefhttpsdocspythonorg3libraryasyncioprotocolhtml relnofollowsubprocessprotocola to receive output from the child process and the associated transport to get the process exit code i dont know if this is optimal though ive based my approach on an a hrefhttpstackoverflowcoma20697159265261answer to a similar question by jf sebastianap precodeimport asyncio import contextlib import os import locale class subprocessprotocolasynciosubprocessprotocol def pipedatareceivedself fd data if fd 1 name stdout elif fd 2 name stderr text datadecodelocalegetpreferredencodingfalse printreceived from formatname textstrip def processexitedself loopstop if osname nt on windows the proactoreventloop is necessary to listen on pipes loop asyncioproactoreventloop asyncioseteventlooploop else loop asynciogeteventloop with contextlibclosingloop this will only connect to the process transport looprununtilcompleteloopsubprocessexec subprocessprotocol python c printhello async world0 wait until process has finished looprunforever printprogram exited with formattransportgetreturncode codepre
2
using pil to detect a scan of a blank page
pjust as a first try sort your image folder by file size if all scans from one document have the same resolution the blank pages will certainly result in smaller files than the nonblank ones p pi dont know how many pages you are scanning but if the number is low enough this could be a simple quick fixp
2
can you search backwards from an offset using a python regular expression
pusing positive lookbehind to make sure there are at least 30 characters before a wordp precode re like rwlt30 m rematchrwltd offset mystring if m print mgroup1 else print no match codepre pfor the other example negative lookbehind may helpp precodemynewstring looking feeding dancing prancing offset 16 m rematchrbwingltd offset mynewstring if m print mgroup1 codepre pwhich first greedy matches any character but backtracks until it fails to match 16 characters backwards codelt16codep
2
string replacement with dictionary complications with punctuation
phere is a way to do it with a single regexp precodein 24 d asapas soon as possible afaik as far as i know in 25 s i will do this asap afaik regards x in 26 resubrb joindkeys rb lambda m dmgroup0 s out26 i will do this as soon as possible as far as i know regards x codepre punlike versions based on codestrreplacecode this observes word boundaries and therefore wont replace abbreviations that happen to appear in the middle of other words eg etc in fetchp palso unlike most all other solutions presented thus far it iterates over the input string just once regardless of how many search terms there are in the dictionaryp
2
python matplotlib setarray takes exactly 2 arguments 3 given
pi think youre a bit confused on several thingsp ol liif youre trying to chance the x amp y locations youre using the wrong method codesetarraycode controls the emcolorem array for the collection that codescattercode returns youd use codesetoffsetscode to control the x amp y locations which method you use depends on the type of artist in questionli lithe two vs three arguments is coming in because codeartistsetarraycode is a method of an object so the first argument is the object in question li ol pto explain the first point heres a simple bruteforce animationp precodeimport matplotlibpyplot as plt import numpy as np x y z nprandomrandom3 100 pltion fig ax pltsubplots scat axscatterx y cz s200 for in range20 change the colors scatsetarraynprandomrandom100 change the xy positions this expects a single 2xn 2d array scatsetoffsetsnprandomrandom2100 figcanvasdraw codepre pto explain the second point when you define a class in python the first argument is the instance of that class conventionally called codeselfcode this is passed in behindthescenes whenever you call a method of an objectp pfor examplep precodeclass foo def initself selfx hi def sayhiself something print selfx something f foo note that we didnt define an argument but self will be passed in fsayhiblah this will print hi blah this will raise typeerror bar takes exactly 2 arguments 3 given fsayhifoo bar codepre
2
installing psycopg2 postgresql in virtualenv on windows
pedit this solution is outdated a hrefhttpstackoverflowcomquestions5382801wherecanidownloadbinaryeggswithpsycopg2forwindows53832665383266refer to this answera insteadp pi had the same problem following the suggestion on a hrefhttpwwwstickpeoplecomprojectspythonwinpsycopgthe download pagea of the windows port for getting it working on zope worked for me under virtualenv also in the nonvirtual installp ol lidownload the executable rename the exe extension to zipli liextract the file contentsli licopy the psycopg2 folder to myenvlibli licopy the egg to myenvlibsitepackagesli ol
2
is it possible getting all parameters of a field
pfor a model codemymodelcodep precodeclass mymodelmodelsmodel myfield modelscharfieldmaxlength100 codepre pyou can get the field using the a hrefhttpsdocsdjangoprojectcomen19refmodelsmeta relnofollowmeta apiap precodegtgtgt field mymodelmetagetfieldmyfield codepre pyou can then use the codedeconstructcode method to get the kwargs that were passed to the field when it was instantiatedp precodegtgtgt name path args kwargs fielddeconstruct gtgtgt printkwargs umaxlength 100 codepre
2
bound method responsejson of response 200
pactually you should call it since there is methodp precodedata requestsgeturljson codepre
2
problems with creating label in tkinter
pcodegame overnyou scored number pointscode is a tuple of three items but codetextcode probably expects a string instead and does strange things to arguments of other types use string concatenation or codeformatcode to provide a single stringp precodegameoverlabelroot textgame overnyou scored strnumber points fontarial black 26 bgred codepre por p precodegameoverlabelroot textgame overnyou scored pointsformatnumber fontarial black 26 bgred codepre
2
measure time elapsed in python
pthe python cprofile and pstats modules offer great support for measuring time elapsed in certain functions without having to add any code around the existing functionsp pfor example if you have a python script timefunctionspyp precodeimport time def hello print hello timesleep01 def thankyou print thank you timesleep005 for idx in range10 hello for idx in range100 thankyou codepre pto run the profiler and generate stats for the file you can just runp precodepython m cprofile o timestatsprofile timefunctionspy codepre pwhat this is doing is using the cprofile module to profile all functions in timefunctionspy and collecting the stats in the timestatsprofile file note that we did not have to add any code to existing module timefunctionspy and this can be done with any modulep ponce you have the stats file you can run the pstats module as followsp precodepython m pstats timestatsprofile codepre pthis runs the interactive statistics browser which gives you a lot of nice functionality for your particular use case you can just check the stats for your function in our example checking stats for both functions shows us the followingp precodewelcome to the profile statistics browser timestatsprofile stats hello lttimestampgt timestatsprofile 224 function calls in 6014 seconds random listing order was used list reduced from 6 to 1 due to restriction lthellogt ncalls tottime percall cumtime percall filenamelinenofunction 10 0000 0000 1001 0100 timefunctionspy3hello timestatsprofile stats thankyou lttimestampgt timestatsprofile 224 function calls in 6014 seconds random listing order was used list reduced from 6 to 1 due to restriction ltthankyougt ncalls tottime percall cumtime percall filenamelinenofunction 100 0002 0000 5012 0050 timefunctionspy7thankyou codepre pthe dummy example does not do much but give you an idea of what can be done the best part about this approach is that i dont have to edit any of my existing code to get these numbers and obviously help with profilingp
2
python ide on linux console
pusing emacs with pythonmode you can execute the script with cc ccp
2
how to split continuous data into groups
pfor numpy have a look at a hrefhttpdocsscipyorgdocnumpyreferencegeneratednumpyhistogramhtml relnofollowcodenphistogramcodea for the continuous data and a hrefhttpdocsscipyorgdocnumpyreferencegeneratednumpybincounthtmlnumpybincount relnofollowcodenpbincountcodea for the discrete datap pas a quick examplep precodeimport numpy as np data1 1 1 2 2 2 3 4 4 7 7 7 7 7 7 data2 nprandomnormalsize100 discretecounts npbincountdata1 discretevals nparangelendiscretecounts counts edges nphistogramdata2 codepre pif youd like to plot the results have a look at a hrefhttpmatplotliborgapipyplotapihtmlmatplotlibpyplothist relnofollowcodeplthistcodea and a hrefhttpmatplotliborgapipyplotapihtmlmatplotlibpyplotbar relnofollowcodepltbarcodeap pfor examplep precodeimport numpy as np import matplotlibpyplot as plt data1 1 1 2 2 2 3 4 4 7 7 7 7 7 7 data2 nprandomnormalsize100 fig axes pltsubplotsnrows2 counts npbincountdata1 vals nparangelencounts axes0barcounts vals aligncenter colorlightblue axes0settitlediscrete data axes[1].hist(data2, color='salmon') axes[1].set(title='continuous data') for ax in axes: ax.margins(0.05) ax.set_ylim(bottom=0) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/rcxot.png" rel="nofollow"><img src="http://i.stack.imgur.com/rcxot.png" alt="enter image description here"></a></p> <p>if you're using <code>pandas</code>, as @carsten mentioned, look at the <code>hist</code> function to plot the histogram (similar to <code>plt.hist</code>). however, the equivalent of <code>numpy.histogram</code> is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>pandas.cut</code></a>, which is extremely handy when you want the histogram counts (or want to group by a continuous range).</p>
2
ipython notebook pylab inline zooming of a plot
pat present the closest you can come is to redraw it at a larger size using the codefigsizecode function it expects dimensions in inches which caught me out the first time i tried to use itp pthere are some plants for a rich backend that would allow plots to be manipulated live using html5 but i think it will be a few more months before thats readyp pif youre using the notebook on your local computer for now the easiest option might be not to use inline mode so the plots pop up as separate windowsp
2
what does functoolswraps do
pi very often use classes rather than functions for my decorators i was having some trouble with this because an object wont have all the same attributes that are expected of a function for example an object wont have the attribute codenamecode i had a specific issue with this that was pretty hard to trace where django was reporting the error object has no attribute codenamecode unfortunately for classstyle decorators i dont believe that wrap will do the job i have instead created a base decorator class like sop precodeclass decbaseobject func none def initself func selffunc func def getattributeself name if name func return superdecbase selfgetattributename return selffuncgetattributename def setattrself name value if name func return superdecbase selfsetattrname value return selffuncsetattrname value codepre pthis class proxies all the attribute calls over to the function that is being decorated so you can now create a simple decorator that checks that 2 arguments are specified like sop precodeclass processlogindecbase def callself args if lenargs 2 raise exceptionyou can only specify two arguments return selffuncargs codepre
2
how to hide console window in python
psave it with a codepywcode extension and will open with codepythonwexecode double click it and python will start without a window p pfor example if you have the following script namep precodefoopy codepre prename it top precodefoopyw codepre
2
how to use python beautiful soup to get only the level 1 navigabletext
psomething likep precodefor anchor in tbodyfindalldiv styles1 text joinx for x in anchorcontents if isinstancex bs4elementnavigablestring codepre pworks just know that youll also get the line breaks in there so codestripcodeing might be necessaryp pfor examplep precodefor anchor in tbodyfindalldiv styles1 text joinx for x in anchorcontents if isinstancex bs4elementnavigablestring printtext printtextstrip codepre pprintsp precodeunnnhere is text 3 and this is what i wantn uhere is text 3 and this is what i want codepre pi put them in lists so you could see the newlinesp
2
how do i properly use connection pools in redis
predispy provides a connection pool for you from which you can retrieve a connection connection pools create a set of connections which you can use as needed and when done the connection is returned to the connection pool for further reuse trying to create connections on the fly without discarding them ie not using a pool or not using the pool correctly will leave you with way too many connections to redis until you hit the connection limit p pyou could choose to setup the connection pool in the init method and make the pool global you can look at other options if uncomfortable with global p precoderedispool none def init global pool printpid d initializing redis pool osgetpid redispool redisconnectionpoolhost10001 port6379 db0 codepre pyou can then retrieve the connection from a pool like thisp precoderedisconn redisredisconnectionpoolredispool codepre palso i am assuming you are using hiredis along with redispy as it should improve performance in certain cases have you also checked the number of connections open to the redis server with your existing setup as it most likely is quite high you can use the info commmand to get that informationp precoderediscli info codepre pcheck for the strongclientsstrong section in which you will see the strongconnectedclientsstrong field that will tell you how many connections you have open to the redis server at that instant p
2
what causes django to use 500html only 3 out of 6 times
pi would try restarting apache ive noticed inconsistencies in how urls are handled after any change this sounds very similar to a problem i had when a url would sometimes load on refreshp
2