text_a
stringlengths 9
150
| text_b
stringlengths 18
20.9k
| labels
int64 0
2
|
---|---|---|
python element order in dictionary | pas you are using django you could use codesorteddictcode a hrefhttpdocsdjangoprojectcomendevrefutilsdjangoutilsdatastructuressorteddict relnofollowdocsap
| 2 |
setting the fmt option in numpysavetxt | pyou can use the codefmtcode parameter in many ways here are some examples to give you some insightp
precodeimport numpy as np
a nparray11121314
21222324
codepre
p1 codenpsavetxttmptxta fmt13fcodep
precode11000 12000 13000 14000
21000 22000 23000 24000
codepre
p2 codenpsavetxttmptxta fmt04dcodep
precode0011 0012 0013 0014
0021 0022 0023 0024
codepre
pyou can also use to write expressions like note that the number of entries in the expression is the same as the number of columns in the arrayp
p3 codenpsavetxttmptxta fmt11f 11f 11f 11fcodep
precode110 120 130 140
210 220 230 240
codepre
| 2 |
python script doesnt terminates after a long time when its finished | pdont call codereadlinescode that loads the entire file into memory beforehand you can just iterate over codefcode directly and itll work finep
precodewith codecsopenhugefile r encodingutf8 as f
for line in f
codepre
| 2 |
prepending zeros to a list | pthis might work i have not tested it myself but i think it should be finep
precodedef addzerobinarylist
if lenbinarylist lt 8
zeros 0 8 lenbinarylist
return zeros binarylist
else
return binarylist
codepre
| 2 |
convert curl i user to python requests | pusep
precoderequestsgeturl authusername password
codepre
psee the section on a hrefhttpdocspythonrequestsorgenlatestuserauthenticationbasicauthenticationbasic authenticationa in the coderequestscode documentationp
| 2 |
python unhash value | pit cant be donep
pa hash is not a compressed version of the original value it is a number or something similar emderivedem from the original value the nature of hash implementations is that it is possible but statistically unlikely if the hash algorithm is a good one that two different objects produce the same hash valuep
pthis is known as the a hrefhttpenwikipediaorgwikipigeonholeprinciplepigeonhole principlea which basically states that if you have n different items and want to place them into m different categories where the n number is larger than m ie more items than categories youre going to end up with some categories containing multiple items since a hash value is typically much smaller in size than the data it hashes it follows the same principlesp
pas such it is impossible to go back once you have the hash value you need a different way of transporting data than thisp
pfor instance an example but not a very good one hash algorithm would be to calculate the number modulus 3 ie the remainder after dividing by 3 then you would have the following hash values from numbersp
precode1 gt 1 lt same hash number but different original values
2 gt 2
3 gt 0
4 gt 1 lt
codepre
pare you trying to use the hash function in this way in order top
ul
lisave space you have observed that the hash value is much smaller in size than the original datali
lisecure transportation you have observed that the hash value is difficult to reverseli
litransport data you have observed that the hash numberstring is easier to transport than a complex object hierarchyli
ul
p p
pknowing why you want to do this might give you a better answer than just emit cant be doneemp
pfor instance for the above 3 different observations heres a way to do each of them properlyp
ul
licompressiondecompression for instance using gzip or zlib the two typically available in most programming languagesruntimesli
liencryptiondecryption for instance using rsa aes or a similar secure encryption algorithmli
liserializationdeserialization which is code built to take a complex object hierarchy and produce either a binary or textual representation that later on can be deserialized back into new objectsli
ul
| 2 |
including nonpython files with setuppy | pstrongto accomplish what youre describing will take two stepsstrongp
ul
lithe file needs to be added to the source tarballli
lisetuppy needs to be modified to install the data file to the source pathli
ul
pstrongstep 1 to add the file to the source tarball include it in the manifeststrongp
pcreate a a hrefhttpdocspythonorgdistutilssourcedisthtmlthemanifestintemplatemanifesta template in the folder that contains setuppyp
pthe manifest is basically a text file with a list of all the files that will be included in the source tarballp
pheres what the manifest for my project look likep
ul
lichangelogtxtli
liinstalltxtli
lilicensetxtli
lipypreprocessorpyli
lireadmetxtli
lisetuppyli
litestpyli
litodotxtli
ul
pemnote while a hrefhttpdocspythonorgdistutilssourcedisthtmlmanifestsdist strongdoesstrong add some files automaticallya i prefer to explicitly specify them to be sure instead of predicting what it does and doesntemp
pstrongstep 2 to install the data file to the source folder modify setuppystrongp
psince youre looking to add a data file licensetxt to the source install folder you need to modify the data install path to match the source install path this is necessary because by default data files are installed to a different location than source filesp
pto modify the data install dir to match the source install dirp
ppull the install dir info from distutils withp
precodefrom distutilscommandinstall import installschemes
codepre
pmodify the data install dir to match the source install dirp
precodefor scheme in installschemesvalues
schemedata schemepurelib
codepre
pand add the data file and location to setup:</p>
<pre><code>data_files=[('', ['license.txt'])]
</code></pre>
<p><em>note: the steps above should accomplish exactly what you described in a standard manner without requiring any extension libraries.</em> </p>
| 2 |
can i get my instance of mechanizebrowser to stay on the same page after calling bformsubmit | pthe answer to my immediate question in the headline is yes with codemechanizebrowseropennovisitcode it works just like codeopencode but it doesnt change the state of the browser instance that is it will retrieve the page and your browser object will stay where it wasp
| 2 |
ordering shuffled points that can be joined to form a polygon in python | pi wrote a paper on a generalization of your problem long ago
there is a nice desription a hrefhttpwwwcsmcgillcacs644godfried2005fallsdroui9p0introductionhtmlherea created for a class in computational geometry
the generalization is that the algorithm works even if your polygon has holes see below
if it does not have holes it still works without modification
br nbspnbspnbspnbspnbsp
img srchttpistackimgurcombmwbbjpg altpolygon with holes
br p
blockquote
pj orourke uniqueness of orthogonal connectthedots emcomputational morphologyem gt toussaint editor elsevier science publishers bvnorthholland 1988 99104p
blockquote
| 2 |
convert an int to list of individual digitals more faster | pmaybe i am missing something but shouldnt this be enough without value checkingp
precodedef inttolisti
return intx for x in strizfill9
def listtointl
return intjoinstrx for x in l
codepre
pstrongreferencestrong a hrefhttpdocspythonorglibrarystdtypeshtmlstrzfill relnofollowcodestrzfillcodeap
| 2 |
python while loop wont stop | pbecause youre using codewhile truecode and codetruecode is always equal to true so this loop will never stop you can do something like thisp
precodewhile true
if p1 cg2
cg2 mnmx2 guess based on middle of highest and lowest
print computer has guessed d cg2
previousguessappendcg2
count21
else
print the computer has guessed it in d times count2
break use break to break the loop
codepre
por just like thisp
precodewhile p1 cg2
cg2 mnmx2 guess based on middle of highest and lowest
print computer has guessed d cg2
previousguessappendcg2
count21
codepre
pif codep1 cg2code is equal to false this loop will terminatedp
| 2 |
multivariate normal density in python | pif still needed my implementation would bep
precodeimport numpy as np
def pdfmultivariategaussx mu cov
caculate the multivariate normal density pdf
keyword arguments
x numpy array of a d x 1 sample vector
mu numpy array of a d x 1 mean vector
cov numpy array of a d x d covariance matrix
assertmushape0 gt mushape1 mu must be a row vector
assertxshape0 gt xshape1 x must be a row vector
assertcovshape0 covshape1 covariance matrix must be square
assertmushape0 covshape0 covmat and muvec must have the same dimensions
assertmushape0 xshape0 mu and x must have the same dimensions
part1 1 2 nppilenmu2 nplinalgdetcov12
part2 12 xmutdotnplinalginvcovdotxmu
return floatpart1 npexppart2
def testgausspdf
x nparray00
mu nparray00
cov npeye2
printpdfmultivariategaussx mu cov
prints 015915494309189535
if name main
testgausspdf
codepre
pin case i make future changes the code is a hrefhttpsgithubcomrasbtpythonreferenceblobmasterusefulscriptsmultivariategaussianpdfpy relnofollowhere on githubap
| 2 |
python adding variable as value in a dict | pyou may either p
precoded
dname yourname
codepre
porp
precoded name yourname
codepre
pboth would workp
| 2 |
prime numbers which can be written as sum of the squares of two numbers x and y | pdo not check whether each number is prime precompute all the prime numbers in the range using a hrefhttpsenwikipediaorgwikisieveoferatosthenes relnofollowsieve of eratosthenesa this will greatly reduce the complexityp
psince you have maximum of 200m numbers and 256mb memory limit and need at least 4 bytes per number you need a little hack do not initialize the sieve with all numbers up to codeycode but only with numbers that are not divisible by 2 3 and 5 that will reduce the initial size of the sieve enough to fit into the memory limitp
pstrongupdstrong as correctly pointed out by will ness in comments sieve contains only flags not numbers thus it requires not more than 1 byte per element and you dont even need this precomputing hackp
| 2 |
which python testing framework to use | pa hrefhttpnosereadthedocsorgenlatestnosea does all of this just codecdcode to the root of your tree of python files and runp
precodenosetests
codepre
pnose a hrefhttpnosereadthedocsorgenlatestfindingtestshtmlfinds test filesa using a a hrefhttpnosereadthedocsorgenlatestwritingtestshtmlregexa basically the word codetestcode or codetestcode present in the namep
blockquote
pif it looks like a test its a test names of directories modules
classes and functions are compared against the testmatch regular
expression and those that match are considered tests any class that
is a unittesttestcase subclass is also collected so long as it is
inside of a module that looks like a testp
blockquote
| 2 |
proper use of list comprehensions python | pfrom python documentationp
blockquote
pa hrefhttpdocspythonorgtutorialdatastructureshtml relnofollowlist comprehensions provide a concise way to create lists common
applications are to make new listsap
blockquote
pperhaps you want to learn more about a hrefhttpdocspythonorglibraryfunctionshtmlreduce relnofollowreducea a hrefhttpdocspythonorglibraryfunctionshtmlfilter relnofollowfiltera and a hrefhttpdocspythonorglibraryfunctionshtmlmap relnofollowmapa functionsp
| 2 |
is something wrong with my python 332 | pyou need to indent your code properlyp
precodegtgtgt temperature 70
gtgtgt if temperature gt 60 and temperature lt 75
printjust right
else
printoh no
just right
codepre
pemwhen you indent it properly the codecode will automatically show up so dont type those inemp
punlike most languages in python indentation is important it is how the python interpreter indentifies emblocks of codeem you might hear the phrase whitespace is significant it means the same thing whitespace means things you type that dont print like spaces the tab character etcp
pso you should always line up the identifier of blocks of code lines that end with codecode at the left margin it is not important how many spaces you indent the body of these blocks of code in your example the print function is in the body of the if statement as long as there is one space python will work however the standard is to use 4 spaces so better get into the habit putting four spaces whenever you want to indent codep
| 2 |
is there an uptodate fast yaml parser with python bindings | pthe linked wiki page states after the warning use libyaml c and pyyaml python although the note does have a bad wikilink should be codepyyamlcode not codepyyamlcodep
pas for performance depending on how you installed pyyaml you should have the cparser class available which implements a yaml parser written in optimized c while i dont think this gets around the gil issue it is markedly faster here are a few cursory benchmarks i ran on my machine amd athlon ii x4 640 30ghz 8gb ramp
pfirst with the default purepython parserp
precode usrbinpython2 m timeit s import yaml yfilelargeyaml rread
yamlloady
10 loops best of 3 405 msec per loop
codepre
pwith the cparserp
precode usrbinpython2 m timeit s import yaml yfilelargeyaml rread
yamlloady loaderyamlcloader
10 loops best of 3 592 msec per loop
codepre
pand for comparison with pypy using the purepython parserp
precode pypy m timeit s import yaml yfilelargeyaml rread
yamlloady
10 loops best of 3 101 msec per loop
codepre
pfor codelargeyamlcode i just googled for large yaml file and came across this p
pa hrefhttpsgistgithubcomnrh667383raw1b3ba75c939f2886f63291528df89418621548fdlargeyamlhttpsgistgithubcomnrh667383raw1b3ba75c939f2886f63291528df89418621548fdlargeyamlap
pi had to remove the first couple of lines to make it a singledoc yaml file otherwise yamlload complainsp
peditp
panother thing to consider is using the codemultiprocessingcode module instead of threads this gets around gil problems but does require a bit more boilerplate code to communicate between the processes there are a number of good libraries available though to make multiprocessing easier. there's a pretty good list of them <a href="http://wiki.python.org/moin/parallelprocessing">here</a>.</p>
| 2 |
sqlalchemy commit changes to object modified through dict | pthe problem does not reside in sqlalchemy but is due to pythons a hrefhttpdocspythonorg2howtodescriptorhtml relnofollowdescriptors mechanisma every codecolumncode attribute is a descriptor this is how sqlalchemy hooks the attribute retrieval and modification to produce database requestsp
plets try with a simpler examplep
precodeclass descobject
def getself obj typenone
print get
def setself obj value
print set
class aobject
desc desc
a a
adesc prints get
adesc 2 prints set
codepre
phowever if you go through codeacode eminstanceem dictionary and set another value for codedesccode you bypass the descriptor protocol see a hrefhttpdocspythonorg2referencedatamodelhtmlinvokingdescriptors relnofollowinvoking descriptorsap
precodeadictdesc 0 does not print anything
codepre
phere we just created a new eminstanceem attribute called codedesccode with a value of 0 the codedescsetcode method was never called and in your case sqlalchemy wouldnt get a chance to catch the assignmentp
pthe solution is to use a hrefhttpdocspythonorg2libraryfunctionshtmlsetattr relnofollowcodesetattrcodea which is exactly equivalent to writing codeadesccodep
pre><code>setattr(a, 'desc', 1) # prints '__set__'
</code></pre>
| 2 |
easiest way to turn a list into an html table in python | pi would decompose your problem into two partsp
ul
ligiven a flat list produce a list of sublists where the sublists are of a given length and the overall list may be walked into either a row major order your first and third example or column major your second exampleli
ligiven a list of sublists with string items produce an html table out of itli
ul
pi think the two tasks are really very distinct and theres nothing to gain and much to lose in mushing them up so i would be astonished if any welldesigned library did such mushingp
pfor point 1 rowmajor is easyp
precodedef rowmajoralist sublen
return alistiisublen for i in range0 lenalist sublen
codepre
pand columnmajor not that badp
precodedef colmajoralist sublen
numrows lenalistsublen1 sublen
return alistisublen for i in rangenumrows
codepre
pfor examplep
precodel onetwothreefourfivesixseveneightnine
for r in rowmajorl 3 print r
print
for r in colmajorl 3 print r
for r in rowmajorl 4 print r
codepre
pproduces your three desired results one list per row not in html form yetp
pthe second half of the problem produce an html table from a list of lists of stringsp
precodedef htmltablelol
print lttablegt
for sublist in lol
print lttrgtlttdgt
print lttdgtlttdgtjoinsublist
print lttdgtlttrgt
print lttablegt;'
</code></pre>
<p>if you want to get it as a single string rather than print it out, change each <code>print</code> into <code>yield</code> and use <code>'\n'.join(html_table(lol))</code>.</p>
<p>now you have two simple, useful, usable and reusable building blocks -- having them separate will come in handy whenever you want to present your data as anything but an html table, and also whenever the list-of-lists to present as an html table comes from any other way of building it. putting them together is easy to do in your application code, but of course it's also easy to do a simple "glue routine", e.g., assuming the <code>yield</code>-based version of <code>html_table</code> and that a single string result is desired:</p>
<pre><code>def list_to_html_table(alist, sublength, column_major=false):
if column_major:
lol = col_major(alist, sublength)
else:
lol = row_major(alist, sublength)
return ''.join(html_table(lol))
</code></pre>
<p>isn't this building-blocks approach really nicer and more pleasant, as well as more productive, than programming in terms of big blobs of mushed-up glue...?-)</p>
| 2 |
when to use osname sysplatform or platformsystem | pit depends on whether you prefer raising exception or trying anything on an untested system and whether your code is so high level or so low level that it can or cant work on a similar untested system eg untested mac posix or on embedded arm systems more pythonic is to not enumerate all known systems but to test possible relevant properties eg it is considered important the endianess of the system but unimportant multiprocessing propertiesp
ul
liposname is a sufficient resolution for the correct usage of codeoscode module possible values are posix nt os2 ce or riscos where probably only the first two are mostly importantpli
lipsysplatform is a finer resolution it is recommended to use codeif sysplatformstartswithlinuxcode idiom because linux2 means a linux kernel version 2xx or 3 older kernels are currently never used in python 33 are all linux systems simple linux pli
ul
pi do not know the specifics of mac and java systems and so i can not use the results of very good method platformsystem for branching but i would use advantages of the codeplatformcode module for messages and error loggingp
| 2 |
pandas random order of columns when writing dataframe to csv | ppython dictionaries are essentially a hrefhttpsdocspythonorg2tutorialdatastructureshtmldictionariesunorderedap
pyou can explicitly order the columns like thisp
precodedf dfabc
codepre
| 2 |
how to make string indices circular when string index out of range | pyou just need to do codemystringltindexgt lenmystringcode codeltindexgtcode would be any integer that will be an indexp
pfor examplep
precodemystring26 lenmystring
gtgtgt a
codepre
| 2 |
does comparing using compare identities before comparing values | pfor userdefined class instances codeiscode is used as a fallback where the default codeeqcode isnt overridden codea bcode is evaluated as codea is bcode this ensures that the comparison will always have a result except in the codenotimplementedcode case where comparison is explicitly forbiddenp
pthis is somewhat obliquely good spot a hrefhttpstackoverflowcomusers279627svenmarnachsven marnacha referred to in the a hrefhttpsdocspythonorg3referencedatamodelhtmlobjecthash relnofollowdata model documentationa emphasis minep
blockquote
puserdefined classes have codeeqcode and codehashcode methods by
default with them strongall objects compare unequal except with
themselvesstrong and codexhashcode returns an appropriate value such
that codex ycode implies both that codex is ycode and codehashx hashycodep
blockquote
hr
pyou can demonstrate it as followsp
precodegtgtgt class unequalobject
def eqself other
return false
gtgtgt ue unequal
gtgtgt ue is ue
true
gtgtgt ue ue
false
codepre
pso codeeqcode must be called before codeidcode butp
pre<code>>>> class noequal(object):
pass
>>> ne = noequal()
>>> ne is ne
true
>>> ne == ne
true
</code></pre>
<p>so <code>id</code> must be invoked where <code>__eq__</code> isn't defined.</p>
<hr>
<p>you can see this <a href="https://hg.python.org/cpython/file/tip/objects/object.c#l679" rel="nofollow">in the cpython implementation</a>, which notes:</p>
<pre class="lang-c prettyprint-override"><code>/* if neither object implements it, provide a sensible default
for == and !=, but raise an exception for ordering. */
</code></pre>
<p>the <em>"sensible default"</em> implemented is a c-level equality comparison of the pointers <code>v</code> and <code>w</code>, which will return whether or not they point to the same object.</p>
| 2 |
why this list comprehension is faster than equivalent generator expression | pi believe the difference here is entirely in the cost of 1000000 additions testing with 64bit pythonorg 330 on mac os xp
precodein 698 timeit len none for n in range 1 1000000 if n3 1
10 loops best of 3 127 ms per loop
in 699 timeit sum 1 for n in range 1 1000000 if n3 1
10 loops best of 3 138 ms per loop
in 700 timeit sum 1 for n in range 1 1000000 if n3 1
10 loops best of 3 139 ms per loop
codepre
pso its not that the comprehension is faster than the genexp they both take about the same time but calling codelencode on a codelistcode is instant while summing 1m numbers adds another 7 to the total timep
pthrowing a few different numbers at it this seems to hold up unless the list is very tiny in which case it emdoesem seem to get faster or large enough that memory allocation starts to become a significant factor which it isnt yet at 333kp
| 2 |
matplotlib change colormap after the fact | puse the codeupdatecolorscode to update the colors of all linesp
precodeimport pylab as pl
import numpy as np
cm plgetcmaporrd
x nplinspace0 1 100
def updatecolorsax
lines axlines
colors cmnplinspace0 1 lenlines
for line c in ziplines colors
linesetcolorc
fig ax plsubplots
for i in range10
axplotx x1i01
updatecolorsax
codepre
| 2 |
python leaking memory while using pyqt and matplotlib | pthe pyplot interface is meant for easy interactive use but for embedding in an application the objectoriented api is better for example pyplot keeps track of all figures you have created your codeplotclosefigurecode emshouldem get rid of them but maybe it doesnt get executed try putting it inside codefinallycode or reusing the same figure objectp
psee a hrefhttpmatplotlibsourceforgenetexamplesuser5finterfacesembedding5fin5fqt4htmlthis examplea of embedding matplotlib in a pyqt4 application using the objectoriented api its more work but since everything is explicit you shouldnt get memory leaks from the behindthescenes automation that pyplot doesp
| 2 |
wrote a function to determine if a number is a positive integer and it returns true for negative numbers | pthis all seems needlessly complicated and using codeevalcode on coderawinputcode is a security risk the user can enter anything they likep
pinstead try something likep
precodedef isoks
try
i ints
except valueerror
return false false
else
return true i gt 0
codepre
pexample inputs and outputsp
precodegtgtgt for s in foo 9 9
print s isoks
foo false false
9 true true
9 true false
codepre
hr
pyour error is herep
precodeif x gt 0
codepre
premember codexcode is still a string and in python 2x all strings will compare codegt 0codep
| 2 |
pygame animation using mutiple images overlappingnot working | pstrongbtwstrong your code could look like thisp
pi use my images in example but there are still lines with your imagesp
pi use timer to change imagesbr
you can press space to pause and escape to exit p
petcp
precodeimport pygame
class sprite
def initself x y currentime
selfrect pygamerectx y 100 110
selfimages
for x in range12
for x in range14
img pygameimageloadball strx png
img pygameimageloadcuserstrevorskydrivedocumentstest20sprite strx png
selfimagesappend img
selfcurrentimage 0
selftimenum 100 miliseconds
selftimetarget currentime selftimenum
def updateself currentime
if currentime gt selftimetarget
selftimetarget currentime selftimenum
selfcurrentimage 1
if selfcurrentimage lenselfimages
selfcurrentimage 0
def renderself window
windowblitselfimagesselfcurrentimage selfrect
--------------------------------------------------------
# constans - uppercase
black = (0 ,0 ,0 )
white = (255,255,255)
#----------------------------------------------------------------------
# main
def main():
pygame.init()
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("test2")
move_x, move_y = 0, 0
clock = pygame.time.clock()
curren_time = pygame.time.get_ticks()
player = sprite(110,100, curren_time)
font = pygame.font.sysfont(none, 150)
pause_text = font.render("pause", 1, white)
pause_rect = pause_text.get_rect( center = window.get_rect().center ) # center text on screen
# mainloop
state_game = true
state_pause = false
while state_game:
curren_time = pygame.time.get_ticks()
# events
for event in pygame.event.get():
if event.type == pygame.quit:
state_game = false
elif event.type == pygame.keydown:
if event.key == pygame.k_escape:
state_game = false
elif event.key == pygame.k_space:
state_pause = not state_pause
if event.key == pygame.k_left:
move_x = -3
elif event.key == pygame.k_right:
move_x = 3
elif event.key == pygame.k_up:
move_y = -3
elif event.key == pygame.k_down:
move_y = 3
elif event.type == pygame.keyup:
if event.key in (pygame.k_left, pygame.k_right):
move_x = 0
elif event.key in (pygame.k_up, pygame.k_down):
move_y = 0
# moves
if not state_pause:
player.rect.x += move_x
player.rect.y += move_y
player.update(curren_time)
# draws
window.fill(black)
player.render(window)
if state_pause:
window.blit(pause_text, pause_rect)
pygame.display.flip()
# fps
clock.tick(50)
# the end
pygame.quit()
#----------------------------------------------------------------------
if __name__ == '__main__':
main()
</code></pre>
<p><img src="http://i.stack.imgur.com/k6dvy.png" alt="enter image description here"></p>
<p><img src="http://i.stack.imgur.com/ntj2k.png" alt="ball1.png"> ball1.png
<img src="http://i.stack.imgur.com/zfoed.png" alt="ball2.png"> ball2.png
<img src="http://i.stack.imgur.com/sjzut.png" alt="ball3.png"> ball3.png</p>
| 2 |
calculating minimum length among the lists inside a list | pa few optionsp
precodea 10121113111111 311451111 11678
print mina keylen
1 1 6 7 8
print lenmina keylen
5
print minmaplen a
5
codepre
| 2 |
python error unsupported operand types for int and datetimetimedelta | pcodeoffsetcode is a a hrefhttpsdocspythonorg2librarydatetimehtmldatetimetimedelta relnofollowcodedatetimetimedeltacode objecta if you need just the seconds extract them with a hrefhttpsdocspythonorg2librarydatetimehtmldatetimetimedeltatotalseconds relnofollowcodetimedeltatotalsecondscodeap
precodereturn utcdatetime offsettotalseconds
codepre
pyour emfunction signatureem however suggests it was expecting you to feed it a codedatetimedatetimecode object in which case you shouldnt change this function but the code that calls it clearly you are giving it an integer insteadp
| 2 |
python 27 string substitution using multiple dictionaries | pyou can use codedictdict1 dict2codep
precodegtgtgt dict1 foo bar
gtgtgt dict2 car vroom
gtgtgt dictdict1 dict2
car vroom foo bar
gtgtgt print value 1 is foos and value 2 is cars dictdict1 dict2
value 1 is bar and value 2 is vroom
codepre
| 2 |
sqlite sqlalchemy how to enforce foreign keys | pbuilding on the answers from conny and shadowmatter heres code that will check if you are using sqlite3 before emitting the pragma statementp
precodefrom sqlalchemy import event
from sqlalchemyengine import engine
from sqlite3 import connection as sqlite3connection
eventlistensforengine connect
def setsqlitepragmadbapiconnection connectionrecord
if isinstancedbapiconnection sqlite3connection
cursor dbapiconnectioncursor
cursorexecutepragma foreignkeyson
cursorclose
codepre
| 2 |
append operation in hadoop webhdfs client | passuming your user name is codehdfscode add codeampusernamehdfscode to your url write operations require a valid user p
pyour java code works because it pulls your user information from the unix environment p
pif you see the user codedrwhocode anywhere its probably because you havent set a codeusernamecode in your request p
| 2 |
how to update mysql with python where fields and entries are from a dictionary | pyou dont want to be putting literal values in using string interpolation sql injection attacks are strongnot a good thingtmstrong instead you use the placeholder syntax relevant for your database i think mysqls is sp
pemnote im using codeformatcode here change to use if you want but escape any semp
precoded col1 val1 col2 val2
sql update table set format joinsformatk for k in d
print sql
update table set col2s col1s
codepre
passuming codecurcode is a db cursor the correct way to perform the query isp
precodecurexecutesql dvalues
codepre
pthis works because although the ordering of a dictionary is effectively arbitrary order the order of keysvalues of a dict will be consistent such that codedictzipdkeys dvalues dcodep
| 2 |
ensure a single instance of an application in linux | pthis builds upon the a hrefhttpsstackoverflowcoma221159832230answera by user a hrefhttpsstackoverflowcomusers12138zgodazgodaa it mainly addresses a tricky concern having to do with write access to the lock file in particular if the lock file was first created by coderootcode another user codefoocode can then no successfully longer attempt to rewrite this file due to an absence of write permissions for user codefoocode the obvious solution seems to be to create the file with write permissions for everyone this solution also builds upon a different a hrefhttpsstackoverflowcoma15015748832230answera by me having to do creating a file with such custom permissions this concern is important in the real world where your program may be run by any user including coderootcodep
precodeimport fcntl os stat tempfile
appname myapp lt customize this value
establish lock file settings
lfname lockformatappname
lfpath ospathjointempfilegettempdir lfname
lfflags osowronly osocreat
lfmode statsiwusr statsiwgrp statsiwoth this is 0o222 ie 146
create lock file
regarding umask see httpsstackoverflowcoma15015748832230
umaskoriginal osumask0
try
lffd osopenlfpath lfflags lfmode
finally
osumaskumaskoriginal
try locking the file
try
fcntllockflffd fcntllockex fcntllocknb
except ioerror
msg error may already be running only one instance of it
can run at a time
formatappname
exitmsg
codepre
pa limitation of the above code is that if the lock file already existed with unexpected permissions those permissions will not be correctedp
pi wouldve liked to use codevarrunltappnamegtcode as the directory for the lock file but creating this directory requires coderootcode permissions you can make your own decision for which directory to usep
pnote that there is no need to open a file handle to the lock filep
| 2 |
seaborn matplotlib how to repress scientific notation in factorplot yaxis | pit looks like the following line solves the issue p
precodepltticklabelformatstyleplain axisy
codepre
phere is the a hrefhttpmatplotliborgapiaxesapihtmlmatplotlibaxesaxesticklabelformat relnofollowdocumentation linkap
| 2 |
django custom validation in model form for imagefield max file size etc | pthe name of method should be codecleanltfield namegtcode in this case codecleanbannercodep
pfor future reference i will place a snippet of code that i used in one recent project names must be adapted to work with op code p
precodefrom pil import image
from djangoutilstranslation import ugettext as
def cleanphotoself
image selfcleaneddatagetphoto false
if image
img imageopenimage
w h imgsize
validate dimensions
maxwidth maxheight 500
if w gt maxwidth or h gt maxheight
raise formsvalidationerror
please use an image that is smaller or equal to
s x s pixels maxwidth maxheight
validate content type
main sub imagecontenttypesplit
if not main image and sublower in jpeg pjpeg png jpg
raise formsvalidationerrorplease use a jpeg or png image
validate file size
if lenimage gt 1 1024 1024
raise formsvalidationerrorimage file too large maximum 1mb
else
raise formsvalidationerrorcouldnt read uploaded image
return image
codepre
| 2 |
dropping a single sub column from a multiindex | pa hrefhttppandaspydataorgpandasdocsstablegeneratedpandasdataframedrophtml relnofollowdropa is a very flexible method and there are quite a few ways to use itp
precodein 11 mi pdmultiindexfromproductcol1 col2 col3 a b
in 12 df pddataframe1 index0 columnsmi
in 13 df
out13
col1 col2 col3
a b a b a b
0 1 1 1 1 1 1
codepre
pdrop a single column using a tuplep
precodein 14 dfdropcol1 a axis1
out14
col1 col2 col3
b a b a b
0 1 1 1 1 1
codepre
por a list using a list of tuplesp
precodein 15 dfdropcol1 a col2 b axis1
out15
col1 col2 col3
b a a b
0 1 1 1 1
codepre
por across a level eg all codeacodesp
precodein 16 dfdropa level1 axis1
out16
col1 col2 col3
b b b
0 1 1 1
codepre
pemin 014 youll also be able to pass regex of what to dropemp
ptheres also a way to drop the entire level of a indexcolumnp
precodein 21 dfcolumnsdroplevel1
out21 indexucol1 ucol1 ucol2 ucol2 u'col3', u'col3'], dtype='object')
</code></pre>
| 2 |
no code completion and syntax highlighting in pydev | pto enable code completion go to window preferences pydev editor code completion and check the use code completion box as well as the other boxes for what you want to complete on it seems to take a second to load the first time it has to complete somethingp
psyntax coloring should just work by default rightclick on the file in the package explorer go to open with and make sure youre opening it with the python editor and not the regular text editorp
pi dont know exactly what you mean by importing external modules i have my source in a separate directory structure on disk my pydev projects contain folders linked to those code completion works for that as well as other modules like os if youre having troubles are the modules added to the pydevs python search path not necessarily the same as the regular onep
pi took a brief look at komodo and wingware a while back so i cant answer the second part of your question but ended up going with pydev im not a big fan of eclipse but pydev works reasonably well for mep
| 2 |
how do programming languages call code written in another language | ppython can be extended in cc more info a hrefhttpdocspythonorg2extendingextendinghtml relnofollowhereap
pit basically means that you can wrap a c module like thisp
precodeinclude pythonh
static function returning a pyobject pointer
static pyobject
keywdargparrotpyobject self pyobject args pyobject keywds
takes self args and kwargs
int voltage
no such thing as strings here its a tough life
char state a stiff
char action voom
char type norwegian blue
possible keywords
static char kwlist voltage state action type null
unpack arguments
if pyargparsetupleandkeywordsargs keywds isss kwlist
ampvoltage ampstate ampaction amptype
return null
print to stdout
printf this parrot wouldnt s if you put i volts through itn
action voltage
printf lovely plumage the s its sn type state
reference count some none
pyincrefpynone
return some none
return pynone
static pymethoddef
static pymethoddef keywdargmethods
the cast of the function is necessary since pycfunction values
only take two pyobject parameters and keywdargparrot takes
three
declare the parrot function say what it takes and give it a doc string
parrot pycfunctionkeywdargparrot methvarargs methkeywords
print a lovely skit to standard output
null null 0 null sentinel
codepre
pand using the python header files it will define and understand entry points and return locations in the cc codep
| 2 |
simple django admin app how to track file versions | pdjango never overwrites an uploaded file if you upload foopng twice the second will be foo1png i just tested this but dont take my word for it try it too p
pall you have to do or let djangoreversion do is keep track of the previous file namesp
| 2 |
profiling self and arguments in python | pyou need to pass localsglobals dict and pass first argument what you will usually type
egp
precodecprofilerunctxselfprofilecommand100 globalslocals
codepre
puse something like thisp
precodeclass aobject
def performprofileself
import cprofile
cprofilerunctxselfprofilecommand100 globalslocals
def profilecommandself a
for i in xrangea
pass
print end
aperformprofile
codepre
pand dont call whole ui in profile profile the specific function or computationp
| 2 |
can someone explain the operator to me | pthe carat codecode is bitwise xor imagine it like thisp
precodegtgtgt 83
11
codepre
hr
precode8 in binary 1000
3 in binary 0011
83 1011
codepre
| 2 |
how do i remove packages installed with pythons easyinstall | pfirst you have to run this commandp
precode easyinstall m package
codepre
pit removes all dependencies of the packagep
pthen remove egg file of that packagep
precode sudo rm rf usrlocallibpython2xsitepackagespackageegg
codepre
| 2 |
python web development with or without a framework | pthe commandline python imo definitely comes first get that to work since thats the core of what youre doingp
pthe issue is that using a web frameworks orm from a command line application isnt obvious django provides specific instructions for using their orm from a commandline app those are annoying at first but i think theyre a lifesaver in the long run i use it heavily for giant uploads of customersupplied filesp
pdont use bare cgi its not impossible but too many things can go wrong and theyve all been solved by the frameworks why reinvent something just use someone elses codep
pframeworks involve learning but no real overhead theyre not slow theyre code you dont have to write or debugp
ol
liplearn some pythonpli
lipdo the a hrefhttpdocsdjangoprojectcomendevdjangoa tutorialpli
lipstart to build a web appp
pa start a django project build a small application in that projectp
pb build your new model using the django orm create a django unit test for the model be sure that it works youll be able to use the default admin pages and do a lot of playing around just dont build the ementireem web site yetpli
lipget your commandline app to work using django orm essentially you have to finesse the settings file for this app to work nicely see the a hrefhttpdocsdjangoprojectcomendevtopicssettingstopicssettingssettingsconfigurationa section pli
liponce youve got your command line and the default admin running you can finish
the web apppli
ol
pheres the golden rule of frameworks strongits code you dont have to write debug or maintainstrong use themp
| 2 |
gtkprogressbar not working in python | pthe problem is you are processing the whole directory when you are creating the window that is even before you show it in the line with codeselfdirfileslistdirpathcode it seems to me you want to call it after pressing the button applyp
pthere are at least 2 possible solutions use threads or use iterators for your specific use case i think iterator would be enough besides than simpler and more pythonic i would recommend threads only when you emreallyem need themp
pinstead of walking through the whole directory beforehand and the process them later you can process each file in each directory at a timep
pin your example i would change the method codedirfileslistcode renamed to codewalkcode and codeonbuttonpressedcode asp
pre classlangpy prettyprintoverridecodefrom gc import collect
from girepository import gtk gobject
codepre
pwe now need to import also gobject to use codeidleaddcode which calls a callback whenever there are no higher priority events pending also once the task is finished we need to remove the callback to not call it anymore we need codesourceremovecode for thatp
pi renamed your method codedirfileslistcode as codewalkcode because it seems semantically closer to an iterator when we walk through each directory and file we will temporarily return using codeyieldcode remember codeyield truecode means that there are pending items to process codeyield falsecode means we stop the iterationp
pso the method would bep
pre classlangpy prettyprintoverridecodedef walkself dirpath
selfdirlist
for root dirs files in oswalkdirpath
i 00
selfsettitleospathdirnameroot
for fn in files
i i 10
f ospathjoinroot fn
selfdirlistappendf
selfprogressbarsetfractioni lenfiles
collect
yield true
yield true
gobjectsourceremoveselfid
yield false
codepre
pnow we update the codeprogressbarcode here in this particular part i am updating the progress bar inside each directory that is it will be restarted in every subdirectory and the progress bar will restart in each of them to have an idea of which directory is visiting set the window title with the current directory the important part to understand here is codeyieldcode you can adapt this to whatever you want to dop>
<p>once we have walked the whole directory, we have to return <code>yield false</code>, but before that we remove the callback (<code>gobject.source_remove(self.id)</code>).</p>
<p>i consider here that <code>self.dir_list</code> is not useful here anymore, but you might have something different in mind.</p>
<p>you might wonder when and how <code>walk</code> is called? that can be set when the button is pressed:</p>
<pre><code>def on_button_pressed(self, button, *args):
homedir = os.path.expanduser('~')
rootdir = os.path.join(homedir, 'documents')
self.task = self.walk(rootdir)
self.id = gobject.idle_add(self.task.next)
</code></pre>
<p><code>self.task</code> is an iterator, which has the method <code>next()</code> that retrieves the next item from <code>self.task</code>, which is going to be called whenever there are no pending events (with <code>idle_add</code>). we get the <code>id</code> in order to remove the callback once we are done.</p>
<p>you have to remove the line <code>self.dir_files_list(dir_path)</code> from the <code>__init__</code> method.</p>
<p>one more thing: i called the garbage collector manually (<code>gc.collect()</code>) because it could be useful when processing a large directory (depending on what you are doing with them).</p>
| 2 |
how do i get intellij to recognize common python modules | pjust create and add python sdkp
precodefile gt project structure gt project gt project sdk gt new
codepre
pand select the installation path of your python interpreter for
example codecpython26code in windows and codeusrbinpython27code in linux as the home pathp
prelated discussion a hrefhttpdevnetjetbrainsnetthread286883httpdevnetjetbrainsnetthread286883ap
| 2 |
splitting a string into an iterator | pnot directly splitting strings as such but the coderecode module has a hrefhttpdocspythonorg2libraryrehtmlrefinditer relnofollowcoderefinditercodea and corresponding codefinditercode method on any compiled regular expressionp
pzero asked for an examplep
precodegtgtgt import re
gtgtgt s the quick brownnfox
gtgtgt for m in refinditers s
printmspan mgroup0
0 3 the
4 9 quick
13 18 brown
19 22 fox
codepre
| 2 |
convert letters to lower case | pas oxtopus suggested you can simply convert letters to their lowercase version with codetextlowercode no need for a regular expression this works with unicode strings too etcp
| 2 |
dictionary with list of values | puse a a hrefhttpdocspythonorglibrarycollectionshtmlcollectionsdefaultdictcodedefaultdictcodea to calculate the sumsp
precodefrom collections import defaultdict
res defaultdictint
with openfootxt r as f
for line in f
kv linesplit
resk intv
res is now a 12 b 5 c 8
codepre
pif you dont want the sums but lists of elements modify that top
precodefrom collections import defaultdict
res defaultdictlist
with openfootxt r as f
for line in f
kv linesplit
reskappendv
res is now a 1 2 9 b 5 c 8
codepre
pnote that i changed some variable names notable codefilecode to codefcode and codedictcode to coderescode thats because codefilecode and codedictcode are the names of builtins and should therefore be avoided as variable names in order to avoid confusionp
palso codereadlinescode is not necessary you can directly iterate over the filep
padditionally the a hrefhttpdocspythonorgreferencecompoundstmtshtmlthewithstatementcodewithcodea statement ensures that the file gets closed afterwardsp
| 2 |
trouble getting if statement to work in def but not in interpreter | precodedef tests
n sfindnot
b sfindbad
if n lt b
return sreplacesn good
print testthis dinner is not that bad
codepre
pyou should codereturncode the result from function codetestcodep
| 2 |
python add list to set | psets cant have mutable changeable elementsmembers a list being mutable cannot be a member of a setp
pas sets are mutable you cannot have a set of sets
you can have a set of frozensets thoughp
pthe same kind of mutability requirement applies to the keys of a dictp
pother answers have already given you code i hope this gives a bit of insight
im hoping alex martelli will answer with even more detailsp
| 2 |
avoid escaping glob expressions in plumbum | blockquote
pbut is there a way to make it understand glob expressions should be passed to the shell asisp
blockquote
pcodeplumbumcode passes codeacode to codelscode command asis codelscode command doesnt run any shell so there is no glob expansion it is done by the shell on nixp
pyou could use codeglobcode module to do the expansionp
precodefrom glob import glob
lsl globa
codepre
panother way is to use codeworkdircode objectp
precodefrom plumbum import local
lsl localcwd a
codepre
pto defer the call you could use codelslargscode syntax note there is probably a bug in codeplumbum 110code version that requires to convert codeargscode list to a tuple explicitlyp
pif you want you could call the shellp
precodefrom plumbumcmd import sh
shc ls l a
codepre
pnote pythons codeglobglobcode function might produce the glob expansion different from that of the shellp
| 2 |
sort numpy string array with negative numbers | pyou could use a hrefhttpnedbatcheldercomblog200712humansortinghtmlnatural sortingap
precodeimport numpy as np
import re
def atoitext
try
return inttext
except valueerror
return text
def naturalkeystext
alistsortkeynaturalkeys sorts in human order
httpnedbatcheldercomblog200712humansortinghtml
return atoic for c in resplitd text
a nparray3 2 1 0 2 word
printsortedakeynaturalkeys
2 1 0 2 3 word
a nparray3 2 1 0 2 word 1 word 2 up
printsortedakeynaturalkeys
2 2 up 1 1 word 0 2 3 word
codepre
| 2 |
why is numpy slower than python how to make code perform better | precodeimport time numpy
def d
a range100000
b range0100000010
c ij for ij in zipab
return c
def e
a numpyarrayrange100000
b numpyarrayrange0100000010
c ab
return c
python 004s 004s 004s
numpy 002s 002s 002s
codepre
ptry it with bigger arrays even with the overhead of creating arrays numpy is much fasterp
| 2 |
how to catch the error in each time in python | pyou will want to move your codetry exceptcode within your codeforcode loop if you want to continue with the ones that dont fail such as belowp
precodefor progstopclock progstartclock programid in iziplongestselfprogramstopclock programstartclock progidlist fillvalue
try
currenttime inttimestrftimem
programstoptime timestrptimeprogstopclock imp
programfinished progstopclocksplit1replacepm replaceam
if programstoptime epgtime1
if programfinished 00
if programwidth gt 342
programswidth 342
selfgetcontrolintprogramidsetwidthprogramswidth
selfgetcontrolintprogramidsetvisiblefalse
selfgetcontrolintprogramidsetpositionintposx 350 intposy
selfgetcontrolintnextprogramsetposition375 intposy
except valueerror e
do something or ignore error
codepre
| 2 |
opencv python matchtemplate function with multiple matches | pheres howp
precoderesult cv2matchtemplateimgtemplatecvcvtmsqdiff
the get the best match fast use this
minxmaxyminlocmaxloc cv2minmaxlocresult
xy minloc
get all the matches
result2 npreshaperesult resultshape0resultshape1
sort npargsortresult2
y1 x1 npunravelindexsort0 resultshape best match
y2 x2 npunravelindexsort1 resultshape second best match
codepre
pthis is note the fastest way as the above sorts all the matches even the totally wrong ones if the performance matters to you you can use the bottlenecks a hrefhttpberkeleyanalyticscombottleneckreferencehtmlbottleneckpartsort relnofollowpartsorta function insteadp
| 2 |
pagination with the python cmd module | pthe simple thing would just be to pipe your script through less or a similar command at runtimep
pheres a simple method that does approximately what you want thoughp
precodedef printandwaitsomelongmessage
lines somelongmessagesplitn
i0
while i lt lenlines
print njoinlinesii10
rawinputpress enter to read more
i 10
codepre
pyou could also look into using cursesp
| 2 |
looking for a nicer python syntax to pass multiple parameters to a singleparametered lambda | preplacing the lambda altogether is the usecase for codeoperatoritemgettercodep
precodesortedditems keyoperatoritemgetter1
codepre
| 2 |
are these two python forloops the same thing | pno thats not the same p
pyour version creates a new dictionary object each iteration with just one key and value the version in the video creates emoneem dictionary object with a series of keyvalue pairsp
pthe version in the video is equivalent top
precoded
for m in months
dm3lower m
codepre
pbut is using a a hrefhttpsdocspythonorg2tutorialclasseshtmlgeneratorexpressions relnofollowemgenerator expressionema to produce the keyvalue pairs as tuples in a loop instead the codedictcode object takes each such pair and adds them to the dictionary being constructedp
pand in python 27 and newer could also be written with a a hrefhttpsdocspythonorg2tutorialdatastructureshtmldictionaries relnofollowdictionary comprehensionap
precodem3lower m for m in months
codepre
pthe end result is a dictionary with the first three letters of each month lowercased as the keyp
precodegtgtgt import calendar
gtgtgt months calendarmonthname1
gtgtgt m3lower m for m in months
mar march feb february aug august sep september apr april jun june jul july jan january may may nov november dec december oct october'}
>>> pprint(_)
{'apr': 'april',
'aug': 'august',
'dec': 'december',
'feb': 'february',
'jan': 'january',
'jul': 'july',
'jun': 'june',
'mar': 'march',
'may': 'may',
'nov': 'november',
'oct': 'october',
'sep': 'september'}
</code></pre>
| 2 |
extending a c application with embedded scripting | pif you want to use python i would definitely suggest using a hrefhttpwwwboostorgdoclibs1480libspythondoc relnofollowboostpythona it is an incredibly well designed library just an example all you have to do to expose a c class to python is thisp
precodestruct world
void setstdstring msg thisgtmsg msg
stdstring greet return msg
stdstring msg
boostpythonmodulehello
classltworldgtworld
defgreet ampworldgreet
defset ampworldset
codepre
pit handles almost everything automatically conversions between types exceptions it even allows you to use reference counted objects between the two languages with codeboostsharedptrcode p
| 2 |
how to handle multiple members of a c class simultaneously | pyou can do the same in c by using pointers or reference to your objectsp
pif your class is codemyclasscode you could declarep
precodestdvectorltmyclassgt list
codepre
pthen add your objects to the listp
precodelistpushbackampobjectofmyclass for all of your objects
codepre
pand finallyp
precodestdvectorltmyclassgtiterator itr
for itr listbegin itr listend itr
itrgtmymethod
codepre
pi have used codestdvectorcode for simplicity in allocating objects it grows automatically and to get an iterator which should be known to you but you could do the same just by using a plain array if you preferp
| 2 |
how to get the absolute path relative to the project root without double slashes | pin my django projects im using unipath it is simplifying a lot
try to use a hrefhttpspypipythonorgpypiunipath10 relnofollowhttpspypipythonorgpypiunipath10a
it is really nice and self explainingp
| 2 |
how can i get the progressdialog to close before i open my messagebox | pi think infinity77 has the right answer here people forget that gui calls are not synchronous they arent finished by the time they return that done call sends a message to the window and in response to that the window probably queues up several more messages to clean itself up when you fire up a model message box that creates its own message loop while leaving the original message loop in suspended animation thus the cleanup messages cannot be processed until the message box returns and your main message loop runs again a yield call will allow those queued up messages to drainp
| 2 |
python print the sum of items in list whose total is the largest and is odd | pin a easy way
sum all and subtract the minimum odd number if first sum is even p
precodeif suml2 1
printsuml
else
printsuml i for i in sortedl if i210
codepre
| 2 |
why is my python output delayed to the end of the program | pits because codesysstdoutcode is buffered use codeflushcodep
precodeimport sys
from time import sleep
for i in range3
sysstdoutwrite
sysstdoutflush
sleep1
printwelcome
codepre
| 2 |
how to programmatically get the md5 checksum of amazon s3 file using boto | pit seems well established that the etag is not the md5sum if the file was assembled after running a multipart upload i think in that case ones only recourse is to download the file and perform a checksum locally if the result is correct the s3 copy must be good if the local checksum is wrong the s3 copy may be bad or the download might have failed if you no longer have the original file or a record of its md5sum i think youre out of luck it would be great if the md5sum of the assembled file were available or if there were a way to locally compute the expected etag of a file to be uploaded via multipartp
| 2 |
differences of scipyspatialkdtree in python 27 and 35 | pin python3 codezipcode returns an a hrefhttpsdocspythonorg3libraryfunctionshtmlzip relnofollowiterator objecta rather than a list of tuples codepointscode will therefore be a 0dimensional codenpobjectcode array containing a codezipcode iterator rather than a 2d array of x y coordinatesp
pyou could construct a codelistcode from the iteratorp
precodepoints nparraylistzipstopsstoplatstopsstoplon
codepre
phowever a more elegant solution might be to avoid using codezipcode altogether by indexing multiple columns of your dataframep
precodepoints stopsstoplatstoplonvalues
codepre
| 2 |
namedtuple in numpy | pa structured array like codepointtypecode does not define math operations that involve several fieldsp
pwith the sample from a hrefhttpstackoverflowcoma33455682901925httpstackoverflowcoma33455682901925ap
precodein 470 pointtype x float y float
in 471 points nparray12 34 56 dtypepointtype
in 472 points
out472
array10 20 30 40 50 60
dtypex ltf8 y ltf8
in 473 points0points1
typeerror unsupported operand types for numpyvoid and numpyvoid
codepre
pinstead i can create a 2d array and then view it as codepointtypecode the databuffer layout will be the samep
precodein 479 points nparray12 34 56float
in 480 points
out480
array 1 2
3 4
5 6
in 481 pointsviewpointtype
out481
array10 20
30 40
5.0, 6.0)]],
dtype=[('x', '<f8'), ('y', '<f8')])
in [482]: points.view(point_type).view(np.recarray).x
out[482]:
array([[ 1.],
[ 3.],
[ 5.]])
</code></pre>
<p>i can do math across rows, and continue to view the results as points:</p>
<pre><code>in [483]: (points[0]+points[1]).view(point_type).view(np.recarray)
out[483]:
rec.array([(4.0, 6.0)],
dtype=[('x', '<f8'), ('y', '<f8')])
in [484]: _.x
out[484]: array([ 4.])
in [485]: points.sum(0).view(point_type)
out[485]:
array([(9.0, 12.0)],
dtype=[('x', '<f8'), ('y', '<f8')])
</code></pre>
<p>alternatively i could start with the <code>point_type</code>, and view it as 2d for the math, and then view-it-back</p>
<pre><code>pdt1=np.dtype((float, (2,)))
in [502]: points
out[502]:
array([(1.0, 2.0), (3.0, 4.0), (5.0, 6.0)],
dtype=[('x', '<f8'), ('y', '<f8')])
in [503]: points.view(pdt1)
out[503]:
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]])
in [504]: points.view(pdt1).sum(0).view(point_type)
out[504]:
array([(9.0, 12.0)],
dtype=[('x', '<f8'), ('y', '<f8')])
</code></pre>
<p>so it is possible to view and operate on an array as 2d and as recarray. to be pretty or useful it probably needs to be burried in a user defined class.</p>
<p>another option to crib ideas from the <code>recarray</code> class. at its core it is just a structured array with a specialized <code>__getattribute__</code> (and setattribute) method. that method first trys the normal array methods and attributes (e.g. <code>x.shape</code>, <code>x.sum</code>). then it tries to fine <code>attr</code> in the defined fieldnames.</p>
<pre><code>def __getattribute__(self, attr):
try:
return object.__getattribute__(self, attr)
except attributeerror: # attr must be a fieldname
pass
fielddict = ndarray.__getattribute__(self, 'dtype').fields
try:
res = fielddict[attr][:2]
except (typeerror, keyerror):
raise attributeerror("record array has no attribute %s" % attr)
return self.getfield(*res)
...
</code></pre>
<p><code>points.view(np.recarray).x</code> becomes <code>points.getfield(*points.dtype.fields['x'])</code>.</p>
<p>an alternate approach would be to borrow from <code>namedtuple</code> (<code>/usr/lib/python3.4/collections/__init__.py</code>), and define <code>x</code> and <code>y</code> properties, which would index the <code>[:,0]</code> and <code>[:,1]</code> columns of the 2d array.
it may be easiest to add those properties to a subclass of <code>np.matrix</code>, letting that class ensure that most math results are 2d.</p>
| 2 |
looking for a more elegant solution to this | pthe thing i like most about python is that it makes it so easy to break a problem apartp
precodedef skip67seq
skipping false
for value in seq
skipping skipping or value 6
yield 0 if skipping else value
skipping skipping and value 7
def sum67seq
return sumskip67seq
gtgtgt sum671 2 2
5
gtgtgt sum671 2 2 6 99 99 7
5
gtgtgt sum671 1 6 7 2
4
codepre
| 2 |
why use a flat list in heapsort | pyou should take a look at it you will find a lot of important thing about the sorting algorithms
a hrefhttpenwikipediaorgwikisortingalgorithm relnofollowsortingap
pon the other hand a hrefhttpenwikipediaorgwikiheap28datastructure29 relnofollowheapa is a treebased data structure with special properties in case of maximum heap the greatest element is in the root node and if b is a child node of a then keya keyb br
heaps are crucial in several efficient graph algorithms such as a hrefhttpenwikipediaorgwikidijkstra27salgorithm relnofollowdijkstras algorithma and in the sorting algorithm a hrefhttpenwikipediaorgwikiheapsort relnofollowheapsortabr
you should also check out a hrefhttpstackoverflowcomquestions8938375anintuitiveunderstandingofheapsortthisa about heap sortbr
strongeditstrong pythonrelated implementation of heap sort can be found a hrefhttpbloggnucomcc2010heapsortinpython relnofollowhereap
| 2 |
how to get this simple python 2 code to work in python 3 | pin python 3 print should be used as a function not a statement so the last line in your outer loop body needs to be codeprintcode not codeprintcode p
| 2 |
how can i send an email based on a new primary key being generated through django | puse a hrefhttpsdocsdjangoprojectcomendevtopicssignals relnofollowdjango signalsap
precodefrom djangodbmodels import signals
def sendemailonneworderinstance created raw kwargs
fixtures or updates are not interesting
if not created or raw
return
instance is your purchaseorder instance
email emailmessagepurchase order system your message here toyouremailgmailcom
emailsend
signalspostsaveconnectsendemailonneworder senderpurchaseorder dispatchuidsendemailonneworder
codepre
pyou have to paste this code somewhere it will be executed during loading django eg codemodelspycodep
pexample codemodelspycodep
precodefrom djangocoremail import emailmessage
from djangodb import models
from djangodbmodels import signals
class purchaseordermodelsmodel
product modelscharfieldmaxlength256
vendor modelscharfieldmaxlength256
dollaramount modelsfloatfield
itemnumber modelsautofieldprimarykeytrue
def sendemailonneworderinstance created raw kwargs
fixtures or updates are not interesting
if not created or raw
return
instance is your purchaseorder instance
email emailmessagepurchase order system your message here toyouremailgmailcom
emailsend
signalspostsaveconnectsendemailonneworder senderpurchaseorder dispatchuidsendemailonneworder
codepre
| 2 |
term document matrix and cosine similarity in python | pmay i recommend you take a look at a hrefhttpscikitlearnorgstablemodulesfeatureextractionhtmlcommonvectorizerusagescikitlearna this is a very well regarded library in the python community with a very simple a consistent api they have also implemented a a hrefhttpscikitlearnorg013modulesmetricshtmlcosine similaritya metric this is an example taken from a hrefhttpstackoverflowcomquestions8897593similaritybetweentwotextdocumentsherea of how you could do it in 3 lines of codep
precodegtgtgt from sklearnfeatureextractiontext import tfidfvectorizer
gtgtgt vect tfidfvectorizermindf1
gtgtgt tfidf vectfittransformid like an apple
an apple a day keeps the doctor away
never compare an apple to an orange
i prefer scikitlearn to orange
gtgtgt tfidf tfidfta
array 1 025082859 039482963 0
025082859 1 022057609 0
039482963 022057609 1 026264139
0 0 026264139 1
codepre
| 2 |
how can i wrap a block in jinja2 | pyou should be able check the contents of a block using the codeselfblocknamecode syntaxp
precode if selfheadline is not empty
write out headline html wrapper here
endif
codepre
pto quote from a hrefhttpjinjapocooorgdocstemplateschildtemplate relnofollowthe documentationap
blockquote
pif you want to print a block multiple times you can however use the special self variable and call the block with that namep
blockquote
precodelttitlegt block title endblock lttitlegt
lth1gt selftitle lth1gt
block body endblock
codepre
| 2 |
multithreaded file read python | peach thread runs your function independently each copy of the function opens the file as a local which is not shared each python file object tracks reading state completely independently each has their own oslevel file handle herep
pso no if emnothing else is altering the file contentsem each thread will see each line just once just the same as if separate emprocessesem tried to read the filep
| 2 |
no module named urls | pi cant reproduce the import error on my machine using your project files windows 7 django 111 python 264 everything imported fine but the urls were not specified properly like the tutorial shows fixing the codep
pmysiteurlspyp
precodefrom djangoconfurlsdefaults import
from djangocontrib import admin
adminautodiscover
urlpatterns patterns
rpolls includemysitepollsurls
radmin includeadminsiteurls
codepre
pmysitepollsurlspyp
precodefrom djangoconfurlsdefaults import
urlpatterns patternsmysitepollsviews
r index
rpltpollidgtd detail
rpltpollidgtdresults results
rpltpollidgtdvote vote
codepre
pvisit a hrefhttp1270018000pollshttp1270018000pollsa i received a templatedoesnotexist exception because the template file is missingp
pstrongim afraid my answer might be to reboot and try it again strongp
| 2 |
how to mount a network directory using python | pid recommend you use codesubprocesscheckcallcodep
precodefrom subprocess import
most simply
checkcall mkdir mntdatadir shelltrue
checkcall mount t whatever datadir mntdatadir shelltrue
more securely
from ospath import expanduser
checkcall mkdir expanduser mntdatadir
checkcall mount t whatever datadir expanduser mntdatadir
codepre
| 2 |
pythonway of getting a substring with a specified delimiter | pyou can use the codeglobcode modulep
precodeimport glob
for filename in globiglob
username description filenamesplit
codepre
| 2 |
removing tuples from a list | pthe coderemovecode method takes an object to remove from the list not an index you could either use codedelcode which does take an index or pass the tuple to coderemovecode directlyp
precodedef filtersent
for tuple in sent
if tuple1 none
del sentsentindextuple
sentremovetuple
codepre
phowever this still wont work youre modifying the list while iterating over it which will screw up your position in the iteration also both codeindexcode and coderemovecode are slow and its a bad idea to name a function codefiltercode hiding the builtin codefiltercode function it would most likely be better to create a new filtered list with a list comprehensionp
precodedef filteredsent
return item for item in sent if item1 none
codepre
| 2 |
windows python version and vc redistributable version | ol
liwindows python versionli
lidll nameli
livc redistributableli
lilink to installerli
ol
hr
ol
li24 25 32 bitli
limsvcr71dll msvcp72dllli
limicrosoft visual c 2003 71 included with net 11li
lia hrefhttpmsdnmicrosoftcomenusnetframeworkaa569264httpmsdnmicrosoftcomenusnetframeworkaa569264ali
ol
hr
ol
li26 27 30 31 32 32 bitli
limsvcr90dll msvcp90dllli
limicrosoft visual c 2008 redistributable package x86li
lia hrefhttpwwwmicrosoftcomdownloadendetailsaspxdisplaylangenampid29httpwwwmicrosoftcomdownloadendetailsaspxdisplaylangenampid29ali
ol
hr
ol
li25 64 bitli
limsvcrtdll msvcp60dllli
liincluded with windowsli
linali
ol
hr
ol
li26 27 30 31 32 64 bitli
limsvcr90dll msvcp90dll li
limicrosoft visual c 2008 redistributable package x64li
lia hrefhttpwwwmicrosoftcom/download/en/details.aspx?id=15336">http://www.microsoft.com/download/en/details.aspx?id=15336</a></li>
</ol>
| 2 |
how to change all characters except for the two | pyou just need to specify a group of characters you emdontem want to matchp
precodegtgtgt resubio a flagsrei
i o i o o o i
codepre
phere all characters except for codeicode codeocode and code code are replaced by a hyphen ignoring case placing characters inside a group prefixed with the codecode symbol means that those characters will be omitted from the matchingp
| 2 |
converting operator to python3 | pits a synonym for the inequality operator codecode as seen in basicp
pby the way the line you are asking about would be far more idiomatically written asp
precodeif in tag
codepre
| 2 |
how would you implement a basic eventloop | pi would use a simple lightweight messaging library called zeromq a hrefhttpwwwzeromqorghttpwwwzeromqorga it is an open source library lgpl this is a very small library on my server the whole project compiles in about 60 seconds p
pzeromq will hugely simplify your eventdriven code and it is also the most efficient solution in terms of performance communicating between threads using zeromq is much faster in terms of speed than using semaphores or local unix sockets zeromq also be a 100 portable solution whereas all the other solutions would tie your code down to a specific operating system p
| 2 |
indexing the datetime column in the csv file using pandas | pif i understand your question correctly thats how you can do itp
precodefrom pandas import
codepre
pread in the data index by matchdatep
precodeframereadcsvdatescsv parsedates true indexcol 4
print frame
country player runs scorerate weekday
matchdate
20100216 afghanistan mohammad shahzad 118 9752 tue
20100316 india schin 112 9802 wed
codepre
pdefine two datetime objects that define the range that you want slicep
precodexdatetime2010 1 5
ydatetime2010 2 25
codepre
pand slice it get all rows that have a codematchdatecode between codexcode and codeycodep
precodeprint frameixxy
country player runs scorerate weekday
matchdate
20100216 afghanistan mohammad shahzad 118 9752 tue
codepre
pif you just want to get a certain month or year you can just do thisp
pcodeframeix20102codep
precode country player runs scorerate weekday
matchdate
20100216 afghanistan mohammad shahzad 118 9752 tue
codepre
| 2 |
how do i find if an int is in array of arrays | precodegtgtgt a 123 456
gtgtgt print any3 in b2 for b in a
false
gtgtgt a 137 456
gtgtgt print any3 in b2 for b in a
true
codepre
| 2 |
python regular expressions two character contain | pi think strongpositive lookaheadstrong might be your solution herep
ptested and workingp
precode6
codepre
pive tried it at a hrefhttpsregex101compython relnofollowregex101coma which you might also find helpful while testing your regular expressionsp
| 2 |
append columns of data | pthe indentation is wrong so you are writing the entire array t on every iteration instead of only at the end change it to thisp
precodet
for line in freadlines
line linesplitt
tappendssn line0 line3
f1writelinest
codepre
palternatively you could write the lines one at a time instead of waiting until the end then you dont need the array codetcode at allp
precodefor line in freadlines
line linesplitt
s ssn line0 line3
f1writes
codepre
| 2 |
importerror at no module named urls | pin your settingspy file make sure the rooturlconf is correctp
pit should look something likep
precoderooturlconf ltinsert project namegturls
codepre
pjudging by what youve provided you might want to make sure it looks likep
precoderooturlconf projectnameurls
codepre
| 2 |
how do you submit a form to an app engine python application without refreshing the sending page | psounds like you want to look into ajax the simplest way to do this is probably to use the ajax functions in one of the popular javascript libraries like jqueryp
| 2 |
generating random sentences from custom text in pythons nltk | pyou should be training the markov model with multiple sequences so that you accurately sample the starting state probabilities as well called pi in markovspeak if you use a single sequence then you will always start in the same statep
pin the case of orwells 1984 you would want to use sentence tokenization first nltk is very good at it then word tokenization yielding a list of lists of tokens not just a single list of tokens and then feed each sentence separately to the markov model this will allow it to properly model sequence starts instead of being stuck on a single way to start every sequencep
| 2 |
how to check what os am i running on in python | precodegtgtgt import platform
gtgtgt platformsystem
codepre
| 2 |
check if header exists with python pandas | pcsvsniffer has a hasheader function that should return true if the first row appears to be a header a procedure for using it would be to first remove all empty rows from the top until the first nonempty row and then run csvsnifferhasheader my experience is that the header must be in the first line for hasheader to return true and it will return false if the number of header fields do not match the number of data fields for at least one row in its scan range which must be set by the user 1024 or 2048 are typical scan ranges i tried to set it much higher even so the entire file would be read but it still failed to recognize the header if it was not in the first line all my testing was done using python 2710p
phere is an example of using csvsniffer in a script that first determines if a file has a recognizable header and if not renames it creates a new empty file with the original name then opens the renamed file for reading and the new file for writing and writes the renamed file contents to the new file excluding leading blank lines finally it retests the new file for a header to determine if removing the blank lines made a differencep
precodeimport csv
from datetime import datetime
import os
import re
import shutil
import sys
import time
commondelimeters set t
def snifffilepath
with openfilepath rb as csvfile
dialect csvsniffersniffcsvfileread2048
delimiter reprdialectdelimiter
if delimiter not in commondelimeters
print filepathhas uncommon delimiterdelimiter
else
print filepathhas common delimiterdelimiter
csvfileseek0
if csvsnifferhasheadercsvfileread2048
print filepath has a header
return true
else
print filepath does not have a header
return false
def removeleadingblanksfilepath
test filepath for header and delimiter
print testingfilepathwith sniffer
hasheader snifffilepath
if hasheader
print no need to remove leading blank lines if any infilepath
return true
make copy of filepath appending current datetime to its name
if ospathisfilefilepath
now datetimenowstrftimeydmhms
m researchrazaz09zfilepath
bakpath
if m none
bakpath filepathreplacemgroup1 now mgroup1
else
bakpath filepath now
try
print renaming filepathto bakpath
osrenamefilepath bakpath
except
print renaming operation failed sysexcinfo0
return false
print creating a newfilepathfrombakpathminus leading blank lines
now open renamed file and copy it to original filename
except for leading blank lines
timesleep2
try
with open(bakpath) as o, open (filepath, 'w') as n:
p = false
for line in o:
if p == false:
if line.rstrip():
n.write(line)
p = true
else:
continue
else:
n.write(line)
except ioerror as e:
print 'file copy operation failed: %s' % e.strerror
return false
print 'testing new',filepath,'with sniffer'
has_header = sniff(filepath)
if has_header:
print 'the header problem with',filepath,'has been fixed'
return true
else:
print 'the header problem with',filepath,'has not been fixed'
return false
</code></pre>
<p>given this csv file where the header is actually on line 11:</p>
<pre><code>header,better,leader,fodder,blather,super
1,2,3,,,
4,5,6,7,8,9
3,4,5,6,7,
2,,,,,
</code></pre>
<p>remove_leading_blanks() determined that it did not have headers, then removed the leading blank lines and determined that it did have headers.
here is the trace of its console output:</p>
<pre><code>testing test1.csv with sniffer...
test1.csv has uncommon delimiter '\r'
test1.csv does not have a header
renaming test1.csv to test1.20153108142923.csv
creating a new test1.csv from test1.20153108142923.csv minus leading blank lines
testing new test1.csv with sniffer
test1.csv has common delimiter ','
test1.csv has a header
the header problem with test1.csv has been fixed
done ok
</code></pre>
<p>while this may work a lot of the time, generally it does not appear reliable due to too much variation in headers and their placement. however, maybe its better than nothing.</p>
<p>see <a href="https://docs.python.org/2/library/csv.html#csv.sniffer" rel="nofollow">csv.sniffer</a>, <a href="https://github.com/python/cpython/blob/master/lib/csv.py" rel="nofollow">csv.py</a> and <a href="https://github.com/python/cpython/blob/master/modules/_csv.c" rel="nofollow">_csv.c</a> for more info. <a href="https://pymotw.com/2/csv/" rel="nofollow">pymotw's csv â comma-separated value files</a> has a good tutorial review of the csv module with details on dialects.</p>
| 2 |
cant call my class in python | pby the example you gave it seems that you are only creating the new instance but not calling the codeeditinputfilecode method try to dop
precodefe fileeditora b
feeditinputfile
codepre
| 2 |
update new django and python 27 with virtualenv on dreamhost with passenger | pi currently have private server a shell account and a bit of luck so here is what i dop
ol
lipssh to your host to upgrade pythonp
precode cd
mkdir tmp
cd tmp
wget httpwwwpythonorgftppython273python273tgz
tar zxvf python273tgz
cd python273
configure enableshared prefixhomepython27 enableunicodeucs4
make
make install
codepreli
lipconfigure system to use our new python open bashrc and add the following linep
precode export pathhomepython27binpath
export ldlibrarypathhomepython27lib
save it and run
source bashrc
codepre
pyou can now check your python version with codewhich pythoncodepli
lipinstall codeeasyinstallcode codepipcodep
precodecd tmp
wget httppeaktelecommunitycomdistezsetuppy
python ezsetuppy
easyinstall pip
codepreli
lipinstall codevirtualenvcodep
precode pip install virtualenv
virtualenv homeltsitegtenv
switch to virtualenv
source homeltsitegtenvbinactivate
codepre
pyou can also add env path to codebashrccodep
precode export pathhomeltsitegtenvbinpath
source bashrc
codepreli
lipinstall django and everything elsep
precode pip install django
pip install .
pip install ....
pip install ....
</code></pre></li>
<li><p>create project</p>
<pre><code> cd $home/<site>/
python $home/<site>/env/bin/django-admin.py startproject project
</code></pre></li>
<li><p>create <code>passenger_wsgi.py</code> in <code>home/<site>/</code> with following content</p>
<pre><code> import sys, os
cwd = os.getcwd()
sys.path.append(cwd)
sys.path.append(cwd + '/project') #you must add your project here or 500
#switch to new python
#you may try to replace $home with your actual path
if sys.version < "2.7.3": os.execl("$home/<site>/env/bin/python",
"python2.7.3", *sys.argv)
sys.path.insert(0,'$home/<site>/env/bin')
sys.path.insert(0,'$home/<site>/env/lib/python2.7/site-packages/django')
sys.path.insert(0,'$home/<site>/env/lib/python2.7/site-packages')
os.environ['django_settings_module'] = "project.settings"
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.wsgihandler()
</code></pre></li>
</ol>
<p>or this way</p>
<pre><code>import sys, os
base_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(base_dir)) #you must add your project here or 500
#switch to new python
#you may try to replace $home with your actual path
python_path = os.path.join(base_dir, 'env', 'bin', 'python')
if sys.executable != python_path:
os.execl(python_path, "python2.7.12", *sys.argv)
</code></pre>
<p>if you are using django 1.7, replace the last two line with</p>
<pre><code>from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
</code></pre>
<ol start="8">
<li>enjoy :d</li>
</ol>
| 2 |
how do you filter pandas dataframes by multiple columns | pusing codeampcode operator dont forget to wrap the substatements with codecodep
precodemales dfdfgendermale amp dfyear2014
codepre
pto store your dataframes in a codedictcode using a for loopp
precodefrom collections import defaultdict
dic
for g in male female
dicgdefaultdictdict
for y in 2013 2014
dicgydfdfgenderg amp dfyeary store the dataframes to a dict of dict
codepre
h2edith2
pa demo for your codegetdfcodep
precodedef getdfdic gender year
return dicgenderyear
print gendfdic male 2014
codepre
| 2 |
python add list to set | pyoull want to use tuples which are hashable you cant hash a mutable object like a listp
precodegtgtgt a setabcde
gtgtgt a
seta c b e d
gtgtgt t f g
gtgtgt aaddt
gtgtgt a
seta c b e d f g
codepre
| 2 |
how to write a python function that adds all arguments | pjust use the a hrefhttpdocspythonorglibraryfunctionshtmlsumsuma builtin functionp
precodegtgtgt def myfuncargs
return sumargs
gtgtgt myfunc1234
10
gtgtgt
codepre
hr
pstrongeditstrongp
pi dont know why you want to avoid sum but a hrefhttpdocspythonorglibraryfunctionshtmlreducehere we goap
precodegtgtgt def myfuncargs
return reducelambda x y x y args
gtgtgt myfunc1234
10
gtgtgt
codepre
pinstead of the codelambdacode you could also use a hrefhttpdocspythonorglibraryoperatorhtmloperatoraddoperatoraddap
hr
pstrongedit2strongp
pi had a look at your a hrefhttpstackoverflowcomquestions11519787howtofindthelistinalistoflistswhosesumofelementsisthegreatestothera a hrefhttpstackoverflowcomquestions11520087howtouseacustomfunctioninmaxxkeycustomfunctionfunction/">questions</a>, and it seems your problem is using <code>sum</code> as the <code>key</code> parameter for <code>max</code> when using a custom class. i <a href="http://stackoverflow.com/a/11521976/142637">answered</a> your question and provided a way to use your class with <code>sum</code> in my answer.</p>
| 2 |
read mat files in python | pive screwed half an hour even after reading the answers hope this answer helpsp
pfirst save the mat file asp
precodesavetestmatv7
codepre
pafter that in python use the usual loadmatp
precodeimport scipyio as sio
test sioloadmattestmat
codepre
| 2 |