text_a
stringlengths 9
150
| text_b
stringlengths 18
20.9k
| labels
int64 0
2
|
---|---|---|
find in files using ruby or python | pi know you said you dont feel like writing it yourself but for what its worth it would be very easy using codeoswalkcode you could do something like thisp
precoderesults
if regexsearch
p recompilesearchtext
for dir subdirs subfiles in oswalkcdocs2009
for name in fnmatchfiltersubfiles txt
fn ospathjoindir name
with openfn r as f
if regexsearch
results fnlineno for lineno line in enumeratef if psearchline
else
results fnlineno for lineno line in enumeratef if linefindsearchtext gt 0
codepre
pthats python btwp
| 2 |
python fast way to remove duplicates in this list | precodegtgtgt a hello hi hello hi how what hello hi how what
gtgtgt setmaptuple a
sethow what hello hi
codepre
| 2 |
most pythonic way to read csv values into dict of lists | pdepending on what type of data youre storing and if youre ok with using numpy a good way to do this can be with a hrefhttpdocsscipyorgdocnumpyreferencegeneratednumpygenfromtxthtml relnofollowcodenumpygenfromtxtcodeap
precodeimport numpy as np
data npgenfromtxtdatacsv delimiter namestrue
codepre
pwhat this will do is create a numpy a hrefhttpdocsscipyorgdocnumpyuserbasicsrechtml relnofollowstructured arraya which provides a nice interface for querying the data by header name make sure to use codenamestruecode if you have a header rowp
pexample given codedatacsvcode containingp
precodeabc
123
456
789
codepre
pyou can then access elements withp
precodegtgtgt dataa column with header a
array 1 4 7
gtgtgt data0 first row
10 20 30
gtgtgt datac2 specific element
90
gtgtgt dataa c two columns
array10 30 40 60 70 90
dtypea ltf8 c ltf8
codepre
<p><code>genfromtext</code> also provides a way, as you requested, to "format the data being ingested by column up front."</p>
<blockquote>
<p><strong>converters</strong> : <em>variable, optional</em></p>
<p>the set of functions that convert the data of a column to a value. the converters can also be used to provide a default value for missing data: converters = {3: lambda s: float(s or 0)}.</p>
</blockquote>
| 2 |
how to reverse string with stride via python string slicing | pyou can bring several ideas to a hrefhttpstackoverflowcomquestions9475241splitpythonstringeverynthcharactersplit a string in piecesa and then reverse each piece and reassemble join the list reversed toop
peg using satomacoto answer in a notsoreadable wayp
precodejoina1ii21 for i in range0 lena 2
codepre
por using fj answer p
precodejoinmapjoin zipitera21
codepre
pand so on being codeacode your stringp
| 2 |
object does not support item assignment error | pthe error seems clear model objects do not support item assignment
codemymodelobjectslatestidfoo barcode will throw this same errorp
pits a little confusing that your model instance is called codeprojectformcodep
pto reproduce your first block of code in a loop you need to use codesetattrcodep
precodefor kv in sessionresultsiteritems
setattrprojectform k v
codepre
| 2 |
how to use array in django | pyou may be interested in using a a hrefhttpdocsdjangoprojectcomendevrefmodelsfieldscommaseparatedintegerfieldcodecommaseparatedintegerfieldcodeap
pif youve got a list of integers like thisp
precodemyints 12345
codepre
pand a model like thisp
precodeclass mymodelmodelsmodel
values commaseparatedintegerfieldmaxlength 200
codepre
pthen you can save codemyintscode into a codemymodelcode like thisp
precodem mymodelvalues joinmyints
msave
codepre
| 2 |
forgetting to return the result from a function how to prevent this bug | ppylint will sometimes catch this kind of error in particular if you assign to coderesultcode but then never use itp
precodepylint zorgpy
module zorg
w0612 5zorg unused variable result
codepre
phowever it does not catch the case where you build up coderesultcode in pieces and then forget to return it because then the variable is not unusedp
pdepending on many other things though pylint through its static typeanalysis may catch the failure to return a valuep
| 2 |
proper way to migrate ndb model property | pyou can change the classlevel property name while keeping the underlying ndb property name by specifying the strongnamexxstrong param in the property constructorp
pso something like this could be donep
precodeclass userndbmodel
company ndbkeypropertynamecompany repeatedtrue
property
def companyself
return selfcompany
companysetter
def companyself newcompany
selfcompany newcompany
codepre
pso now anytime you access strongcompanystrong ndb will actually setget strongcompanystrong internally and you dont have to do any data migrationsp
| 2 |
modify an xml file in python | puse elementtreep
precodefrom xmletreeelementtree import element subelement comment tostring
configure one attribute with set
root elementopml
rootsetversion 10
rootappendcommentgenerated by elementtreecsvtoxmlpy for pymotw
codepre
pa hrefhttpbroadcastoreillycom201003pymotwcreatingxmldocumentshtml relnofollowhttpbroadcastoreillycom201003pymotwcreatingxmldocumentshtmlap
| 2 |
why it works about python type conversion | papart from when specifying function arguments codexcode is the same as codexcode so codeint100code is equivalent to codeint100codep
pthey even compile to the same bytecodep
precodegtgtgt import dis
gtgtgt disdislambda int100
1 0 loadglobal 0 int
3 loadconst 1 100
6 callfunction 1
9 returnvalue
gtgtgt disdislambda int100
1 0 loadglobal 0 int
3 loadconst 1 100
6 callfunction 1
9 returnvalue
codepre
| 2 |
write a comma in csv file using python | puse the proper a hrefhttpdocspythonorgrelease264librarycsvhtmlwriterobjects relnofollowcsv writersap
precodegtgtgt import csv
gtgtgt spamwriter csvwriteropeneggscsv wb
gtgtgt spamwriterwriterowspam lovely spam
codepre
poutputsp
blockquote
pspamlovely spamp
blockquote
| 2 |
nesting functions in python | pyour problem is that codetxtreversecode does not return the reversed list it returns codenonecodep
pie codetxtreversecode reverses your list in placep
| 2 |
python finding the longest sequence with findall | pcoderedotallcode does nothing in this case so ive just taken it out for simplicitys sakep
precodegtgtgt import re
gtgtgt maxrefindallg fggfggggfggfg keylen
gggg
codepre
pif you need all of them in order of lengthp
precodegtgtgt sortedrefindallg fggfggggfggfg keylen reversetrue
gggg gg gg g
codepre
| 2 |
python builtin types subclassing | pyou need to call the list initializerp
precodeclass mylistlist
def initself li
supermylist selfinitli
codepre
passigning to codeselfcode in the function just replaces the local variable with the list not assign anything to the instancep
precodegtgtgt class mylistlist
def initself li
supermylist selfinitli
gtgtgt ml mylist1 2 3
gtgtgt ml
1 2 3
gtgtgt lenml
3
gtgtgt typeml
ltclass mainmylistgt
codepre
| 2 |
how to get started with a barebones eclipse pydev | pthe leanest eclipse installation is the a hrefhttpdownloadeclipseorgeclipsedownloadsdrops4r442201502041700 relnofollowplatform runtime binarya at around 50mb look for it in the middle of the page install it and then once in eclipse go to helpinstall new software and use a hrefhttppydevorgupdates relnofollowhttppydevorgupdatesa as link to install pydev and you are done not very hard at all p
| 2 |
replace str method on list object in python | pthis solution works without a wrapper and works if you join two lists by add any operation that modify the list itself will work as expected only functions that return a copy of the list like sorted reveresed will return the native python list which is fine sort and reverse on the other hand operate on the list itself and will keep the typep
precodeclass mylistlist
def newcls datanone
obj supermylist clsnewcls data
return obj
def strself
return mylists listself
def addself other
return mylistlistself listother
gtgtgt l mylistrange5
gtgtgt print l
mylist0 1 2 3 4
gtgtgt print l 1 2
mylist0 1 2 3 4 1 2
gtgtgt lsort
gtgtgt print l
mylist0 1 2 3 4
codepre
| 2 |
how to create a loop from 19 and from az | prather than create a range loop over a emstringem to get individual charactersp
precodeimport string
for character in stringasciilowercase stringdigits1
print character
codepre
pthis uses the a hrefhttpsdocspythonorg2librarystringhtmlcodestringcode modulea to grab predefined strings of ascii lowercase letters and digitsp
pthe codestringdigits1code slice removes the code0code character to leave just the digits code1code through to code9codep
| 2 |
python for loop with range | pyoure missing the fact that codenumscode is getting filtered on every iteration so on the first iteration all numbers for which x 2 is not 0 which includes 4 are filtered outp
pif you put an extra codeprint numscode within the loop after the filter you would see this more clearlyp
| 2 |
script slicing in python | pthis is where list comprehensions become really handyp
precodegtgtgt newlist partiye oy vermeyecegimi bilerek sandiga gidecegim
gtgtgt print i6 for i in newlist
partiy oy vermey bilere sandig gidece
codepre
pif you wanted to expand itp
precodes
for i in newlist
sappendi6
codepre
pits pretty much the same approach as what youre doing but its a little neaterp
pwhat youre doing is continually reassigning codeacode to a value so its rather pointless i think you wanted codeaappends6code anyway which adds a value to a list but even then that wont work since youre approaching the solution the wrong way pp
| 2 |
upload file to my dropbox from python script | pthanks to smarx for the answer above i just wanted to clarify for anyone else trying to do this p
ol
lipmake sure you install the dropbox module first of course codepip install dropboxcode pli
lipcreate an app under your own dropbox account in the app console a hrefhttpswwwdropboxcomdevelopersappshttpswwwdropboxcomdevelopersappsapli
lipjust for the record i created my app with the followingp
pa app type as dropbox api appp
pb type of data access as files amp datastoresp
pc folder access as my app needs access to files already on dropbox ie permission type as full dropboxpli
lipthen click the generate access token button and cutpaste into the python example below in place of codeltauthtokengtcodepli
ol
pprecodep
import dropbox
client dropboxclientdropboxclientltauthtokengt
print linked account clientaccountinfo
f openworkingdrafttxt rb
response clientputfilemagnumopustxt f
print uploaded response
foldermetadata clientmetadata
print metadata foldermetadata
f metadata clientgetfileandmetadatamagnumopustxt
out openmagnumopustxt wb
outwritefread
outclose
print metadata
codepre
p p
| 2 |
any gotchas using unicodeliterals in python 26 | palso take into account that codeunicodeliteralcode will affect codeevalcode but not codereprcode an asymmetric behavior which imho is a bug ie codeevalreprbxa4code wont be equal to codebxa4code as it would with python 3p
pideally the following code would be an invariant which should always work for all combinations of codeunicodeliteralscode and python 27 3x usagep
precodefrom future import unicodeliterals
bstr bxa4
assert evalreprbstr bstr fails in python 27 holds in 31
ustr xa4
assert evalreprustr ustr holds in python 27 and 31
codepre
pthe second assertion happens to work since codereprxa4code evaluates to codeuxa4code in python 27p
| 2 |
difference between python lambda functions inside class and def | pyour problem here is the difference between bound methods and functionsp
phave a simpler examplep
precodeclass someclassobject
bound lambda args bound method got formatargs
def initself
selfunbound lambda args function got formatargs
codepre
precodegtgtgt c someclass
codepre
pif we look closely these two functions are not of the same typep
precodegtgtgt cbound
ltbound method someclassltlambdagt of ltmainsomeclass object at 0xgtgt
gtgtgt cunbound
ltfunction someclassinitltlocalsgtltlambdagt at 0xgt
codepre
pand as a result when we call them they receive different argumentsp
precodegtgtgt cbound1 2 3
bound method got ltmainsomeclass object at 0xgt 1 2 3
gtgtgt cunbound1 2 3
unbound got 1 2 3
codepre
pnotice that only the bound function got a codeselfcode argument passed in p
psuptested in 35 27 might have slightly different names for thingssupp
| 2 |
python import vs execfile | panother difference execfile gets a context dictionary the global context by default or
a specified dictionary this could allow some strange thingsp
pcodedontdothispycodep
precode probably not a good thing to do
zx1 an expression that involves an undefined field
codepre
pobviously p
precodefrom dontdothis import
codepre
pfailsp
phoweverp
precodedx1
execfile dontdothispy d
codepre
pis ok and results in codedx1 z2codep
pnote thatp
precodex1
execfile dontdothispy
codepre
pis ok and results in the variable codezcode being added to the globalsp
| 2 |
finding how many different letters there are in a string in python | ptry looking at the length of the set of lettersp
precodelensetyourstring
in 8 setlowercase
out8 seta c e l o s r w
in 9 lensetlowercase
out9 8
codepre
pnbspp
pdont forget to remove spacesp
precodein 10 lensetthe quick brown fox jumps over the lazy doglowerreplace
out10 26
codepre
| 2 |
can listdisplay in a django modeladmin display attributes of foreignkey fields | pyou can show whatever you want in list display by using a callable it would look like thisp
pre
def bookauthorobject
return objectbookauthor
class personadminadminmodeladmin
listdisplay bookauthorpre
| 2 |
why are list dict and tuple slower than and | pthe function call requires a variable name lookup followed by a function invocation the function called then creates a list and returns it the list syntax literal gets the interpreter to just make a listp
precodegtgtgt import dis
gtgtgt foo lambda
gtgtgt bar lambda list
gtgtgt disdisfoo
1 0 buildlist 0
3 returnvalue
gtgtgt disdisbar
1 0 loadglobal 0 list
3 callfunction 0
6 returnvalue
gtgtgt
codepre
| 2 |
formating string in c | pclosest implementation would bep
precodeinclude ltstdiohgt
int mainvoid
char text100
int var1 10
int var2 45
int var3 76
sprintftext numbers are d d d var1 var2 var3
codepre
| 2 |
is it possible to run function in a subprocess without threading or writing a separate filescript | pi think youre looking for something more like the multiprocessing modulep
pa hrefhttpdocspythonorglibrarymultiprocessinghtmltheprocessclasshttpdocspythonorglibrarymultiprocessinghtmltheprocessclassap
pthe subprocess module is for spawning processes and doing things with their inputoutput not for running functionsp
phere is a codemultiprocessingcode version of your codep
precodefrom multiprocessing import process queue
def myfunctionq x
qputx 100
if name main
queue queue
p processtargetmyfunction argsqueue 1
pstart
pjoin this blocks until the process terminates
result queueget
print result
codepre
| 2 |
chained nested dict get calls in python | phow about using a small helper functionp
precodedef getnd path
for p in path
if p not in d
return none
d dp
return d
codepre
pand thenp
precodegetnm gparents parent child for m in m
codepre
| 2 |
python difference between and is not | pcodeiscode tests for object identity but codecode tests for object value equalityp
precodein 1 a 3424
in 2 b 3424
in 3 a is b
out3 false
in 4 a b
out4 true
codepre
| 2 |
python tuple question | pif you just put code1000code python assumes youre just evaluating the expression as math hence it gets simplified to just 1000 think of the result of code5 1000 4codep
pjust as the expression above would get simplified to code1009code here is what your line looks like once things have been simplifiedp
precodep multiprocessingprocesstargettimesleep args1000
codepre
pyou can see that this is not the same thing at all codeargscode is supposed to be a tuple of arguments not a single integerp
pif you put code1000code python can tell you are looking for a tuple which only contains one element since that expression is differentiable from a simple arithmetic expression so you end up passing in the correct thingp
| 2 |
how do i make this list function faster | precodeimport collections
def countworddistancesli
wordmap collectionsdefaultdictlist
for i w in enumerateli 1
wordmapwappendi
for k v in wordmapiteritems
wordmapk sumvfloatlenv
return wordmap
codepre
pthis makes only one pass through the list and keeps operations to a minimum i timed this on a word list with 11m entries 29k unique words and it was almost twice as fast as patricks answer on a list of 10k words 2k unique it was more than 300x faster than the ops codep
pto make python code go faster there are two rules to keep in mind use the best algorithm and avoid python p
pon the algorithm front iterating the list once instead of n1 times n number of unique words is the main thing that will speed this up p
pon the avoid python front i mean you want your code to be executing in c as much as possible so using codedefaultdictcode is better than a dict where you explicitly check if the key is present codedefaultdictcode does that check for you but does it in c in the python implementation codeenumeratecode is better than codefor i in rangelenlicode again because its fewer python steps and codeenumerateli 1code makes the counting start at 1 instead of having to have a python 1 somewhere in the loopp
pedited third rule use pypy my code goes twice as fast on pypy as on 27p
| 2 |
allow all method types in flask route | pyou can change the urlmap directly for this by adding a a hrefhttpwerkzeugpocooorgdocsroutingwerkzeugroutingrulecoderulecodea with no methodsp
precodefrom flask import flask request
import unittest
from werkzeugrouting import rule
app flaskname
appurlmapaddrule endpointindex
appendpointindex
def index
return requestmethod
class testmethodunittesttestcase
def setupself
selfclient apptestclient
def testcustommethodself
resp selfclientopen methodbacon
selfassertequalbacon respdata
if name main
unittestmain
codepre
blockquote
pcodemethodscodep
pa sequence of http methods this rule applies to if not specified all methods are allowedp
blockquote
| 2 |
how to return a static html file as a response in django | pif your css and js files are static dont use django to serve them or a hrefhttpsdocsdjangoprojectcomenstablehowtostaticfiles relnofollowserve them as static filesap
pfor your html you could do the same if it is just some fixed file that wont have any dynamic content you could also use a hrefhttpsdocsdjangoprojectcomenstabletopicsclassbasedviews relnofollowgeneric viewsa with the a hrefhttpsdocsdjangoprojectcomenstablerefclassbasedviewstemplateview relnofollowtemplateviewa just add a line like this to your codeurlspycodep
precode urlrpathtourl templateviewasviewtemplatenameindexhtml
codepre
| 2 |
cascadeforward neural network | pif i understand correctly you want to connect your input layer to both hidden layer and directly to the output layerp
pwhat if you simply create an additional fullconnection from input layer to output layer p
precodefrom pybrainstructure import feedforwardnetwork
n feedforwardnetwork
from pybrainstructure import linearlayer sigmoidlayer
inlayer linearlayer2
hiddenlayer sigmoidlayer3
outlayer sigmoidlayer1
naddinputmoduleinlayer
naddmodulehiddenlayer
naddoutputmoduleoutlayer
from pybrainstructure import fullconnection
intohidden fullconnectioninlayer hiddenlayer
hiddentoout fullconnectionhiddenlayer outlayer
intoout fullconnectioninlayer outlayer
naddconnectionintohidden
naddconnectionhiddentoout
naddconnectionintoout
nsortmodules
print n
codepre
pthis seems to be workingp
| 2 |
generic way to get primary key from declaratively defined instance in sqlalchemy | pyou can use codeinspectioncode for that purposep
pa hrefhttpdocssqlalchemyorgenlatestcoreinspectionhtml relnofollowhttpdocssqlalchemyorgenlatestcoreinspectionhtmlap
ppassing an instance of a mapped object to inspect returns an codeinstancestatecode describing that object
this state also contains the identityp
precodebase declarativebase
class myclassbase
tablename mytable
key columninteger primarykeytrue
a myclasskey1
from sqlalchemyinspection import inspect
pk inspectaidentity
print pk
codepre
pwill givep
precode1
codepre
psince primary keys can consist of multiple columns the identity in general is a tuple containing all the column values that are part of the primary key
in your case thats simply the codekeycodep
| 2 |
non numerical indexing in multidimensional matrices lists | pyou can use a hrefhttppandaspydataorgpandasdocsstablegeneratedpandasdataframelochtml relnofollowcodeloccodeap
precodeimport pandas as pd
mat pddataframethree a 3 b 6
two a 2 b 5
one a 1 b 4
columns onetwothree
print mat
one two three
a 1 2 3
b 4 5 6
get
print matloca three
3
set
matloca three 10
print mat
one two three
a 1 2 10
b 4 5 6
codepre
peditp
pyou can create a hrefhttppandaspydataorgpandasdocsstabledsintrohtmldataframe relnofollowcodedataframecodea from codenumpy arraycode toop
precodeprint arr
1 2 3
4 5 6
mat pddataframearr indexab columnsonetwothree
one two three
a 1 2 3
b 4 5 6
codepre
| 2 |
how to disable formatting for floatfield in template for django | precode floatvarstringformatf
codepre
| 2 |
webpy obtain request headers | pthe a hrefhttpwebpyorgcookbookctxcodewebctxenvcodea structure gives you access to the a hrefhttpwwwpythonorgdevpepspep0333environvariableswsgi environment variablea in wsgi apps the content type header is named codecontenttypecodep
precodect webctxenvgetcontenttype
codepre
| 2 |
python library to modify mp3 audio without transcoding | pi got three quality answers and i thank you all and upvoted you all for them i havent chosen any as the accepted answer because each addressed one aspect so i wanted to write a summaryp
pstrongdo you need to work in mp3strongp
ul
liptranscoding to pcm and back to mp3 is unlikely to result in a drop in quality pli
lipdont optimise audioquality prematurely test it with a simple prototype and listen to itpli
ul
pstrongworking in mp3strongp
ul
lipwikipedia has a summary of the a hrefhttpenwikipediaorgwikimp3mp3 file formatapli
lipmp3 frames are short 1152 samples or just a few milliseconds allowing for moderate precision at that levelpli
liphowever a hrefhttpenwikipediaorgwikimp3wikipediaa warns that frames are not independent items byte reservoir and therefore cannot be extracted on arbitrary frame boundariespli
lipexisting libraries are unlikely to be of assistance if i really want to avoid decodingpli
ul
pstrongworking in pcmstrongp
pthere are several libraries at this levelp
ul
lia hrefhttppymediaorgpymediaali
lia hrefhttplamesourceforgenetlameali
lia hrefhttpspacepantsorgsrcpymadpymada linux only decoder onlyli
ul
pstrongworking at a higher levelstrongp
ul
lipa hrefhttpcode.google.com/p/echo-nest-remix/">echo nest remix api</a> (mac or linux only, at the moment) is an api to a web-service that supports quite sophisticated operations (e.g. finding the locations of music beats and tempo, etc.)</p></li>
<li><p><a href="http://mpesch3.de1.cc/mp3dc.html#dwn">mp3directcut</a> (windows only) is a gui that apparently performs the operations i want, but as an app. it is not open-source. (i tried to run it, got an access denied installer error, and didn't follow up. a gui isn't suitably for me, as i want to repeatedly run these operations on a changing library of files.) </p></li>
</ul>
<p>my plan is now to start out in pymedia, using pcm. thank you all for your assistance.</p>
| 2 |
how do you use initpy | pyou also need to have initpy in a and b directoriesp
pfor your example to work first you should add your base directory to the pathp
precodeimport sys
syspathappend
import inittestaaaa
codepre
| 2 |
import statement after function definition how can i make it more pythonic | phow about putting the functions in two different modulesp
pcodemodule1codep
precodeimport win32file
def findfilewildcard
returns path of the first matched file using win32file
gtgtgt findfile1dpython26exe
dpython26pythonexe
return filepath
codepre
pcodemodule2codep
precodeimport glob
def findfilewildcard
same as above but using glob
return filepath
codepre
pmain programp
precodetry
from module1 import findfile
except importerror
from module2 import findfile
codepre
| 2 |
identical error codes | pit appears python is exposing the error code from the os the interpretation of the code is osdependentp
p111 is codeeconnrefusedcode on many linux systems and on cygwinp
p146 is codeeconnrefusedcode on solarisp
p10061 is codewsaeconnrefusedcode in winerrorh its the windows socket apis version of codeeconnrefusedcodep
pno doubt on other systems its different againp
pthe correct way to handle this is use symbolic comparisons based on the oss definition of codeeconnrefusedcode thats the way you do it in c for example in other words have a constant called econnrefused that has the value of econnrefused for that platform in a platformspecific library which will be necessary to link to the oss socket primitives in any case and compare error codes with the econnrefused constant rather than magic numbersp
pi dont know what pythons standard approach to os error codes is i suspect its not terribly well thought outp
| 2 |
python math module | pcodepowcode is built into the languagenot part of the math library the problem is that you havent imported math p
ptry thisp
precodeimport math
mathsqrt4
codepre
| 2 |
what is wrong with my algorithmcode | pin else clause
put p
precodeconductivitysum0
datapoint0
tempcheck tempi
conductivitysumconductivityi
datapoint1
codepre
pbecause when you go to else clause you miss that particular conductivity of i it doesnt get saved so before moving to next i save that conductivityp
| 2 |
do oo design principles apply to python | pthe biggest differences are that python is duck typed meaning that you wont need to plan out class hierarchies in as much detail as in java and has first class functions the strategy pattern for example becomes much simpler and more obvious when you can just pass a function in rather than having to make interfaces etc just to simulate higher order functions more generally python has syntactic sugar for a lot of common design patterns such as the iterator and the aforementioned strategy it might be useful to understand these patterns ive read head first and found it pretty useful but think about pythonic ways to implement them rather than just doing things the same way you would in javap
| 2 |
using pythons sysargv to return function results to command line | pok i might as well post this as my answer instead of just a commentp
pinp
precodeprint dictionaryagrv
codepre
pcodeargvcode is misspelledp
pit should be p
precodeprint dictionarysysargv
codepre
palso use codesysargvcode codeargvcode by itself wont sufficep
| 2 |
i dont understand jinja2 call blocks | pthis is the outputp
precodeltdiv classdialoggt
lth2gthello worldlth2gt
ltdiv classcontentsgt
this is a simple dialog rendered by using a macro and
a call block
ltdivgt
ltdivgt
codepre
pso when we call renderdialog we pass hello world as title when it reach codecallercode it passes the contents of the codecallcode blockp
| 2 |
encoding issue with asciisafe file with codec header depending on line count | pthis looks like a regression caused by a hrefhttpbugspythonorgissue20731 relnofollowissue 20731a it looks like the position calculation is assuming there will always be crlf line endings while your file has only got lf characters leading to an incorrect offset a hrefhttpshgpythonorgcpythonfilev352parsertokenizercl510 relnofollowbeing calculated hereap
pre classlangc prettyprintoverridecodefd filenotokgtfp
due to buffering the file offset for fd can be different from the file
position of tokgtfp if tokgtfp was opened in text mode on windows
its file position counts crlf as one char and cant be directly mapped
to the file offset for fd instead we step back one byte and read to
the end of line
pos ftelltokgtfp
if pos 1
lseekfd offtpos gt 0 pos 1 pos seekset offt1
pyerrsetfromerrnowithfilenamepyexcoserror null
goto cleanup
codepre
pthe problem disappears when you convert your file to use windows crlf line endings but i can understand that for crossplatform scripts thats not a practical solutionp
pive filed a hrefhttpbugspythonorgissue27797 relnofollowissue 27797a this should be fixed in python itselfp
| 2 |
fastest way to load a screenshot into memory for cv template matching | pa hrefhttpslaunchpadnetxpresser relnofollowxpressera is a project that works in ubuntu that also uses opencv in the a hrefhttpbazaarlaunchpadnetniemeyerxpressertrunkviewheadxpresserxutilspy relnofollowxutils modulea theres a function to take a screenshot which is as followsp
precodedef takescreenshotx0 y0 widthnone heightnone
window gtkgdkgetdefaultrootwindow
if not width and height
size windowgetsize
if not width
width size0
if not height
height size1
pixbuf gtkgdkpixbufgtkgdkcolorspacergb false 8 width height
pixbuf pixbufgetfromdrawablewindow windowgetcolormap
x y 0 0 width height
array pixbufgetpixelsarray
return imagescreenshot arrayarray
widtharrayshape1 heightarrayshape0
codepre
pi hope this helpsp
| 2 |
what is a pythonic way to alter a dict with a key and multiple values to get the desired output | pmaking extensive use of generators and list comprehension you can write it like thisp
pre classlangpython prettyprintoverridecodeother other unknown strings denoting noncontries
ids seti for ij in mylist all ids in the list
known seti for ij in mylist if j not in other ids of real countries
outlist k for k in mylist if k1 not in other keep all real countries
outlistextendi other0 for i in ids known append other for all ids with no real country
codepre
pthe result will bep
pre classlangpython prettyprintoverridecode10 india 12 usa 12 uk 11 other
codepre
pif order matters this will mean more workp
| 2 |
trying to catch integrity error with sqlalchemy | pthere might be no database operations until codedbsessioncommitcode therefore the codeintegrityerrorcode is raised later in the stack after the controller code that has codetryexceptcode has already returnedp
| 2 |
how do numpy and gmpy2 compare with gmp in terms of speed | pnumpy and gmpy2 have different purposesp
pnumpy has fast numerical libraries but to achieve high performance numpy is effectively restricted to working with vectors or arrays of lowlevel types 16 32 or 64 bit integers or 32 or 64 bit floating point values for example numpy access highly optimized routines written in c or fortran for performing matrix multiplicationp
pgmpy2 uses the gmp mpfr and mpc libraries for multipleprecision calculations it isnt targeted towards vector or matrix operationsp
pthe python interpreter adds overhead to each call to an external library whether or not the slowdown is significant depends on the how much time is spend by the external library if the running time of the external library is very short say 10e8 seconds then pythons overhead is significant if the running time of the external library is relatively long several seconds or longer then pythons overhead is probably insignificantp
psince you havent said what you are trying to accomplish i cant give a better answerp
pdisclaimer i maintain gmpy2p
| 2 |
python behavior of string in loop | pyou could use a hrefhttpdocspythonorglibrarystdtypeshtmlstrtitle relnofollowcodetitlecodeap
precodegtgtgt s thesethreewords
gtgtgt print stitle
thesethreewords
codepre
| 2 |
pythonregex match in string | pto allow for multiple consecutive matches use lookaheadlookbehindp
precoderltdd
codepre
pexamplep
precodegtgtgt refindallrltdd test75678test
56 78
codepre
pwe can also use lookahead to perform the split as you want itp
precodeimport re
def splitits
pieces resplitrdd s
pieces1 pieces1rsplit 1 split off extension
return pieces
codepre
ptestingp
precodegtgtgt print splitittest100csv
test1 00 csv
gtgtgt print splitittest2wma
test2 wma
gtgtgt print splitittest31100456jpg
test3 1100456 jpg
gtgtgt print splitittest456png
te.s.t.4', '5,6', 'png']
>>> print split_it('test5,7,8.sss')
['test5,7,8', 'sss']
>>> print split_it('test6.2,3,4.png')
['test6.2,3,4', 'png']
>>> print split_it('test7.5,6.7,8.test')
['test7', '5,6', '7,8', 'test']
</code></pre>
| 2 |
more concise comparison of two lists | puse codeanycode or codeallcode to test respectively if a condition holds for any element or all of the elements in a list coupled with codezipcode to stick together the two lists for example the code in the question can be implemented more concisely like thisp
precodenot anyx gt y for x y in zipt1 t2
gt true
codepre
por equivalently as pointed by squiguy in the commentsp
precodeallx lt y for x y in zipt1 t2
gt true
codepre
| 2 |
if else in a list comprehension | pyou could move the conditional top
precodev 22 13 45 50 98 69 43 44 1
x1 if x gt45 else x5 for x in v
codepre
pbut its starting to look a little ugly so you might be better off using a normal loop note that i used codevcode instead of codelcode for the list variable to reduce confusion with the number 1 i think codelcode and codeocode should be avoided as variable names under any circumstances even in quickanddirty example codep
| 2 |
with statement backport for python 25 | pwithstatement wasnt back ported but implemented in python 25 adding new keywords or syntax can break existing applications with python the way they decided to handle this is allow people to optin to those features early so you can slowly transition your code overp
pfrom a hrefhttppythonorgdoc252reffuturehtml relnofollowhttppythonorgdoc252reffuturehtmlap
blockquote
pa future statement is a directive to
the compiler that a particular module
should be compiled using syntax or
semantics that will be available in a
specified future release of python
the future statement is intended to
ease migration to future versions of
python that introduce incompatible
changes to the language it allows use
of the new features on a permodule
basis before the release in which the
feature becomes standardp
blockquote
pyou can actually inspect futures to get information on when first supported when the import isnt needed anymore etcp
precodepython 251 r25154863 apr 18 2007 085108 msc v1310 32 bit intel on win32
type help copyright credits or license for more information
gtgtgt import future
gtgtgt dirfuture
cofutureabsoluteimport cofuturedivision cofuturewithstatement cogeneratorallowed conested feature all builtins
doc file name absoluteimport allfeaturenames division generators nestedscopes withstatement
gtgtgt futurewithstatement
feature2 5 0 alpha 1 2 6 0 alpha 0 32768
gtgtgt
codepre
p>i personally have been heavily using the with_statement in python 2.5 for well over a year and have not had issues. i also transparently run that code with python 2.6. there are some weird corner cases they have worked at cleaning up in the language, mostly related to cleanly and correctly compacting nested with statements.</p>
| 2 |
implementing use of with object as f in custom class in python | pthe first google hit for me explains it simply enoughp
pa hrefhttpeffbotorgzonepythonwithstatementhtm relnofollowhttpeffbotorgzonepythonwithstatementhtmap
pand the pep explains it more precisely but also more verboselyp
pa hrefhttpwwwpythonorgdevpepspep0343 relnofollowhttpwwwpythonorgdevpepspep0343ap
| 2 |
is it possible to colour a specific item in a listbox widget | paccording to the codeeffbotorgcode documentation regarding the a hrefhttpeffbotorgtkinterbooklistboxhtmtkinterlistbox relnofollowcodelistboxcodea widget you cannot change the color of spefic itemsp
blockquote
pthe listbox can only contain text items and all items must have the same font and colorp
blockquote
pbut actually you can change both the font and background colors of specific items by using the a hrefhttpeffbotorgtkinterbooklistboxhtmtkinterlistboxitemconfigmethod relnofollowcodeitemconfigcodea method of your codelistboxcode object see the following examplep
precodeimport tkinter as tk
def demomaster
listbox tklistboxmaster
listboxpackexpand1 fillboth
inserting some items
listboxinsertend a list item
for item in one two three four
listboxinsertend item
this changes the background colour of the 2nd item
listboxitemconfig1 bgred
this changes the font color of the 4th item
listboxitemconfig3 fg blue
another way to pass the colour
listboxitemconfig2 bggreen
listboxitemconfig0 foregroundpurple
if name main
root tktk
demoroot
rootmainloop
codepre
| 2 |
matplotlib quiver and imshow superimposed how can i set two colorbars | psimply call codecolorbarcode twice right after each plotting call pylab will create a new colorbar matching to the latest plot note that as in your example the quiver values range from 01 while the imshow takes negative values for clarity not shown in this example i would use different colormaps to distinguish the two types of plots p
precodeimport numpy as np
import pylab as plt
create some sample data
dx nplinspace0120
xy npmeshgriddxdx
z x2 y
z2 x
pltimshowz
pltcolorbar
pltquiverxyz2width01linewidth1
pltcolorbar
pltshow
codepre
pimg srchttpistackimgurcom3fv8ipng altenter image description herep
| 2 |
delay a task until certain time | pyou could instead use the codepausecode package a hrefhttpspypipythonorgpypipause012 relnofollowhttpspypipythonorgpypipause012a taking an example from their documentation p
precodeimport pause datetime
dt datetimedatetime2013 6 2 14 36 34 383752
pauseuntildt
codepre
| 2 |
convert unicode codepoint to utf8 hex in python | precodedatafromfileufd9b
unicodedatafromfileunicodeescapeencodeutf8
codepre
| 2 |
how to make menuaddcommand work in tkinter on the mac | pi dont think you can do that with the native aqua tk on os x and you probably shouldnt try os x native menus dont work like that and tk tries to follow apples a hrefhttpsdeveloperapplecomlibrarymacdocumentationuserexperienceconceptualosxhiguidelinesmenuappearancebehaviorhtmlapplerefdocuid20000957ch23sw1 relnofollowhuman interface guide for menusa you need to have a menu bar with dropdown emcascadesem p
pthe codetkdocscode website has a good introduction to a hrefhttpwwwtkdocscomtutorialmenushtml relnofollowtk menus and their platform differencesa you emcouldem use an x11based tk on os x but that is not recommended as apple does not ship x11 servers anymore with os x and your app would look and behave oddly for os x usersp
| 2 |
python help reading csv file failing due to lineendings | pthe two occurrences of xd5 in line 194 and the last line have nothing to do with the problemp
pthe problem appears to be a bug or a misleading error message or incorrectvague documentation in the python 26 csv modulep
pin the file the lines are terminated by x0d aka r in the classic mac tradition the last line is not terminated but that is nothing to do with the problemp
pthe a hrefhttpdocspythonorglibrarycsvhtmlcsvreaderdocs for csvreadera say if csvfile is a file object it must be opened with the b flag on platforms where that makes a difference it is widely known that it does make a difference on windows however opening the file with rb or r makes no difference in this case still the same error messagep
pthe a hrefhttpdocspythonorglibrarycsvhtmlcsvdialectlineterminatordocs for csvdialectlineterminatora say the string used to terminate lines produced by the writer it defaults to rn note the reader is hardcoded to recognise either r or n as endofline and ignores lineterminator this behavior may change in the future it appears to be recognising r as newline but not as endoflineendoffieldp
pthe error message csverror newline character seen in unquoted field do you need to open the file in universalnewline mode is confusing its recognised r as a newline but its not treating newline as an endof line and thus implicitly endoffield p
pit appears necessary to open the file in ru mode to get it to work its not apparent why the same r recognised in universalnewline mode is any betterp
| 2 |
how to convert colors into strings with the same size | passuming you are using python 26 or newer you can use a hrefhttpdocspythonorglibrarystdtypeshtmlstrformat relnofollowcodestrformatcodeap
precodeprint 002102202formatselfr selfg selfb
codepre
pif you want hexadecimal probably you do then add an xp
precodeprint 002x102x202xformatselfr selfg selfb
codepre
| 2 |
writing header with dictwriter from pythons csv module | pa few optionsp
p1 laboriously make an identitymapping ie donothing dict out of your fieldnames so that csvdictwriter can convert it back to a list and pass it to a csvwriter instance p
p2 the documentation mentions the underlying codewritercode instance so just use it example at the endp
precodedwwriterwriterowdwfieldnames
codepre
p3 avoid the csvdictwriter overhead and do it yourself with csvwriterp
pwriting datap
precodewwriterowdk for k in fieldnames
codepre
porp
precodewwriterowdgetk restval for k in fieldnames
codepre
pinstead of the codeextrasactioncode functionality id prefer to code it myself that way you can report all extras with the keys and values not just the first extra key what is a real nuisance with dictwriter is that if youve verified the keys yourself as each dict was being built you need to remember to use extrasactionignore otherwise its going to slowly fieldnames is a list repeat the checkp
precodewrongfields k for k in rowdict if k not in selffieldnames
codepre
pp
precodegtgtgt f opencsvtestcsv wb
gtgtgt import csv
gtgtgt fns foo bar zotsplit
gtgtgt dw csvdictwriterf fns restvalhuh
dwwritefieldnamesfns no such animal
gtgtgt dwwriterowfns no such luck it cant imagine what to do with a list
traceback most recent call last
file ltstdingt line 1 in ltmodulegt;
file "c:\python26\lib\csv.py", line 144, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
file "c:\python26\lib\csv.py", line 141, in _dict_to_list
return [rowdict.get(key, self.restval) for key in self.fieldnames]
attributeerror: 'list' object has no attribute 'get'
>>> dir(dw)
['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
es', 'restval', 'writer', 'writerow', 'writerows']
# eureka
>>> dw.writer.writerow(dw.fieldnames)
>>> dw.writerow({'foo':'oof'})
>>> f.close()
>>> open('csvtest.csv', 'rb').read()
'foo,bar,zot\r\noof,huh?,huh?\r\n'
>>>
</code></pre>
| 2 |
how to create objects on the fly in python | puse a hrefhttpdocspythonorglibrarycollectionshtmlcollectionsnamedtuplecodecollectionsnamedtuplecodeap
| 2 |
python fabric passing host as arguemnt | precodefabfilepy
from fabricapi import run env
envuser root
envkeyfilename homeubuntusshidrsa
def test
runmkdir p homeubuntu
fabric fab test h 111111111111
gtgtgt1921689920 executing task test
gtgtgt1921689920 run mkdir p homeubuntu
gtgtgt
gtgtgtdone
codepre
ph opstion sets envhosts to the given commadelimited list of host strings
please check a hrefhttpdocsfabfileorgen16usagefabhtml relnofollowherea for detailed fab command usagp
por like thisp
precodefabfilepy
def setenvhostnone
if host is not none
envhosts host
envuser ubuntu
envkeyfilename homeubuntusshidrsa
def test
runmkdir p homeubuntu
fabric fab setenvweb01 test
snip
codepre
| 2 |
how to login users with email and log them out with django rest framework json web tokens | ol
liwhen using jwt for authentication youd usually store the token in the browsers localstorage or sessionstorage to logout you just remove the token theres nothing else to invalidateli
lione of the benefits of using this kind of approach for authentication is that tokens are not persisted in the database so you dont have to query a session store for anything when authenticatingli
lithis should be possible with a custom django authentication backend as wellli
ol
| 2 |
performance searching a string in a text file python | precodecounterword for word in mytext if word in mydates
codepre
pi think would work quickly well on ishp
| 2 |
writing list of dict into file in python | pheres a way to write out the data using a dynamic list of headersp
precodenewlist tablea columnc1 datatypeint
tablea columnc2 datatypevarchar
tablea columnc2 datatypenumeric
header newlist0keys
with openmyloglog w as log
logwritejoinheader
logwriten
for data in newlist
logwritejoindatah for h in header
logwriten
codepre
| 2 |
in python assign a value based on dictionary mapping | pyou reassigned codepoz0code to a different object namely the value of codesome value str0code the assignment operator codecode does not modify codepoz0codes value but changing the binding in the codedictcodep
| 2 |
how to avoid slack command timeout error | paccording to the slack a hrefhttpsapislackcomslashcommandsrespondingtoacommandslash command documentationa you need to respond within 3000ms three seconds if your command takes longer then you get the codetimeout was reachedcode error your code obviously wont stop running but the user wont get any response to their commandp
pthree seconds is fine for a quick thing where your command has instant access to data but might not be long enough if youre calling out to external apis or doing something complicated if you emdoem need to take longer then see the emdelayed responses and multiple responsesem section of the documentationp
ol
livalidate the request is okayli
lireturn a code200code response immediately maybe something along the lines of codetext ok got thatcodeli
ligo and perform the actual action you want to doli
liin the original request you get passed a unique coderesponseurlcode parameter make a codepostcode request to that url with your followup message
ul
licodecontenttypecode needs to be codeapplicationjsoncodeli
liwith the body as a jsonencoded message codetext all done codeli
liyou can return ephemeral or inchannel responses and add attachments the same as the immediate approachli
ulli
ol
paccording to the docs you can respond to a user commands up to 5 times within 30 minutes of the users invocationp
| 2 |
how to set utc offset for datetime | pthe a hrefhttpdocspythonorg2librarydatetimehtml relnofollowcodedatetimecode module documentationa contains an example codetzinfocode class that represents a fixed offsetp
precodezero timedelta0
a class building tzinfo objects for fixedoffset time zones
note that fixedoffset0 utc is a different way to build a
utc tzinfo object
class fixedoffsettzinfo
fixed offset in minutes east from utc
def initself offset name
selfoffset timedeltaminutes offset
selfname name
def utcoffsetself dt
return selfoffset
def tznameself dt
return selfname
def dstself dt
return zero
codepre
| 2 |
is there a standard function to iterate over base classes | pthere is a method that can return them all in method resolution order mro codeinspectgetmrocode see herep
pa hrefhttpdocspythonorglibraryinspecthtmlinspectgetmrohttpdocspythonorglibraryinspecthtmlinspectgetmroap
pit returns them as a tuple which you can then iterate over in a single loop yourselfp
precodeimport inspect
for baseclass in inspectgetmrofoo
do something
codepre
pthis has the side benefit of only yielding each base class once even if you have diamondpatterned inheritancep
| 2 |
python why do some packages get installed as eggs and some as egg folders | pa single egg file is in fact a zip archive with a particular directory structure inside per the a hrefhttpdocspythonorglibraryzipimporthtml relnofollowzipimporta documentation only codepycode codepyccode and codepyocode files can be imported from zip files so if the package needs to import other kinds of module resources like compiled c code codesocode files codepydcode files it wont work as a zip filep
pi dont know if this is the emonlyem reason that some eggs wont work as zip archives but i think it is the main reasonp
| 2 |
how to access index in a pandas hdstore pytables | pthe multiindex example from the a hrefhttppandaspydataorgpandasdocsdeviohtmlstoringmultiindexdataframes relnofollowdocsap
precodein 21 index multiindexlevelsfoo bar baz qux
one two three
labels0 0 0 1 1 2 2 3 3 3
0 1 2 0 1 1 2 0 1 2
namesfoo bar
in 22 dfmi dataframenprandomrandn10 3 indexindexcolumnsa b c
in 23 dfmi
out23
a b c
foo bar
foo one 0385666 0013980 1787451
two 0190728 0574169 0115581
three 0823308 1845204 0603430
bar one 0863913 1544945 0598322
two 0941484 1080205 0086216
baz two 0510657 0205781 1747204
three 1322135 1131720 0838862
qux one 0346890 0905762 0348206
two 1378711 0751701 2229486
three 0120956 0535718 0344610
codepre
pstore in table format note that in 013 you will pass codeformattablecodep
precodein 24 dfmitohdftesth5dfmitabletruemodew
codepre
pto retrieve a single column the mi are stored as columnsp
precodein 25 store pdhdfstoretesth5
in [26]: store.select_column('df_mi','foo')
out[26]:
0 foo
1 foo
2 foo
3 bar
4 bar
5 baz
6 baz
7 qux
8 qux
9 qux
dtype: object
in [30]: store.select_column('df_mi','bar')
out[30]:
0 one
1 two
2 three
3 one
4 two
5 two
6 three
7 one
8 two
9 three
dtype: object
in [31]: store.close()
</code></pre>
| 2 |
is any elegant way to make a list contains some integers to become a list contains some tuples | precodea2i a2i1 for i in rangelena2
codepre
pthis is of course assuming that lena is an even numberp
| 2 |
accessing a value in a tuple that is in a list | pa list comprehension is absolutely the way to do this another way that emshouldem be faster is codemapcode and codeitemgettercodep
precodeimport operator
newlist mapoperatoritemgetter1 oldlist
codepre
pin response to the comment that the op couldnt find an answer on google ill point out a super naive way to do itp
precodenewlist
for item in oldlist
newlistappenditem1
codepre
pthis usesp
ol
lideclaring a variable to reference an empty listli
lia for loopli
licalling the codeappendcode method on a listli
ol
pif somebody is trying to learn a language and cant put together these basic pieces for themselves then they need to emview it as an exerciseem and do it themselves even if it takes twenty hoursp
pone needs to learn how to emthink about what one wantsem and compare that to emthe available toolsem every element in my second answer should be covered in a basic tutorial strongyou cannot learn to program without reading onestrongp
| 2 |
python sort a list by most comment element | pif your list contains other lists you could convert nested lists to tuples first before countingp
precodefrom collections import counter
printcounterlistoftuplesmostcommon
printcountermaptuple listoflistsmostcommon
codepre
| 2 |
how do i write json data to a file in python | precodejsondumpdata opendatatxt wb
codepre
| 2 |
regular expression matching all but a string | pyou can make use of negative look aheadsp
pfor examplep
precodegtgtgt refindallraabb string
a bc def ghij
codepre
hr
ul
lipcodecode matches codecodepli
lipcodeaabbcode negative lookahead checks if codecode is not followed by codeaacode or codebbcodepli
lipcodecode matches ony or more character other than codecodepli
ul
hr
pstrongeditstrongp
pthe above regex will not match those which start with codeaacode or codebbcode for example like codeaabccode to take care of that we can add codecode to the lookaheads like p
precodegtgtgt refindallraabb string
codepre
| 2 |
standard solution for decoding additive numbers | pyou want to use binary operations to decode the original the following code actually returns the correct stringsp
precodegtgtgt flags user redo enqueue cache os
real application clusters sql debug
gtgtgt def getflagsvalue
flags
for i flag in enumerateflags
if value amp 1 ltlt i
flagsappendflag
return flags
gtgtgt print getflags22
redo enqueue os
codepre
pif you really just want the constantsp
precodegtgtgt def binarydecompositionvalue
return 1 ltlt i for i in xrangelenflags if value amp 1 ltlt i
gtgtgt print binarydecomposition22
2 4 16
codepre
| 2 |
django edit queryset objects without affecting database | pone simple method is to convert the queryset to a list the list will contain instances of your model you can do whatever you like with those instances and nothing will be saved to the database unless you call codesavecode or one of the other methods that writes to the databasep
precodedividendset stockdividendsetallorderbydate
dividends listdividendset
for dividend in dividends
dividendextravalue1 foo
dividendextravalue2 bar
now pass the dividends list to your template as part of your context rather than the qs
codepre
| 2 |
generator functions equivalent in java | phad the same need so wrote a little class for it here are some examplesp
precodegeneratorltintegergt simplegenerator new generatorltintegergt
public void run throws interruptedexception
yield1
some logic here
yield2
for integer element simplegenerator
systemoutprintlnelement
prints 1 then 2
codepre
pinfinite generators are also possiblep
precodegeneratorltintegergt infinitegenerator new generatorltintegergt
public void run throws interruptedexception
while true
yield1
codepre
pthe codegeneratorcode class internally works with a thread to produce the items by overriding codefinalizecode it ensures that no threads stay around if the corresponding generator is no longer usedp
pthe performance is obviously not great but not too shabby either on my machine with a dual core i5 cpu 267 ghz 1000 items can be produced in lt 003sp
pthe code is on a hrefhttpsgithubcommherrmannjavageneratorfunctionsgithuba there youll also find instructions on how to include it as a mavengradle dependencyp
| 2 |
python pep8 and multiline dict formatting | pput the opening curly brace on the assignment linep
precodeactivationgradclasses
activationforwardstrictrelu activationbackwardstrictrelu
activationforwardlog activationbackwardlog
activationforwardsincos activationbackwardsincos
codepre
pthere emrarelyem is a need to use codecode to escape a newline in python instead use codecode codecode and codecode to group expressions across multiple linesp
| 2 |
creating distinct objects in a function | pyou need to create two dictsp
precodev
codepre
por use a loopp
precodev for in range2
codepre
pyou are creating a two references to the same objectp
precodein 2 a 2
in 3 ida0
out3 140209195751176
in 4 ida1
out4 140209195751176
in 5 a0 is a1
out5 true
in 6 a for in range2
in 7 ida1
out7 140209198435720
in 8 ida0
out8 140209213918728
in 9 a0 is a1
out9 false
codepre
| 2 |
python convert string literal to float | pfloating point values cannot have a comma you are passing code123243123code as it is to float function which is not valid first split the string based on commap
precodes 123243123
print ssplit 123 24 3123
codepre
pthen convert each and and every element of that list to float and add them together to get the result to feel the power of python this particular problem can be solved in the following waysp
pyou can find the codetotalcode like thisp
precodes 123243123
total summapfloat ssplit
codepre
pif the number of elements is going to be too large you can use a generator expression like thisp
precodetotal sumfloatitem for item in ssplit
codepre
pall these versions will produce the same result asp
precodetotal s 0 123243123
for currentnumber in ssplit
total floatcurrentnumber
codepre
| 2 |
python memory management with list comprehensions | pi presume the issue is herep
precodesmallcustdictcustid1 customerdictcustid1
smallcustdictcustid2 customerdictcustid2
a loop to round out the remaining allids object to fill in 0 values
for customerid catalog in smallcustdictiteritems
for id in allids
if id not in catalog
smallcustdictcustomeridasin 00
codepre
pthe dictionaries from codecustomerdictcode are being referenced in codesmallcustdictcode so when you add to them you they persist this is the only point that i can see where you do anything that will persist out of scope so i would imagine this is the problemp
pnote you are making a lot of work for yourself in many places by not using list comps doing the same thing repeatedly and not making generic ways to do things a better version might be as followsp
precodeimport collections
import functools
import operator
customerdict collectionsdefaultdictdict
def simpearsoncustid1 custid2
declaring as a dict literal is nicer
smallcustdict
custid1 customerdictcustid1
custid2 customerdictcustid2
unchanged as im not sure what the intent is here
for customerid catalog in smallcustdictiteritems
for id in allids
if id not in catalog
smallcustdictcustomeridasin 00
dict views are setlike so the easier way to do what you want is the intersection of the two
si smallcustdictcustid1viewkeys amp smallcustdictcustid2viewkeys
if not is a cleaner way of checking for no values
if not si
return 0
made more generic to avoid repetition and wastefully looping repeatedly
parts listpart for part in zipvalueid for value in smallcustdictvalues for id in si
sums sumpart for part in parts
sumsqs sumpowi 2 for i in part for part in parts
psum sumfunctoolsreduceoperatormul part for part in zipparts
sum1 sum2 sums
sum1sq sum2sq sumsqs
unchanged
num psum sum1sum2lensi
den sqrtsum1sq powsum12lensi sum2sq powsum22lensi
again using if not
if not den
return 0
else
return numden
codepre
pnote that this is entirely untested as the code you gave isnt a complete example however it should be easy enough to use as a basis for improvementp
| 2 |
how to multiply a super large number with a super small number in python | pwhen multiplying an extremely large number by an extremely small number working with floats can introduce huge inaccuracies in your case the magnitude of the numbers is causing overflow errors so you have bigger problems than just inaccuracies p
pwhenever you find yourself in this situation it can be useful to first strongcheck if it is possible to stay in the integer domainstrong and massage the numbers a little first in your case it is possible and ill explain how below p
pone operand of the multiplication the extremely large number is 8000 samples from 10000 items use the closed form equation for the number of combinations where your sample size codencode is 10000 and the subset size codercode is 8000 exclam here is factorial which you can find in codemathfactorialcode in python p
precodecnr n r n r
codepre
pthe other operand code08 8000code is the extremely small number which by index laws is equal top
precode88000 108000
codepre
pso when we multiply these two numbers together the answer we want isp
precode 10000 88000
8000 2000 108000
codepre
plets call this number codexcode and then take logarithms of both sides working in the log domain will transform multiplications into additions and divisions into subtractions making things more manageablep
precodefrom math import log factorial
numerator logfactorial10000 8000log8
denominator logfactorial8000 logfactorial2000 8000log10
logx numerator denominator
codepre
pnow these numbers are of a magnitude that is usable in pythonp
pyou will find that codelogxcode is equal to approximately 3214 you now only need to observe that codeexplogx xcode to find your answer it is a very large but finite number p
| 2 |
idiomatic clojure equivalent of this python code | preading that python snippet it looks like you want the eventual output to look likep
precodecode load 0
load 1
add
store 0
labels entry 0
codepre
pits much easier to write the code once you have a firm description of the goal and indeed this is a pretty simple reduce there are a number of stylisticallydifferent ways to write the reductor but this way seems easiest to read for mep
precodedefn load asm
reduce fn keys code labels op arg1 amp args as instruction
if label op
code code
labels assoc labels arg1 count code
code conj code instruction
labels labels
code labels
asm
codepre
h3edith3
pthis version supports a codenamecode argument and simplifies the reduction step by not repeating elements that dont changep
precodedefn load name asm
reduce fn program op arg1 as instruction
if label op
associn program labels arg1 count code program
updatein program code conj instruction
code labels name name
asm
codepre
| 2 |
remove duplicate data from an array in python | pas you dont care about the order of the items you keep you could dop
precodegtgtgt intdd for d in datavalues
200012025 2002121575 2000121575
codepre
hr
pif you would like to keep the emlowestem item i cant think of a onelinerp
phere is a basic example for anybody who would like to add a condition on the key or value to keepp
precodeseen set
result
for item in sorteddata
key intitem or whatever condition
if key not in seen
resultappenditem
seenaddkey
codepre
| 2 |
python custom exception and subexceptions | pa standard technique would be to subclass codeconnectivityexceptioncode to create exception classes specific to each kind of error conditionp
precodeclass connectivityexceptionexception pass
class httpconnectivityexceptionconnectivityexception pass
class ftpconnectivityexceptionconnectivityexception pass
codepre
pthen instead of coderaise connectivityexceptioncode you can use coderaise httpconnectivityexceptioncode or coderaise ftpconnectivityexceptioncode depending on which specific type of error you want to indicate p
pmultiple exception blocks can be used to dispatch error handling according to the exception typep
precodetry
somenetworkoperation
except httpconnectivityexception as ex
this will execute if the error is an httpconnectivityexception
except ftpconnectivityexception as ex
likewise for ftpconnectivityexception
except connectivityexception as ex
the generic case this block will execute if the connectivityexception isnt
an instance of one of the earlier specified subclasses
codepre
pnote that the exceptionhandling blocks are tried in lexical order the first block specifying a class to which the exception object belongs will be used in this case that means that you need to put the codeconnectivityexceptioncode block last or else it will catch codehttpconnectivityexceptioncode and codeftpconnectivityexceptioncode as wellp
| 2 |
how to count values in a certain range in a numpy array | pyou could use codehistogramcode heres a basic usage examplep
precodegtgtgt import numpy
gtgtgt a numpyrandomrandomsize100 100
gtgtgt numpyhistograma bins00 73 224 555 77 79 98 100
array 8 14 34 31 0 12 1
array 0 73 224 555 77 79 98 100
codepre
pin your particular case it would look something like thisp
precodegtgtgt numpyhistograma bins25 100
array73 array 25 100
codepre
padditionally when you have a list of strings you have to explicitly specify the type so that codenumpycode knows to produce an array of floats instead of a list of stringsp
precodegtgtgt strings stri for i in range10
gtgtgt numpyarraystrings
array0 1 2 3 4 5 6 7 8 9
dtypes1
gtgtgt numpyarraystrings dtypefloat
array 0 1 2 3 4 5 6 7 8 9
codepre>
| 2 |
the r2 score i get from gridsearchcv is very different from the one i get from crossvalscore why sklearn python | puse codepredictorbestestimatorcode as the estimator in codecrossvalscorecode this is the one with the best parameters the way you choose it you are probably obtaining the initial estimator with default parameters you could check by putting the latter in codecrossvalscorecode as well and comparing resultsp
| 2 |
why does return listsort return none not the list | pcodelistsortcode sorts the list in place ie it doesnt return a new list just writep
precodenewlistsort
return newlist
codepre
| 2 |
trying to verify sha1 message signature using python what am i doing wrong | pyour code is work properly a hrefhttpsgistgithubcomkalloc5106808 relnofollowhttpsgistgithubcomkalloc5106808a
i see something else wrong herep
| 2 |
splitting on last delimiter in python string | puse a hrefhttpdocspythonorg2librarystdtypeshtmlstrrsplitcodersplitcodea insteadp
precodesrsplit 1
codepre
pdemop
precodegtgtgt s abcd
gtgtgt srsplit 1
abc d
gtgtgt srsplit 2
ab c d
codepre
pthis method starts splitting from the righthandside of the string by giving it a maximum you get to split just the righthandmost occurrencesp
| 2 |
how to generate a fully connected subgraph from node list using pythons networkx module | pi dont know of any method which does this but you can easily mimic the completegraph method of networkx and slightly change italmost like a builtinp
precodeimport networkx
import itertools
def completegraphfromlistl createusingnone
g networkxemptygraphlenlcreateusing
if lenlgt1
if gisdirected
edges itertoolspermutationsl2
else
edges itertoolscombinationsl2
gaddedgesfromedges
return g
s completegraphfromlista b c d
print sedges
codepre
| 2 |