text_a
stringlengths
9
150
text_b
stringlengths
18
20.9k
labels
int64
0
2
euler 3 python putting the prime numbers into a list
pthis will run quite slowly for large numbers consider the case in which the algorithm attempts to find the prime factors where num 1000000 your nested for loop will generate 1million operations before the next number is even consideredp pconsider using the sieve of eratosthones to get all of the prime numbers up to a certain integer it is not as efficient as certain other sieves but is easy to implement spend some time reading the theory behind the sieve before implementingthis will help your understanding of later problemsp pa hrefhttpenwikipediaorgwikisieveoferatosthenes relnofollowhttpenwikipediaorgwikisieveoferatosthenesap
0
trouble with named pipes
ptry to provide an absolute path tmptestpipe to be sure that both are looking to the same filep
0
how to re arrange this python code without breaking sqlalchemy relevant dependencies
pi dont have the capability to do any testing at my current location but i suggest moving all of that code to codemaincode as follows also codemytablecode subclasses codedeclarativebasecodep precodefrom sqlalchemy import createengine column integer from sqlalchemyorm import sessionmaker from sqlalchemyextdeclarative import declarativebase class mytabledeclarativebase tablename mytable tableargs autoload true id columninteger primarykeytrue monkey patching the id column as primary key def createpathfilename generate absolute path to filename def mainargv parse filename here from argv pathtofile createpathmyfilenamesqlite engine createenginesqlitepathformatpathpathtofile echofalse base mytable basemetadatacreateallengine session sessionmakerbindengine session session for row in sessionquerymytableall print row return stop if name main sysexitmain codepre
0
why is default variable off by one in function definition
pyour function definition wont work because the way you have defined your default arguments pythons default arguments are evaluated once when the function is defined not each time the function is called like it is in say ruby this means that if you use a mutable default argument and mutate it you will and have mutated that object for all future calls to the function as well your program will not work as you see below p pa hrefhttpistackimgurcomi5bhxpng relnofollowimg srchttpistackimgurcomi5bhxpng altenter image description hereap
0
python list segregation
pif the list is a text file you can use pandasp precodedf pdreadcsvfilepathsep codepre pim going to use a dummy df to show queryingp precodedf pddataframenparrayalaska12alabama12brooklyn12reshape33 ar2 dfvaluesn if dfvaluesn0startswitha else for n in rangelendfvalues df3 pddataframenparrayar2 df3tocsvoutputfile codepre
0
python define method outside of class definition
pnot sure if it fits you scenario but you ca derive from strongmyclassstrong and add the function you wantp
0
embed fckeditor in python app
pin order of difficultyp pif you just need to support windows you can embed ie in wx see the docs and demosp pwxwebkit is looking a bit more mature but its still in developmentp pyou could just use the webbrowser using webbrowseropenurl things will be very crude and interaction will be a painp pa fourth option you could try out pyjamas for your whole gui then run it all in a webbrowserp
0
create pandas dataframe from uneven data
peditp phere is a simple way to have what you want for one bearp precode recreating your data d meals425 children542 territory867 bear1 colorbrown grownsize7ft stats dataframed def beartodfbeardict df beardictstats for kv in beardictiteritems if k stats pass else dfk v return df in 32 beartodfbear1 out32 children meals territory color grownsize 0 5 4 8 brown 7ft 1 4 2 6 brown 7ft 2 2 5 7 brown 7ft codepre phow many bears do you have if you want to concatenate all your bearsdata in the same dataframe use pandasconcat p
0
fail to compile a python script with dependencies
ptry a hrefhttpsgithubcompyinstallerpyinstaller relnofollowpyinstallera it is very useful to make any executable and if you need a windows executable you have to compile it on windowsp
0
for every point in a list compute the mean distance to all other points
pbased on alims comment to the question take a look at scipyspatialdistancepdist i found a pure numpyscipy solutionp precodefrom scipyspatialdistance import cdist fct lambda p0p1 greatcircledistancep00p01p10p11 meandist npsortcdistpointspointsfct1mean1 codepre pdefinitely thats for sure an improvement over my list comprehension solutionp pwhat i dont really like about this though is that i have to sort and slice the array to remove the 00 values which are the result of computing the distance between identical points so basically thats my way of removing the diagonal entries of the matrix i get back from cdistp pnote two things about the above solutionp ul liim using codecdistcode not codepdistcode as suggested by alimli liim getting back an array of the same size as codepointscode which contains the mean distance from every point to all other points just as specified in the original questionli ul pcodepdistcode unfortunately just returns an array that contains all these mean values in a flat array that is the mean values are unlinked from the points they are referring to which is necessary for the problem as it ive described it in the original questionp hr phowever since in the actual problem at hand i only need the mean over the means of all points which i did not mention in the question codepdistcode serves me just finep precodefrom scipyspatialdistance import pdist fct lambda p0p1 greatcircledistancep00p01p10p11 meandistoverall pdistpointsfctmean codepre pthough this would for sure be the definite answer if i had asked for the mean of the means but ive purposely asked for the array of means for all points because i think theres still room for improvement in the above codecdistcode solution i wont accept this as the answerp
0
singleton python generator or pickle a python generator
pthis may not be an option for you but stackless python a hrefhttpstacklesscom relnofollowhttpstacklesscoma emdoesem allow you to pickle things like functions and generators under certain conditions this will workp pin foopyp precodedef foo with openfootxt as fi buffer firead del fi for line in buffersplitn yield line codepre pin footxtp precodeline1 line2 line3 line4 line5 codepre pin the interpreterp precodepython 26 stackless 31b3 060516 python266673766749m oct 2 2008 183131 ipython 091 an enhanced interactive python in 1 import foo in 2 g foofoo in 3 gnext out3 line1 in 4 import pickle in 5 p pickledumpsg in 6 g2 pickleloadsp in 7 g2next out7 line2 codepre psome things to note you emmustem buffer the contents of the file and delete the file object this means that the contents of the file will be duplicated in the picklep
0
python process text file with these criteria
precodeblacklist set1234567890 with openreachtxt as infile openoutreachtxt w as outfile for line in infile line linestrip if not line continue left line linesplit 1 parts prstriplstrip for p in linesplit parts p for ip in enumerateparts if not allchar in blacklist for char in p or ilenparts1 outfilewritesn joinparts codepre pwith your example codereachtxtcode i get p precodezsmcbge0424spvcos 1408 zsmcblk0424spvcos 1408 zsmcgry0424spvcos 1408 zsmcblk0525spvcos3 1408 zsmcgry0525spvcos2 1408 zsmcbge0424spvcos 1408 codepre
0
python decorator with options
pi like lennart regebro katrielalex and martineau answers above but at the risk of sounding very strongcornystrong i will risk writing a emstory basedem example p pin this two part story we can have strongteachersstrong that teach strongstudentsstrong from experiencep precodedef selftaughtteacherfn i teach students because i had no teacher to guide me def astudentreallifeissues detailsaboutmyworld im a student who has been trained by a teacher who has taught me about the problems i may encounter in real life thanks to my teacher for giving me extra knowledge print i have to remember what my teacher taught me myanswer fnreallifeissues detailsaboutmyworld print ah yes i made the right decision return myanswer return astudent selftaughtteacher def studentnamedlisapracticingmathslength width height print im consulting my powers of maths return length width height codepre plets see what the student knowsp precodegtgtgt answer studentnamedlisapracticingmaths10 20 height3 i have to remember what my teacher taught me im consulting my powers of maths ah yes i made the right decision gtgtgt answer 600 codepre pvery good in the emsecond part of the storyem we introduce a strongprofessorstrong who teaches others to become strongteachersstrong those strongteachersstrong then share what they learned with their strongstudentsstrongp precodedef professorwhotrainsteacherssubjects totrainteachers i am a profeseur i help train teachers def ateacherwhogetstrainedfn i learn subjects i should teach to my students knowledge s for s in subjects def astudentreallifeissues *details_about_my_world): ''' i'm a student who has been trained by a teacher who has taught me about the problems i may encounter in real life. thanks to my teacher for giving me extra knowledge. ''' print '(i know %s that i learned from my teacher,...)' % \ [information for information in knowledge] my_answer = fn(*real_life_issues, **details_about_my_world) print 'ah yes, i made the right decision.' # return my_answer # return a_student # # return a_teacher_who_gets_trained </code></pre> <p>so we can train a teacher and let them teach a student...</p> <pre><code>&gt;&gt;&gt; teacher1 = professor_who_trains_teachers('math','science') &gt;&gt;&gt; teacher1 &lt;function a_teacher_who_gets_trained at 0x104a7f500&gt; &gt;&gt;&gt; teacher1.__name__ 'a_teacher_who_gets_trained' &gt;&gt;&gt; @teacher1 def student_named_lisa_practicing_maths(length, width, height): print 'im consulting my powers of maths...' return length * width * height </code></pre> <p>that student knows their maths.. </p> <pre><code>&gt;&gt;&gt; answer = student_named_lisa_practicing_maths(20, 10, 2) (i know ['math', 'science'] that i learned from my teacher,...) im consulting my powers of maths... ah yes, i made the right decision. &gt;&gt;&gt; &gt;&gt;&gt; answer 400 </code></pre> <p>and we can create the teacher out-right as well.</p> <pre><code>@professor_who_trains_teachers('math', 'science', remember='patience') def student_named_lisa_practicing_maths(length, width, height): print 'im consulting my powers of maths...' return length * width * height </code></pre> <p>again the new student can do their maths...</p> <pre><code>&gt;&gt;&gt; answer = student_named_lisa_practicing_maths(10, 20, height=3) (i know ['math', 'science'] that i learned from my teacher,...) im consulting my powers of maths... ah yes, i made the right decision. &gt;&gt;&gt; &gt;&gt;&gt; answer 600 </code></pre>
0
how to sort a list with strings and integers
pi am not sure how exactly you want your arguments to be sorted but you can just call the builtin function codesortedcodep precodedef paramstolistparams return sortedlistparams codepre
0
how to display object properties in python
ptry to use codevarscode it gives objects attributes as a dictionnaryp blockquote pvarsobject dictionaryp pwithout arguments equivalent to codelocalscode brwith an argument equivalent to codeobjectdictcodep blockquote pexamplep precodegtgtgt class myobjobject pass gtgtgt obj myobj gtgtgt varsobj gtgtgt obja 1 gtgtgt varsobj a 1 codepre
0
dictreader is skipping two lines of my file
pif your file is really formatted as you describe you may need to put commas between the column namesp precodedate open high low codepre
0
i want to use python to list a directory then sort the filenames by size
pmaybe this will give you some ideas a hrefhttpwikipythonorgmoinhowtosorting relnofollowhttpwikipythonorgmoinhowtosortingap
0
installing pyodbc fails on osx 109 mavericks
pi met the the same problem today on ubuntu 1404 i found some guy in below link said should install unixodbcdevp pa hrefhttpscodegooglecomppyodbcissuesdetailid55 relnofollowhttpscodegooglecomppyodbcissuesdetailid55ap pi did it and then the pip install success p phope this helpfulp
0
how do i do tagbind on all tags in tkinter
puse a list or function assuming to you want to bind all tags the samep precodefor thistag in tagname1 tagname2 tagname3 treeviewtagbindthistag eventsequence clickhandler codepre
0
comparison of python and perl solutions to wide finder challenge
blockquote pthe perl implementation uses the mmap system call p blockquote pthis it avoids buffer copying and provides async iop
0
there is an error with my python program and i dont know whats wrong
blockquote ptypeerror unsupported operand types for str and intp blockquote pthis is telling you the operand codecode division is running into an error because it is trying to divide a codestrcode and an codeintcode you can check the type of variables with codetypecodep precodegtgtgt typebase ltclass strgt codepre pyou can make it an integer with the codeintcode functionp precodebase intbase gtgtgttypebase ltclass intgt codepre
0
regarding passing variables to an argument
pthe problem is that you dont need a codemaincode function just put the code unindented by itself and it will run when you run the programp
0
python how can i do a string find on a unicode character that is a variable
pin some cases i ignore when you will have to decode also the string that you are looking inp precodesdecodeutf8finduu0101 codepre
0
python construct consume data for optional field
pperhaps you could use an adapter similar to the lengthvalueadapter for a sequencep precodeclass lengthvalueadapteradapter adapter for lengthvalue pairs it extracts only the value from the pair and calculates the length based on the value see prefixedarray and pascalstring parameters subcon the subcon returning a lengthvalue pair slots def encodeself obj context return lenobj obj def decodeself obj context return obj1 class optionaldataadapteradapter slots def decodeself obj context if contextflag return obj else return none codepre psop precodestruct structstruct flagflag optionaldataadapterubint8optionaldata ubint8mandatory codepre
0
speeding up timestamp operations
pi would give this a try in bash using the date command date proves to be faster than even gawk for routine conversions python may struggle with thisp pto speed this up even faster export the column in a in one temp file column b in another ect you can even do this in python then run the 5 columns in parallel p precodefor column in a printgtgtthefilea column for column in b printgtgtthefileb column codepre pthen a bash scriptp precodeusrbinenv bash readarray a lt thefilea for i in a do date r item i done codepre pyoull want a master bash script to run the first part in python codepython pythonscriptpycode then you will want to call in each of the bash scripts in the background from the master codefileash ampcode that will run each column individually and will automatically designate nodes for my bash loop after readarray im not 100 that is the correct syntax if you are on a linux use codedate d itemcodep
0
using flask web app as windows application
pi do not currently have a windows client here so i cannot exactly test what i am suggestingp pusing strongpywinautostrong you can check for a windows namep pyou could build a script that checks this in background and kills your flask application when the requested browser window is not openedp precodefrom pywinautofindwindows import findwindows if not findwindowsbestmatchyourwindownamehere do your kill codepre
0
best method of importing scapy
p i often use when i do not want to overwrite my namespacep precodefrom scapy import all as scapy codepre pafter that everything is accessible under codescapycodep precodescapysendscapyipscapyicmp codepre
0
installed module in pythonstill i got error
pthere is several relatedduplicated answers but i personally accidentally use codesudocode to install some python packagesformulas and massed up with the permission p blockquote p brew doctor p blockquote pis your friend and you will find some good suggestions to fix you problemsp panother suggestion is use codevirtualenvcode for python google for your favorite tutorial and article to work with itp
0
creating a csv file for movie review corpus in python
precodedirectory rawinputinput folder output rawinputoutput folder txtfiles ospathjoindirectory txt for txtfile in globglobtxtfiles with opentxtfile rb as inputfile intxt csvreaderinputfile filename ospathsplitextospathbasenametxtfile0 csv with openbookcsv wb as outputfile outcsv csvwriteroutputfile outcsvwriterowsintxt codepre pi have tried this code it is working but the issue is each text file in the neg folder of the movie review corpus must come as one single row in the csv fileie the neg folder contains thousand file and i want that the new created csv should have thousand rows one row for the complete text of one text file but this is not happening the last file data is overwriting the previous file data and the last file data is appearing in multiple rows in the csv filep
0
how can i filter a date of a datetimefield in django
pin django 176 worksp precodemyobjectobjectsfilterdatetimeattrstartswithdatetimedate2009822 codepre
0
celery and signals
pif i understood correctly you want the same process to send ans receive the signal it sent if so why not usep precodeoskillosgetpid signalsiguser1 codepre pand define the handler for sigusr1 accordinglyp pif you want another process to get it you have to have its pid anyway to send signals to it so just use the same command i gave here with the proper pid instead of osgetpid unless i missed somethingp
0
moving items in a list a certain number of spaces
pi would use the lists slice notation a hrefhttpdocspythonorgtutorialintroductionhtmllists relnofollowhttpdocspythonorgtutorialintroductionhtmllistsap pfor example lets say you have a list like thisp precodel 1 2 3 4 5 6 7 8 codepre pand you wanted to move the element code4code over 1 space you could do something like thisp precodeindex 3 value 4 spaces 1 target index spaces length lenl dont replace the element l0target value ltargetindex lindex1length results in 1 2 4 3 5 6 7 8 do replace the element l0target value ltarget1index lindex1length results in 1 2 4 5 6 7 8 codepre pwith the parameters codeindexcode codevaluecode codespacescode and codetargetcode extracted this is general enough to extract into a nice function try it with other values not just 1 or 3 if codespacescode is too high the result will be the original listp pif you want to move the element right instead of left youll have to change the expression a bit but its the same ideap
0
python if element1 from list1 is equal to element2 from list2 change element1
ptry this it worksp h2solution 1h2 h2demo on a hrefhttpreplit0vg12 relnofollowreplitaeditedh2 h3codeh3 precodedef codeslst cods toadd c 0 for ind elem in enumeratelst if elem4 not in cods toaddappendelem strind c lstremoveelem c 1 for ind elem in enumeratelst tmp tmpappendelem4 tmpappendelem10 tmpappendelem810 tmpappendelem48 lstinsertind tmp lstremoveelem lstinsertintelem1 elemlenelem 1 for elem in toadd return lst first cara20130716 tara20080601 pala19961231 melo19601023 secnd pala cara tara print codesfirst secnd codepre h3outputh3 precodecara20130716 tara 01 06 2008 pala 31 12 1996 melo19601023 codepre hr h2solution 2h2 pif you want the match to be caseinsensitivep h2demo on a hrefhttpreplit0vg11 relnofollowreplitah2 h3code:</h3> <pre><code>def codes(lst, cods): for ind, cod in enumerate(cods): cods[ind] = cod.lower() toadd = [] c = 0 for ind, elem in enumerate(lst): if elem[:4].lower() not in cods: toadd.append(elem + str(ind+c)) lst.remove(elem) c += 1 for ind, elem in enumerate(lst): tmp = [] tmp.append(elem[:4]) tmp.append(elem[10:]) tmp.append(elem[8:10]) tmp.append(elem[4:8]) lst.insert(ind, tmp) lst.remove(elem) [lst.insert(int(elem[-1]), elem[:len(elem) - 1]) for elem in toadd] return lst first = ['cara20130716', 'tara20080601', 'pala19961231', 'melo19601023'] secnd = ['pala', 'cara', 'tara'] print codes(first, secnd) </code></pre> <h3>output:</h3> <pre><code>[['cara', '16', '07', '2013'], ['tara', '01', '06', '2008'], ['pala', '31', '12', '1996'], 'melo19601023'] </code></pre>
0
boost python overriding equality operator
ptry thisp precodedefself self defself self codepre preference a hrefhttpwwwboostorgdoclibs1570libspythondoctutorialdochtmlpythonexposinghtmlpythonclassoperatorsspecialfunctions relnofollowhttpwwwboostorgdoclibs1570libspythondoctutorialdochtmlpythonexposinghtmlpythonclassoperatorsspecialfunctionsap
0
wx validate controls in a container stops after first invalid
pto do this you would need to override codevalidatecode in your dialog and iterate over all controls yourself without stopping at the first invalid one like the base class implementation doesp punfortunately you will probably need to duplicate the a hrefhttpsgithubcomwxwidgetswxwidgetsblobwx302srccommonwincmncppl2026 relnofollowcode herea as there is no way to reuse it on the bright side you can use it almost as is with just changing the codereturn falsecode lines to remember the error instead and return it at the endp
0
installing psycopg2 postgresql in virtualenv on windows
pthere is an alternative to install python packages in your computer ie strongpipstrong you can download python packages by just executingp precode pip install pyscopg2 codepre pthe general format of the command isp precode pip install packagename codepre pps to install python packages globally through pip p precode sudo pip install packagename codepre
0
running a python program on a web server
pyou could create a simple cgi script a hrefhttpwikipythonorgmoincgiscripts relnofollowhttpwikipythonorgmoincgiscriptsa using the python cgi modulep peither as a wrapper around your python script or update the existing one put a text area box for pasting the contents or otherwise you need to upload the file and pass it on to your programp pthen print the content header and the results to stdout and they should show up in the browserp
0
first python screen scraping and smtp script wont evaluate properly
phave you tried logging the value of resp20 to see what values you are getting a simple p precodeprint resp20 codepre pwhile debuggingp
0
finding last occurence of substring in string replacing that
pnave approachp precodea a long string with a in the middle ending with fchar rchar a1replacefchar rchar1 11 out2 a long string with a in the middle ending with codepre hr paditya sihags answer with a single coderfindcodep precodepos arfind apos apos1 codepre
0
how to find a point inside an irregular polygon
phere is an algorithm i have used with successp pfind a point outside your polygon just choose an codexcode or codeycode greater than your maxp pdraw a line in your head from your point to the point outside your polygonp pcount the number of intersections of this line with the line segments that make up the perimeter of your polygon if it is odd the point is inside if even it is outsidep panother approach is to use a graphics polygon floodfill function to fill a red polygon on a white background and then see what colour your point isp
0
python dictionary pickling
ptry dumping each object in a separate filep precodewith openuelestutxt wb as f pickledumpuelestu f with openeleplstutxt wb as f pickledumpeleplstu f codepre
0
dynamically setting tablename for sharding in sqlalchemy
ptry thisp precodeimport zlib from sqlalchemyextdeclarative import declarativebase from sqlalchemy import column integer biginteger datetime string from datetime import datetime base declarativebase entityclassdict class absshardingclassbase abstract true def getclassnameandtablenamehashid return shardingclasss hashid shardingclasss hashid def getshardingentityclasshashid param hashid hashid type hashid int rtype absclientuserauth if hashid not in entityclassdict classname tablename getclassnameandtablenamehashid cls typeclassname absshardingclass tablename tablename entityclassdicthashid cls return entityclassdicthashid cls getshardingentityclass1 print sessionqueryclsget100 codepre
0
django orbitedstomp
pit seems that orbited is not suited for this kind of things i talked with orbited creator i switched to hookbox and it works fine p
0
python efficient way to read text file with varying delimiters spaces
puse re library with regex its an easy way to parse textp precodeimport re m researchltabcdef abcdef mgroup0 def codepre
0
python namespace elements visibility vs proper package structure
h2name and bindingh2 pyou can read a hrefhttpdocspythonorg2referenceexecutionmodelhtmlnamingandbinding relnofollowcodepython naming and bindingcodea and understand how python namespace worksp pa scope defines the visibility of a name within a block if a local variable is defined in a block its scope includes that block if the definition occurs in a function block the scope extends to any blocks contained within the defining one unless a contained block introduces a different binding for the name codethe scope of names defined in a class block is limited to the class block it does not extend to the code blocks of methods this includes generator expressions since they are implemented using a function scopecodep pbtw use codeglobalscode and codelocalscode can help debug for variable bindingp h2the user problemh2 pyou can try this insteadp precodefrom model import user as modeluser from foobarschema import user as schemauser codepre
0
timestamp from a txt file into an array
pa hrefhttppandaspydataorg relnofollowpandasa is supposed to be good at this sort of thing im no expert and had some trouble with the codeparsedatecode functionality of a hrefhttppandaspydataorgpandasdocsstableiohtmlioreadcsvtable relnofollowcodereadcsvcodea but the following seems to work reasonably well and fastp precodeimport pandas as pd names date time lat lon height q ns format ymdhmsf df pdreadcsvtmppos delimwhitespacetrue namesnames dfdatetime pdtodatetimedfdate dftime formatformat codepre hr pif you want to select data based on time stamps you can set it as the a hrefhttppandaspydataorgpandasdocsstabletimeserieshtmldatetimeindex relnofollowindex of the dataframeap precodedfindex pdtodatetimedfdate dftime formatformat print df20150218 2300020150218 23010 codepre pyou can also set the time column as the index but it seems directly slicing with only time is not supportedp precodeformat hmsf dfindex pdtodatetimedftime formatformat print df2300023010'] # prints empty dataframe </code></pre> <p>but <a href="http://stackoverflow.com/a/21627484/2379410">you can use the following</a>:</p> <pre><code>print df.between_time('2:30:00','2:30:10') </code></pre>
0
python metaclass properties override class attributes sometimes
phere is some very similar code that might help you understand whats happeningp precodeclass myclassobject def initself data selfdictupdatedata this would fail if i had selfa a property def aself return 1 myobject myclassa 2 print myobjecta print objectgetattributemyobject a print myobjectdicta codepre pwhat youre seeing is that the instance the class having both a descriptor your property on its class and an attribute of the same name normally there are safeguards to protect this but the way codetypecode works goes around themp pso you havep blockquote precode print myobjecta codepre blockquote pthe descriptor beats the codedictcode entry and the codepropertycode is called this is because of the implementation of codeobjectgetattributecode at least conceptuallyp blockquote precode print objectgetattributemyobject a codepre blockquote pthis is the same thing as saying codemyobjectacode except if codeobjectgetattributecode was overridden codegetattributecode is where the behavior of trying descriptors first comes fromp blockquote precode print typegetattributemyobject a codepre blockquote pthis is the same thing as codeobjectgetattributecode because codetypecode doesnt override codegetattributecodep blockquote <pre><code> print myobject.__dict__['a'] </code></pre> </blockquote> <p>this looks it up in your <code>__dict__</code>, which is the only place you stored <code>2</code>. this is just a dict object (maybe/almost), so it's not going to look stuff up anywhere else.</p> <blockquote> <pre><code> print myobject().a </code></pre> </blockquote> <p>the way that attribute works, you're not accessing your type's attributes the same way you would directly. this is probably the part that doesn't have a super-intuitive answer</p>
0
python regex over list of strings
precodefor i in p t refindallsrc alt i print t codepre pupdatep precodekrefindallsrc alti for i in p item for sublist in k for item in sublist codepre pa hrefhttpwwwsamplecomtestjpg relnofollowhttpwwwsamplecomtestjpga a hrefhttpwwwsamplecomtest2jpg relnofollowhttpwwwsamplecomtest2jpgap
0
matplotlib surface plot extends past axis limits
pemmanual data clippingemp pone approach ive seen that works is to emmanually clip the dataem eg your example would be updated to p precodefrom matplotlib import from mpltoolkitsmplot3d import axes3d import matplotlibpyplot as plt import numpy as np from pylab import import math fig pltfigure ax figaddsubplot111 projection3d x nparange5 5 01 y nparange5 5 01 x y npmeshgridx y z x2 y2 axsetzlim10 20 for i in rangelenx for j in rangeleny if zji lt 10 or zji gt 20 zji nan axplotsurfacex y z alpha09 rstride4 cstride4 linewidth05 cmapcmsummer pltshow codepre pstrongnotestrong p pthis can be done concisely for this case using p precodezzgt20 nan codepre presulting in p pimg srchttpistackimgurcomstx2njpg altenter image description herep
0
pyside button auto repeat doesnt start until mouse is moved
pi was having a similar problem using normal qt4x on linux the issue was that something was connected to the clicked signal i think it was stealingchanging the focus of the mouse i just changed that item to connect to the the released signal that doesnt mean you cant connect to clicked but just be sure that there are no focus stealing sideeffectsp
0
python mechanize module selecting all input fields within a form
pfound something that might be of use herep pa hrefhttpstockrtgithubcompemulatingabrowserinpythonwithmechanize relnofollowhttpstockrtgithubcompemulatingabrowserinpythonwithmechanizeap precode select the first index zero form brselectformnr0 codepre
0
why doesnt my code correctly create a list of tuples
pi would add on top of the other answers that this is not the best way to get the intersection of two sets why not simply use a hrefhttpdocspythonorg2librarysetshtmlsetobjects relnofollowpython setsa p precode class lexiconobject def barself sentence return setsentencesplit amp setdirection codepre pi find this both clearer and more efficientp
0
python rectangle of asterisks
pthis doesnt sound much like a rectangle to me but the way i would do this is to use a conditional expression that selects the length of each row according to the remainder when the row number is divided by twop pit would look like thisp precoderows intinputnumber of rows for this design stars intinputnumber of stars on the first row for row in rangerows len stars if row 2 0 else stars 1 print len codepre pstrongoutputstrongp precodenumber of rows for this design 9 number of stars on the first row 6 codepre
0
recursion none python
pmay i suggest that you use beautifulsoup it is easy to learn has good documentation a hrefhttpwwwcrummycomsoftwarebeautifulsoupbs4doc relnofollowhttpwwwcrummycomsoftwarebeautifulsoupbs4docap pa soup object can be instantiated using the code below where markup is a string containing your xml or input file handle to the xml filep precodebeautifulsoupmarkup xml codepre
0
why am i not getting the full text of this page
pthe problem is that youre trying to parse python source code as html and then strip the text back out of itp pso line 318 isp precode if sysversioninfo lt 2 6 codepre pthis happens to be the first codeltcode character in the file since youre trying to parse it as html that means that the whole rest of the file is part of an html tag that never gets finishedp pdepending on which of the three parsers you use and which versions bs4 may decide its not a tag after all and give you your original data or raise an exception or strip out the whole bogus tagp panyway the fix is simple dont parse python source code as html just write thisp precodeurllib2urlopenurlhrefread codepre
0
python script working when run in cmd but not when run from file
ptry to put the lib in the same folder of the script and it should workp
0
facebook serverside login without php
pi have a python library that does thisp ul lia hrefhttpsgithubcomjvanascofacebookutils relnofollowhttpsgithubcomjvanascofacebookutilsali ul pits on pypi as well p pthe main file shows how youd integrate it on the serverside and template for pyramid doing it in django flask whatever would be similarp
0
convert index of series object in panda
pdo you meanp precodegtgtgt s 330 0064591 331 0705979 332 0516967 dtype float64 gtgtgt df a 20131125 074952584591 0064591 20131126 074952584626 0705979 20131127 074952584633 1516967 gtgtgt dffroms pddataframes columnsdfcolumns gtgtgt dffromsindex dfindex gtgtgt df dffroms a 20131125 074952584591 true 20131126 074952584626 true 20131127 074952584633 false codepre
0
python selenium questions href
pfor single elementp pcodedriverfindelementbyxpathadataemberaction1517textcodep pif you want to get text from all similar codeltagtcode elements on pagep precodealist driverfindelementsbyxpathpclassinfoadataemberaction for element in alist print elementtext codepre
0
editing form and saving into database
pupdate your view function like this to return form for get request as wellp precodedef edititemrequest itemid if requestmethod post item itemobjectsgetiditemid your existing code else if its get request item itemobjectsgetiditemid form additeminstanceitem return rendertoresponseforsalehtml locals contextinstancerequestcontextrequest codepre pnote you need to handle case when item with codeitemidcode does not exists in the db in that case do not use codeinstancecode parameter to instantiate the formp
0
regular expression to match start of filename and filename extension
pthis probably doesnt fully comply with filenaming standards but here it goesp precoderunwpy codepre
0
pyplot 3d scatter points at the back overlap points at the front
pthanks you so much for your explanation i thought it could be something like that indeed but i forgot to say in my question that the same thing happened no matter the order of the axscatter commands what is pretty weird i found out before reading your answer that that does not happen with the axplot command therefore i replacedp precodeaxscatterouterzn outerxn outeryn cblack marker lw0 axscatterinnerzn innerxn inneryn cred marker lw0 codepre pbyp precodeaxplotouterzn outerxn outeryn markersize1 colorblack axplotinnerzn innerxn inneryn markersize1 colorred codepre pand i got the following picturep pa hrefhttpistackimgurcomhtaywpng relnofollowimg srchttpistackimgurcomhtaywpng altenter image description hereap pwhich works for me i know however that if i change the point of view i will have the red shell appearing on top of the black one one problem i found later was that the plot function does not have vmin and vmax arguments as the scatter one which makes it harder to define the color as a gradient starting in vmin and vmax p
0
need help looping
pi am no expert in python but i think i see what your problem isp paccording to your code here youre asking the user for a number of any size once theyve input this number then program proceeds to execute a for loop salary number of times this can be a problem if youve made the employees salary something huge like 10000 as this will cause the loop to execute 10000 timesp pim guessing that youre trying to make sure that the salary is somewhere between 0 and 200000 and if the salary falls outside of this range then the program will continue to ask for a salary if this is indeed the case a while loop should do the trick while eliminating a couple lines of codep precodedef empsalaryempnameesalary salary 0 salary intinputwhat is their salary while salary lt 1 or salary gt 200000 salary intinputwhat is their salary codepre pthis should do what you need good luck on your assignmentp
0
format python code in spyder ide
pi tried this p blockquote psource fix indentation remove trailing spacesp blockquote pthis is not the most efficient way but it seems there are no key combinations to do these even in preferences they have not allowed to add new shortcut for thisp
0
python nan json encoder
punfortunately you probably need to use bramars suggestion youre not going to be able to use this directly a hrefhttpsdocspythonorg2libraryjsonhtml relnofollowthe documentationa for pythons json encoder statesp blockquote pif specified default is a function that gets called for objects that cant otherwise be serializedp blockquote pyour codenanconverterdefaultcode method isnt even being called since pythons json encoder already emknowsem how to serialize codenpnancode add some print statements youll see your method isnt even being calledp
0
python regex to extract substring at start and end of string
pdo you need a regex herep precodegtgtgt address myfile10456csv gtgtgt splitbyperiods addresssplit gtgtgt formataddress0 address1 gtgtgt myfilecsv codepre
0
reconstruct python method with kwargs with marshal and types
pafter some more searching i discovered the dill package which allows you to pickle more things than cpickle the reason i was using marshal when you directly reconstruct a serialized function not using the funccode you avoid this keyword issue i was havingp
0
404 error with static files served through djangoapache bitnami
pfrom the documentation a hrefhttpswikibitnamicombitnamicloudhostingbasestack relnofollowhttpswikibitnamicombitnamicloudhostingbasestacka it seems like amazon ec2 uses apache version 2229 you should change codehttpdconfcode to cover both that version and the one in your other setupp precodeltdirectory optbitnamiappsdjangodjangoprojectsdatadashboardprojectstaticgt ltifversion lt 23 gt order allowdeny allow from all ltifversiongt ltifversion gt 23gt require all granted ltifversiongt ltdirectorygt codepre
0
fastest ways to keywise add a list of dicts together in python
pits simple but this could workp precodea x 10 y 05 z 025 b w 05 x 02 ds a b result for d in ds for k v in diteritems resultk v resultgetk 0 n lends result dictk amtn for k amt in resultiteritems print result codepre pi have no idea how it compares to your method since you didnt post any codep
0
amazon ses hide recipient email addresses
pwe use the sendrawemail function instead which gives more control over the make up of your message you could easily add bcc headers this wayp pan example of the code that generates the message and how to send itp precodefrom emailmimemultipart import mimemultipart from emailmimetext import mimetext msg mimemultipartalternative msgsubject testing bcc msgfrom noreplyexamplecom msgto userotherdomaincom msgbcc hiddenotherdomaincom codepre pwe use templating and mimetext to add the message content templating part not shownp precodepart1 mimetexttext plain utf8 part2 mimetexthtml html utf8 msgattachpart1 msgattachpart2 codepre pthen send using the ses sendrawemailp precodesesconnsendrawemailmsgasstring codepre
0
how to install and cron python3 scrapy on cloud linux
pit appears as though you do not have the bzip module installed on your cloud server it may very well be linked to a lack of the bzip2 library being missingp pin order to install it you can typep precodeaptget install bzip2 codepre pyou may need to prefix that command with codesudocodep pin all honesty it should be working out of the box as this is one of pythons major strengths hopefully this helpsp
0
cherrypy accessing the uriroute parameters inside a tool hook
pcherrypyurl will get you the complete uri but i suspect thats not quite what youre looking forwhy do you need it if youre trying to form your location variable based on the uri you probably want pathinfo instead of the complete urip precodelocation sviews requestappconfigapplicationpath if requestpathinfoendswith fname ssindexhtml location requestpathinfo else fname sshtml location requestpathinfo codepre
0
nlargest elements in an sequence need to retain duplicates
phows about this it doesnt emexactlyem return your desired result since it reversesorts on codeycodep precode split lot by first element of values lots defaultdictlist for x y z in lot lotsxappendy z ans for x l in lotsiteritems find top3 unique values top nlargest3 setz for y z in l ans x y z for z y in sortedz y for y z in l if z in top reversetrue print ans codepre
0
django comparing datetimenow with pubdate
precodeimport datetime if somedatetime gt datetimedatetimenow datetimetimedeltadays10 return somedate is greater than the current datetime plus 10 days codepre psee timedelta doc a hrefhttpdocspythonorglibrarydatetimehtmldatetimetimedelta relnofollowhttpdocspythonorglibrarydatetimehtmldatetimetimedeltaap
0
edit response logo in web2py
pjust change the content of the anchor tag to include the imagep precoderesponselogo aimgsrcurlstatic imageslogolbpng hrefurldefault index codepre pnote you dont really need to use coderesponselogocode at all you can instead just put the relevant html directly in the layouthtml viewp
0
method overriding
porder matters if names are samelast function you defined is processing in your case itsp precodedef gxy return xy codepre
0
python 27 print error
pthe print function is specific to python 3 you have two solutions herep pwritep precodefrom future import printfunction codepre pso you can use it as specified by cdarkep por you use print as a simple statement as it should be with older versions of python codeprint hello worldcodep
0
the dateaxisitem sometimes becomes invisible
pim not sure what happens with your dateaxisitem as you know its not yet merged into the main development branch of pyqtgraph however for your particular application it might be easier to start from scratch and define your own timeaxisitem if you start from the following code what functionality would be missingp precodeclass timeaxisitemaxisitem def initself orientation kwargs superinitorientation kwargs def tickstringsself values scale spacing return selfgettickv spacing for v in values def gettickself ts spacing dt datetimedatetimefromtimestampts here you can decide on the accuracy of the time data displayed depending on the spacing if spacing gt 60 return 02d02d dthour dtminute else return 02d02d02d dthour dtminute dtsecond codepre
0
issues with cors flask angularjs
pis the post sending content i had a similar issuee when the body was null if it is adding either an empty body when the object is falsy or adding the contentlength header as 0 both seemed to workp precodescopesyncup function var objtosend scopetransactions transactions scopetransactions httpposthttpmoneybooksdev9001apibudgetsrouteparamsbudgetidtransactions objtosend codepre
0
how can i create a folder system inside of my python program
pnot sure why writing to the file is a problem but you could basically have a tree type data structure to represent a file system for examplep precodeclass file def initself filename directoryfalse selffilename filename selfdirectory directory selffiles if directory else none codepre pwhere codeselffilescode is a list of file objects that you can iterate through as a tree this is obviously rudimentary and ill leave a more detailed implementation up to youp
0
redirect sysstdout to a file without buffering in python 3
pthe issue seems to be in the way you open the file p precodeopenlogfile w 0 codepre pfrom a hrefhttpsdocspythonorg3libraryfunctionshtmlopen relnofollowpython 3x documentationa p blockquote popenfile moder strongbuffering1strong encodingnone errorsnone newlinenone closefdtrue openernonep blockquote pthe third argument for codeopencode determines the buffering mode for the file code0code means no buffering i do not think you can make it work by just using codewbcode instead of codewcode p pyou should remove that code0code third argument and let codeopencode use default line buffering for text files example p precodeopenlogfile w codepre
0
using web2py for a user frontend crud
blockquote pthis doubleredundant way of talking to my db strikes me as odd and web2py does not support python3p blockquote pany abstraction you want to use to communicate with your database whether it be the web2py dal the django orm sqlalchemy etc will have to have some knowledge of the database schema in order to construct queriesp peven if you programmatically generated all the sql statements yourself without use of an ormdal your code would still have to have some knowledge of the database structure ie somewhere you have to specify names of tables and fields etcp pfor existing databases we aim to automate this process via introspection of the database schema which is the purpose of the extractmysqlmodelspy script if that script isnt working you should report an issue on github andor open a thread on the web2py google groupp palso note that when creating a emnewem database web2py helps you avoid redundant specification of the schema by handling migrations including table creation for you so you specify the schema emonlyem in web2py and the dal will automatically create the tables in the database of course this is optionalp
0
installing numpy for python 27
pi generally just avoid the whole numpy install process by using the anaconda distribution from a hrefhttpcontinuumio relnofollowcontinuumioa no i am not a paid spokesperson haha but in reality whether you use anaconda or even the enthought distribution this is a lot easier than trying to install these packages with pip p
0
filtering specific rows in a csv file in python
precodefor mycsvline in csvreader if mycsvline4 abc append to result codepre
0
why is magicfrombuffer returning none
pim not sure the reason for the issue could be the version but ive been able to workaround it with something likep precodemime magicfrombufferdata mimetrue if mime none workaround for issue with libmagic15092 in ubuntu 1204 fixed in libmagic 5112 filestr magicfrombufferdata if filestrstartswithcomposite document file v2 document mime applicationmsword codepre pnot great but gets the job done until its possible to upgrade the server and get a new version of libmagicp
0
split a string into exactly n pieces
pheres the pseudocode i dont know python but probably useful as a general purpose algorithmp precodereglen lt intlenstrn the integer portion only firstlen lenstr n reglen output goes into output array of length n elements each a substring output1 leftstr firstlen for i lt 2 to n startposition lt firstlen i2 reglen 1 outputi lt midstr startposition reglen loop codepre
0
python embedding pyimportimport not from the current directory
pthere is a good way because this is the way it is frequently done with sitepackesp precodeimport sys syspathappenddirectory syspath is a list of all directories to import from codepre por you use p precodeoscwddirectory change the working directory codepre pbefore the importp pan other way is uglyp precodeimport types sys m typesmoduletypemodule sysmodulesmodule m exec openfileread in mdict python3 codepre pmaybe you asked for a cfunction to do your work but i do not know onep
0
returning unique values in csv and unique strings in pythonpandas
pi think the following should work for almost any dataframe it will extract each value that is unique in the entire dataframep ppost a comment if you encounter a problem ill try to solve itp precode replace all nones nas by spaces so they wont bother us later df dffillna preparing a list listsets iterates all columns much faster than rows for col in dfcolumns list containing all the unique values of this column thisset listsetdfcolvalues creating a combined list listsets listsets thisset doing a set of the combined list finalset listsetlistsets for completions sake you can remove the space introduced by the fillna step finalsetremove codepre h3edit h3 pi think i know what happens you must have some float columns and fillna is failing on those as the code i gave you was replacing missing values with an empty string try those p ol lidf dffillnanpnan emoremli lidf dffillna0li ol pfor the first point youll need to import numpy first codeimport numpy as npcode it must already be installed as you have pandasp
0
what class to use for money representation
pit depends what youd like to use codemoneycode for p pfor financial modelling of price and risk codedoublecode pythons codefloatcode is good enough because all models are inaccurate some of them are useful though so one doesnt get any useful extra precision by using infinite precision numbersp pfor currency conversions you need currency rates the currency rate one can get in practise depends on the amount and other factors again currency rate conversion is just a multiplication and it is often implemented by distinct class codeccypaircodep
0
python extract time from date column to plot
pfirst convert your timestamps to python a hrefhttpsdocspythonorg2librarydatetimehtml relnofollowdatetimea using a hrefhttpsdocspythonorg2librarydatetimehtmlstrftimestrptimebehavior relnofollowdatetimestrptimedatestring formatap precodeimport datetime liststring 20160415 060001704 fmt ymd hmsf listdatetimes datetimedatetimestrptimeliststring fmt codepre pthen convert the datetimes to matplotlib format using a hrefhttpmatplotliborgapidatesapihtmlmatplotlibdatesdate2num relnofollowdate2numap precodeimport matplotlib x matplotlibdatesdate2numlistdatetimes codepre pnow you are able to plot using a hrefhttpmatplotliborgapipyplotapihtmlmatplotlibpyplotplotdate relnofollowplotdateap precodeimport matplotlibpyplot as plt pltplotdatex y codepre plimit x axis by using a hrefhttpmatplotliborgapipyplotapihtmlhighlightxlimmatplotlibpyplotxlim relnofollowxlimap precodepltxlimxmax codepre
0
python how to use part of function outside function
precodeclass movieobject def initselftitletodayreturntimelt selftitle title def timeofreturnself selftoday today selfreturntime returntime today datetimedatetimenow returntime today datetimetimedeltadays30 def returnfeemovie fee 2 delta today returntime codepre pthats because codeinitcode is taking arguments that using for class from outsidebut when you use your movie class you have to define that argumentsp
0
shelveopen failing on creation
pi found out that when i was pushing to the repository git wasnt including the directory i was looking in because it was empty if you try to use codeshelveopencode with an argument that is in a directory that doesnt exist it will give you an io error i simply forced the creation of the directory and now it worksp
0
overriding a parents classmethod with an instance method
pi dont think the problem is with parents or inheritance but simply with calling an instance method from a class methodp precodeclass barobject def callerselfxcx printbar callerself selfmyfnx classmethod def classcallerclsxccx printbar class callercls clsmyfnx def myfnselfxnone printin bar instanceselfx def reprself return barinstance barmyfn in bar instance barinstance none barmyfnbar in bar instance barinstance none barcaller bar caller barinstance in bar instance barinstance cx barclasscallerbar bar class caller ltclass mainbargt in bar instance barinstance none barclasscallerbar same the following produce typeerror unbound method myfn must be called with bar instance barmyfn barcaller barclasscaller barclasscaller codepre pwith this single class i can readily call codemyfncode from the instance codecallercode method but have pass a separate codebarcode instance if using codeclasscallercode calling the classmethod with codebarcode is no different from calling it with codebarcodep peven if a classmethod is called with an instance its the codeklasscode that is passed through not the codeobjcode a hrefhttpdocspythonorg2howtodescriptorhtmlstaticmethodsandclassmethods rel"nofollow">http://docs.python.org/2/howto/descriptor.html#static-methods-and-class-methods</a></p> <pre><code>class classmethod(object): "emulate pyclassmethod_type() in objects/funcobject.c" ... def __get__(self, obj, klass=none): if klass is none: klass = type(obj) def newfunc(*args): return self.f(klass, *args) return newfunc </code></pre> <p>why are you using <code>@classmethod</code>? do you call them with just class name, or with instances? even if the parent class versions don't use instance attributes, it might simpler to use instance methods at all levels. python got along for many years without this decorator (added in 2.4).</p>
0
how do i parse lines from a log file
pin perl this should do itp precodeconsider the a variable has the log file my a ltltlog filegtgt my desiredanswer regex if a mproto ig desiredanswer1 codepre
0
placing vertices of graphs wxpython
pyou want a graph drawing algorithm there is ongoing research in this area but a simple forcedirected algorithm can give good results for small graphs look at a hrefhttpenwikipediaorgwikiforcebasedalgorithms28graphdrawing29 relnofollowthis wikipediaa article for the algorithm you can also get some open source libraries that handle this problem like a hrefhttpnodeboxnetcodeindexphpgraph relnofollownodeboxa and a hrefhttpgraphvizorg relnofollowgraphvisap
0
best way to replace x00 in python lists
ptry a unicode pattern like thisp precoderesubux00 s codepre pit should give the following resultsp precodel textx00x00x00 datax00x00x00 rsrcx00x00x00 for x in l for s in l print resubux00 s count 1 text data rsrc codepre por using list comprehensionsp precoderesubux00 s for s in x for x in l codepre pactually should work without the u in front of the string just remove the first 3 slashes and use this as your regex patternp precodex00 codepre
0
replacing all keys and values in nested python dictionary with new values
pi have taken a recursive approach which if the value of the data is dictionary try to replace the keys and values else it treats the data as a single value and try to convert itp pcodereplacedictcode is the dictionary which points out how to convert values and codedatacode are the current valuesp precodedef replacekeyvaldata replacedict if typedata dict return replacedictk replacekeyvalv replacedict for kv in dataiteritems return replacedictdata codepre
0
create plot first then add inside a figure
pit isnt possible to move an codeaxescode from one figure to another the axes is linked to the figure upon creationp pinstead youll have to first generate the figure and then the codeaxescodees within that figurep
0
how to modify query string in python cgi
ptry using urlparse module a hrefhttpdocspythonorglibraryurlparsehtml relnofollowhttpdocspythonorglibraryurlparsehtmlap
0
python derived class call a global variable which initialized in superclass
pfinally i edit my code like thisp pbasepyp precodeclass baseobject def initself driver selfdr driver global dr dr driver codepre ponepyp precodeclass onebase def initself driver superinitdriver global dr dr selfdr def funself printdr if namemain driver 1 test onedriver testfun codepre pmaybe its not very elegant and i dont know if it is a good solution but i can use dr variable in derived classes as many times as i want and dont need the self to call itp
0