text_a
stringlengths
9
150
text_b
stringlengths
18
20.9k
labels
int64
0
2
reading gzipped data in python
pthe codegzipcode module will only open a single file that has been compressed ie codemyfilegzcode you have a codetarcode archive of multiple files that are also compressed this needs to be both untarred and uncompressedp ptry using the codetarfilecode module instead see a hrefhttpsdocspythonorg2librarytarfilehtmlexamples relnofollowhttpsdocspythonorg2librarytarfilehtmlexamplesap pedit to add a bit more information on what has happened you have successfully opened the zipped tarball into a gzip file object which will work almost the same as a standard file object for instance you could call codefreadlinescode as if codefcode was a normal file object and it would return the uncompressed linesp phowever this did not actually unpack the archive into new files in the filesystem you did not create a subdirectory cdatagrantfilesf and so when you try to use the path codesubsetdatapathcode you are looking for a directory that does not existp pthe following ought to workp precodeimport tarfile subsetpathcdatagrantfiles tar tarfileopensubsetfulltargz tarextractallsubsetpath subsetdatapathospathjoinsubsetpathsubsetfull codepre
0
if mystr test why does mystr4 produce error out of range but mystr4 does not
pbecause array accesses are defined such that its an error for a lone index to be out of range but not for part or all of a slice to be if any part of a slice is out of range it simply yields no results rather than triggering an errorp
0
how can i create a simple system wide python library
pthe quick way if youre just making something for your own use and not worrying about packaging is to put the module which could be as simple as a single file in your systems codesitepackagescode directory on debianbased systems a hrefhttpstackoverflowcomquestions9387928whatsthedifferencebetweendistpackagesandsitepackagesyou probably want to use codedistpackagescode insteadap pto find out where your codesitepackagescodecodedistpackagescode directory is start python andp precodegtgtgt from sys import path gtgtgt path usrlibpython34sitepackagespip712py34egg usrlibpython34zip usrlibpython34 usrlibpython34platcygwin usrlibpython34libdynload usrlibpython34sitepackages codepre pnote the last item in that example codeusrlibpython34sitepackagescode thats the sort of thing youre looking for so in this example if i save the following to codeusrlibpython34sitepackagesfoopycodep precodedef bar printhello world codepre pthen from anywhere on my systemp precodegtgtgt from foo import bar gtgtgt bar hello world codepre
0
no such child pyval error
ptry thisp precodefor elt in root eldata for child in eltgetchildren if childtag in skipfields continue eldatachildtag childpyval dataappendeldata codepre
0
sikuli in loop mode
pjust wrap it in a loop like thisp precodeimport time while true timesleep1200 1200 sec 20 min your code codepre
0
python linked list and traversing
pthere is a builtin function in python called codereducecode which traverses a list and compresses it with a given function that is if you have a list of five elements codeabcdecode and a function codefcode it will effectively do p precodetemp fab temp f temp c codepre pyou should be able to use this to write a very neat solutionp pif you want to be less abstract you will need to iterate over each element of the list in turn storing the greatest number so far in a variable change the variable only if the element you have reached is greater than the value of said variablep
0
update multiples fields with sql alchemy
pyou can just supply that dictionary to the update clause p precodedata email mynewemailexamplecom age 20 city london country uk language english profession developer employeer bbc userqueryfilterbyusernameadminupdatedata dbsessioncommit codepre
0
python getting the max value of y from a list of objects
pcodeycode isnt defined as a variable its an attribute of individual codegsnodecode objects you cant use it as a name on its ownp pto access the individual attributes you can use something like codekeylambda x xycode or codeattrgettercode from the codeoperatorcode modulep
0
why is this tiny pygame program freezing and doing nothing
pyou need to update the screen try it withp precodescreen pygamedisplaysetmode640360032 codepre pand in the loop write p precodepygamedispayflip codepre pto close the window completely you can usep precodesysexit codepre pjust be sure to include sys in your importsp
0
sorting lists of tuples based on a list of tuples python
pthis would be easy were codelist2code a a hrefhttpdocspythonorglibrarystdtypeshtmldict relnofollowcodedictcodea like thisp precodebobby otherthings something othervalues suzy stuff codepre ppython will do the conversion for youp precodegtgtgt dict2 dictlist2 codepre pthen you can use a a hrefhttpdocspythonorgtutorialdatastructureshtmllistcomprehensions relnofollowcodelist comprehensioncodeap precodegtgtgt kdict2k for k in sortedlist1 reversetrue if k in dict2 suzy stuff something othervalues bobby otherthings codepre pstrongnbstrong a hrefhttpdocspythonorglibraryfunctionshtmlsorted relnofollowcodesortedcodea is a builtin python function and a bad choice for a variable namep
0
python how to convert a list of dictionaries values into intfloat from string
precode newlist make an empty list for i in list loop to hv a dict in list s make an empty dict to store new dict data for k in ikeys to get keys in the dict of the list skintik change the values from string to int by int func newlistappends to add the new dict with integer to the list codepre
0
except valueerror not tripping python 34
pyour codetryexceptcode doesnt cover the initial user input and so the codevalueerrorcode isnt actually caught if you enter an codeintcode outside the bounds defined 0 x 10 as the first input then you can see the codetryexceptcode blocks workingp pyoull need to refactor your code so that the first input request is inside your try block and the loop or wrap the existing input request in another codetryexceptcodep palso as a side note codeinputcode can take a string argument that will be displayed as a prompt to the userp precodeselection intinputwhich program would you like to run codepre
0
reversing a number using class in python
pcan do this as well p precodereturn evalstrnumber1 codepre
0
how to do validation on djangos manyrelatedmanager
pi found a similar question that is not exactly what i wanted but helps as a workaroundp precodereceiverm2mchanged sendermymodelmyfieldthrough def checksender kwargs if kwargsaction preadd add anothermodelobjectsfilterpkinkwargspkset instances being added your validation here codepre pthanks to a hrefhttpstackoverflowcomusers213000mamachankomamachankoa on his a hrefhttpstackoverflowcomquestions2881368djangohowtooverridearelatedsetsaddmethodquestionap
0
amazon s3 permissions
pive been dealing with this too don who wrote the a hrefhttpundesignedorgza20071022amazons3phpclass relnofollows3 phpa class im using pointed out you can use dirs inside buckets so you can put your file in a dir with a random string and then redirect to that mybucketamazonnetwef49kfe4j409jf4f4f9jdfdmyfilezip while not at all secure you can control access to it by changing permissions or creating and deleting it keep the original securely in a different bucket as necessaryp
0
regular expression not matching the value
pu use a invalid regex pattern you may use rltsswsws replace ltltsswsws in fandall methodp pgood luckp
0
make global variables available in multiple modules
pthe answer seems to be by matthiasp puse from appnamemodules import settings and then access the data in the module with settingsvalue according to pep8 the style guide for python code wildcard imports should be avoided and would in fact lead to undesirable behaviour in this casep pthanks you all for the helpp
0
is there an easy way to create derived attributes in django modelpython classes
pyouve got two options i can think of right nowp ol lisince you dont want the field in the database your best bet is to define a method on the model that returns selfid someconstant say you call it bigid you can access this method anytime as yourobjbigid and it will be available in templates as yourobjbigid you might want to read about the magic dot in django templatesli liif you dont mind it being in the db you can override the save method on your object to calculate id someconstant and store it in a bigid field this would save you from having to calculate it every time since i assume id isnt going to changeli ol
0
django aggregate with foreignkey
pyou basically already have an answerp pcodestatusapplicationscode is a queryset that contains a set of related objects statuses you are asking for codestatusapplications0code would be the first code1code second and so onp pto access the count of each simply dop precodefor status in statusapplications print status statustotal codepre pif you need the whole rows of the table then simply dont use values or leave it emptyp precodeapplications developmentassessmentobjectsannotatetotal countstatus codepre porp precodeapplications developmentassessmentobjectsvaluesannotatetotal countstatus codepre
0
tkinter get data from a entry widget
pthanks fiver for your advice metaphys solution works i solved the problem modifying line 28 in p padduser topleveluserlistp
0
python osmakedirs not working in home directory
pcan you try running the program without using sudop pi am guessing when you are using codesudocode command you are going into the context of the super user which has a different home directory than your current user hence you are seeing the log files getting created in coderootlogscode p
0
calculate number of minutes by passing milliseconds
pmilliseconds to minutesp precodey milisec 1000 y 60 minutes y 60 codepre ponelinerp precodeminutesmilisec10006060 codepre pfinal resultp precodedef returntimestringmilisec minutesmilisec10006060 return d minutes if minutes else na codepre
0
error with flasklogin
pi cant seem to find the place where you assign the userid to the session after validating the formp precodesessionuserid formuserid codepre phave a look at this a hrefhttpsgithubcommarchonflasksimpleregistrationblobmasterflaskextsimpleregistrationpy relnofollowsimpleregistrationforma on github as an examplep
0
finding the corresponding value in python
phere are a couple of ways to improve your codep ol liwhen you are working with files its always best to a hrefhttpsdocspythonorg3tutorialinputoutputhtmlmethodsoffileobjects relnofollowcodeclosecodea your file after working with it or wrap your snippet of code in a a hrefhttpsdocspythonorg3referencecompoundstmtshtmlthewithstatement relnofollowcodewithcodea block this closes your file automaticallyli liyou are iterating multiple times through the lines in your file which isnt necessary there are much more performant approaches to solve your problemli ol pthis code worked for mep precodeimport csv with openautompgdatacsvr as f csvf listcsvreaderf bestmpg 0 bestrow 0 for ij in enumeratecsvf if i 0 continue bestmpg maxbestmpg floatj0 if bestmpg floatj0 bestrow i print csvfbestrow3 output toyota codepre
0
good way of handling nonetype objects when printing in python
pif not scorenone logginginfonewscore scorep porp plogginginfonewscore s strscore p
0
automate google play search items in a list
pive written a little demo that may help you to achieve your goal i used requests and beautiful soup its not exactly what you wanted but it can be adapted easilyp precodeimport requests import bs4 companyname airbnb def getcompanycompanyname r requestsgethttpsplaygooglecomstoresearchqcompanyname soup bs4beautifulsouprtext htmlparser subtitles soupfindalla classsubtitle devurls for title in subtitles try text titleattrstitlelower sometimes there is a subtitle without any text on gplay catchs the error except keyerror continue if companyname in text url httpsplaygooglecom titleattrshref devurlsappendurl return devurls def getcompanyappsurldevurl r requestsgetdevurl soup bs4beautifulsouprtext htmlparser titles soupfindalla classtitle return httpsplaygooglecomtitleattrshref for title in titles def getappcategoryappurl r requestsgetappurl soup bs4beautifulsouprtext htmlparser developername soupfindspan itempropnametext appname soupfinddiv classidapptitletext category soupfindspan itempropgenretext return developername appname category devurls getcompanyairbnb appsurls getcompanyappsurldevurls0 getappcategoryappsurls0 gtgtgt getcompany("airbnb") ['https://play.google.com/store/apps/developer?id=airbnb,+inc'] &gt;&gt;&gt; get_company_apps_url("https://play.google.com/store/apps/developer?id=airbnb,+inc") ['https://play.google.com/store/apps/details?id=com.airbnb.android'] &gt;&gt;&gt; get_app_category("https://play.google.com/store/apps/details?id=com.airbnb.android") ('airbnb, inc', 'airbnb', 'travel &amp; local') </code></pre> <p>my script with google</p> <pre><code>dev_urls = get_company("google") apps_urls = get_company_apps_url(dev_urls[0]) for app in apps_urls: print(get_app_category(app)) ('google inc.', 'google duo', 'communication') ('google inc.', 'google translate', 'tools') ('google inc.', 'google photos', 'photography') ('google inc.', 'google earth', 'travel &amp; local') ('google inc.', 'google play games', 'entertainment') ('google inc.', 'google calendar', 'productivity') ('google inc.', 'youtube', 'media &amp; video') ('google inc.', 'chrome browser - google', 'communication') ('google inc.', 'google cast', 'tools') ('google inc.', 'google sheets', 'productivity') </code></pre>
0
converting a list with many items into single item lines in python
puse a codecollectionsdefaultdictcodep pyou might want to search so for similar questions p
0
django rest framework pagination
pa hrefhttpwwwdjangorestframeworkorgapiguidepagination relnofollowhttpwwwdjangorestframeworkorgapiguidepaginationap blockquote ppagination is only performed automatically if youre using the generic views or viewsets if youre using a regular apiview youll need to call into the pagination api yourself to ensure you return a paginated response see the source code for the mixinslistmodelmixin and genericsgenericapiview classes for an examplep blockquote pa hrefhttpsgithubcomtomchristiedjangorestframeworkblobmasterrestframeworkmixinspyl35 relnofollowhttpsgithubcomtomchristiedjangorestframeworkblobmasterrestframeworkmixinspyl35a a hrefhttpsgithubcomtomchristiedjangorestframeworkblobmasterrestframeworkgenericspyl166 relnofollowhttpsgithubcomtomchristiedjangorestframeworkblobmasterrestframeworkgenericspyl166ap pso i would suggest something likep precodeapiviewget permissionclassesallowany def officesrequest paginationclass apisettingsdefaultpaginationclass paginator paginationclass queryset officeobjectsall page paginatorpaginatequerysetqueryset request serializer officeserializerpage manytrue return paginatorgetpaginatedresponseserializerdata codepre
0
curl request in python
peasiest using the coderequestscode library in python heres an example using python 27p precodeimport requests import json payload ajax 1 htd 20131111 pnp1 htvl req requestsposthttpwwwgooglecomtrendshottrendshotitems datapayload print reqstatuscode prints out status code print jsonloadsreqtext prints out json data codepre
0
how do i loop a menu that has submenus in python
pi have a couple of suggestionsp ol licreate a function menu to a display the menu b reject invalid response and c returns a valid response this menu will remove redundancy in your code as you need it 3 timesli limove the selling logic into a separate function lets call it sellli lilikewise move the buying logic to buyli liuse underscore to make you identifiers variables and function names easier to read i prefer mainmenuresponse over playermenumainli ol pwith these suggestions my implementation isp precodedef menuprompt choices print nn0nformatprompt count lenchoices for i in rangecount print 0 1formati 1 choicesi response 0 while response lt 1 or response gt count response rawinput type a number 10 formatcount if responseisdigit response intresponse else response 0 return response def buystockamount bondamount response menuwhat to buy stocks bonds nevermind do something def sellstockamount bondamount response menuwhat to sell stocks bonds nevermind do something main program starts here ============================================================= stockamount=10000 bondamount=10000 main_menu_response = 0 while main_menu_response != 3: main_menu_response = menu('what to do?', ['buy', 'sell', 'end']) if main_menu_response == 1: buy(stockamount, bondamount) elif main_menu_response == 2: sell(stockamount, bondamount) </code></pre>
0
how to run a continuous loop and add input to text
pfrom what i can understand just try p precodecontinuesy while 1 if continues y fname inputenter first namet lname inputenter second namet telephone inputenter telephone numbert print continues inputcontinuet outfilewritefname outfilewritelname outfilewritetelephone outfileclose else printfile written break codepre
0
order of base classes and super usage in multiple inheritance
pthe difference is simply the order of classes in mro of class codeacode in both casesp precodeclass a1b1 b2 pass class a2b2 b1 pass printa1mro printa2mro codepre pwhich returnsp precodeltclass maina1gt ltclass mainb1gt ltclass mainb2gt ltclass objectgt codepre pandp precodeltclass maina2gt ltclass mainb2gt ltclass mainb1gt ltclass objectgt codepre pnow when you call codea1fcode or codea2fcode the attribute is found in codeb1code and there you call codesupertempcode which means call codetempcode on the next class foundor move on to class next to it not until codetempcode is not found and so on in codemrocodep pas the next and only class in case of codea2code is codeobjectcode which has no codetempcode method an error is raised p pin case of codea1code next class after codeb1code is codeb2code which has a <code>temp()</code> method, hence no error is raised. </p>
0
simplegui inputs into a variable
pyou can retrieve the input string by calling the codegettextcode method of the variable that is assigned to the input fieldbrp blockquote ploginvariable loginguigettextp blockquote pplease note that you will still have to define an input handler function somewhere but can leave it blank and do not name it codeloginvariablecode as youre using it to store the input textp precodedef inputhandlerinput pass logingui frameaddinputlogin inputhandler 20 codepre psource simplegui a hrefhttpwwwcodeskulptororgdocshtmlgettext relnofollowdocumentationap
0
http post request from a pyqtgui
pwell its straight forward p p1 drag and drop the gui elements onto a widget using qtdesigner save it eg virustotaluip p2 use pyuic4 to convert the ui file to a python file pyuic4 virustotalui o virustotalpyp p3 then copy the above given code into the file p p4 sense for the clicked signal from a push button and assign it a slot that packages your parameter dictionary and then do as usual p precodeselflineedit1 qtguiqlineeditself url selflineedit2 qtguiqlineeditself api key selfpushbutton qtguiqpushbuttonself send button qtcoreqobjectconnectselfpushbutton qtcoresignalclicked selfdoit def doitself parameters url strselflineedit1textapikey strselflineedit2text data urlliburlencodeparameters req urllib2requesturl data response urllib2urlopenreq json responseread print json codepre pthis is a basic layout of how the code will run further detailing has to done according to your needsp
0
cant turn off images in selenium firefox
pi had this problem the solution is bellow in 3 steps 1 creating new profile for firefox in windows completely close firefox press windowr write codefirefoxexe pcode then press enter and create a new profile 2open firefox with the created profile then open aboutconfig in navigation bar and find codepermissionsdefaultimagecode and make its number 2 3change your code like bellowp precodeprofilesini profile new profilesini firefoxprofile myprofile profilegetprofileyourprofilename webdriver driver new firefoxdrivermyprofile codepre
0
firing events in mvc specifically in php if its needed
pthere are many ways on how the different components on mvc are linked together i think there is no golden rulep pi use it the way shown in this picturep pimg srchttpistackimgurcomvz7n1png altenter image description herep pthe creation of objects is then like thisp ol lithe app object creates a controller depending on the route the router is injected into the controllerli lithe controller creates a model depending on the route the model is created by a ioc containerli lithe controller creates a view and injects the model into the viewli ol pin my situation i can answer your questions like thisp pq1 no i do not use events there is no need the controller calls the model and when done the model has state and can be used by the viewp pq2 i do it just the other way the controller creates the model the model has no knowledge about the controller or viewp pq3 this is the way i implement itp
0
python average similar values in list and create new list with averaged values
pjust after making my question someone responded to it with the following codep precodefrom collections import ordereddict a 1 101 102 2 3 4 441 d ordereddict for item in a dsetdefaultintitem025 appenditem a sumitem lenitem for item in ditervalues print a 101 2 3 4033333333333333 codepre pso far this code works very good although i havent tested every detail of it thanks to whoever posted it and deleted it afterwardsp
0
python3pip installed but returns command not found
pyou can always use codepython3 m pipcode possibly with codesudocode if the library is available like installed to the right place this does not depend on pip being installed as a normal command which is just a shortcut for thisp
0
digraph nearest node that joins all paths
pyou can do something like thisp pfor each node find the list of all its ancestors and descendants if sizeancestors sizedescendants 1 is equal to network size it is a candidate now find such a node with at at least one ancestor and maximum number of descendantsp pthe list of ancestors and descendants can be calculated pretty easily let me know if you are not sure and i will expand my answerp
0
how to make a python code for this functionfn
phere is a quick and dirty approachp precodefrom itertools import combinationswithreplacement as cwr for xyz in cwrrange2 20 3 num x 1 y 1 z 1 1 denom x y z if num denom 0 print formatx y z num denom num denom codepre pwhich givesp precode2414 224 112 2 codepre pand extending it to four variables givesp precode2222 80 16 5 codepre
0
how do i create a new file on a remote host in fabric python deployment tool
pstringio with put works with a little bit of editing try thisp precodeputstringiostringio import sys os syspathinsert0 rubyswwwsdjangoprojects syspathinsert0 rubyswwwsdjangoprojectsproject import djangocorehandlerswsgi osenvirondjangosettingsmodule projectsettings application djangocorehandlerswsgiwsgihandler userhostuserhost remotepath codepre pif you have an issue with permissions try thisp precodeputstringiostringio import sys os syspathinsert0 rubyswwwsdjangoprojects syspathinsert0 rubyswwwsdjangoprojectsproject import djangocorehandlerswsgi osenvirondjangosettingsmodule projectsettings application djangocorehandlerswsgiwsgihandler userhostuserhost remotepath usesudotrue codepre
0
how can i get the created date of a file on the web with python
pi built a tool that does this based on etags sounds a lot like what youre describingp pa hrefhttpgithubcomdustinpfetch relnofollowpfetcha is a twisted tool that does this on a schedule and can run with many many urls and trigger events upon change postdownload its pretty simple but still might be more complicated than you wantp pa hrefhttpgithubcomdustinsnippetstreemasterpythonnethttpfetchpy relnofollowthis codea however is exactly what youre asking forp pso take your pick p
0
merging arrays slices in python
pid use some kind of bitmap for example extending your codep precodedataabcabdabdabbcbababdbcabbdbacbbcdb slicesindices 0lendata for i in xrange0100 startintrandomrandomlendata endstart 10 slice datastartend slicesindicesstartend 1 lenslice codepre pive used a codelistcode here but you could use any other appropriate data structure probably something more compact if your data is rather bigp pso weve initialized the bitmap with zeros and marked with ones the selected chunks of data now we can use something from codeitertoolscode for examplep precodefrom itertools import groupby groups groupbyslicesindices codepre pcodegroupbycode returns an iterator where each element is a tuple codeelement iteratorcode to just count gaps you can do something simple likep precodegaps lenx for x in groups if x0 0 codepre
0
what format should the file for configparser be
pas taken from the a hrefhttpsdocspythonorg2libraryconfigparserhtml relnofollowdocumentationap blockquote pthe configuration file consists of sections led by a section header and followed by name value entries with continuations in the style of rfc 822 see section 311 long header fields namevalue is also accepted note that leading whitespace is removed from values the optional values can contain format strings which refer to other values in the same section or values in a special default section additional defaults can be provided on initialization and retrieval lines beginning with or are ignored and may be used to provide commentsp pconfiguration files may include comments prefixed by specific characters and comments may appear on their own in an otherwise empty line or may be entered in lines holding values or section names in the latter case they need to be preceded by a whitespace character to be recognized as a comment for backwards compatibility only starts an inline comment while does notp pon top of the core functionality safeconfigparser supports interpolation this means values can contain format strings which refer to other values in the same section or values in a special default section additional defaults can be provided on initializationp pfor examplep blockquote precodemy section foodir dirswhatever dirfrob long this value continues in the next line codepre pyou are pretty free in writing what ever you want in the settings filep pin your particular case you just need to copy amp paste your keys and tag and configparser should do the restp
0
how to insert value from a list into other at position of space
phmm not a very common problemp precodeiabcdefghi j rfd qf while in j and i jjindex ipop0 print j output abc rfd def ghi qf codepre
0
write xml with beautiful soup
pfrom the docs a hrefhttpwwwcrummycomsoftwarebeautifulsoupdocumentationhtmlprinting20a20document relnofollowyou can turn a beautiful soup document or any subset of it into a string with the codestrcode function or the codeprettifycode or coderendercontentscode methods you can also use the codeunicodecode function to get the whole document as a unicode stringap pthen just write that string to a file as you would any other stringp
0
python scapy loading http from a file
pi am very new to python in general scapy in particular but is this what you are looking forp precodefrom scapyall import def httprequestpkt if pkthaslayerhttprequest use httpresponse for response packets pktshow exit0 omit to show more then the first packet pkts rdpcaprootdesktopexamplenetworktrafficpcap for p in pkts httprequestp for sniffing packets sniffprnhttprequest codepre pi think the problem may be the way scapy exorts packets when i run your code and inspect the packet in wireshark the protocol is listed as tcp when i use wireshark to capture the same type of packet it lists the protocol as http if i export the packet from wireshark and read it using rdpcap you get the results you are looking for ie the httprequesthttpresponse layers i dont know this for fact but i checked the a hrefhttpbiotcomcapstatsbpfhtml relnofollowberkeley packet filter syntaxa and they dont list http as a protocol if scapy is based on the bpf syntax and they dont use the http protocol maybe it exports the packet with a protocol of tcp and scapyhttp just parses the raw load during sniff just a guessp
0
prevent php from sending multiple emails when running parallel instances
pyou will need to lock the row in your database by using a transactionp ppsuedo codep precodestart transaction select row for update update row commit if mysqliaffectedrows connection gt1 sendemail codepre
0
unicodeencodeerror ascii codec cant encode character uu2730 in position 1 ordinal not in range128
pyou just need to codeencodecode the textp precodelinktextencodeutf8 codepre palso you can use coderequestscode instead of urllib2p precodeimport requests baseurl httpomahacraigslistorgsys url httpomahacraigslistorgsya filename craigstvstxt soup beautifulsouprequestsgeturlcontent with openfilename a as f writer csvwriterf delimiter for link in soupfindalla classrecompilehdrlnk timeset timestrftimemd hm itemurl urljoinbaseurl linkhref itemsoup beautifulsouprequestsgetitemurlcontent do smth with the itemsoup or why did you need to follow this link writerwriterowtimeset linktextencodeutf8 itemurl codepre
0
kivy how to access kivy widget in python
pto change widgets properties in kivy you need to link the widget between py and kv file first in py filep precodetxtsearch objectproperty codepre pthen in kv file in your root widgetp precodetxtsearch txtsearch codepre pthen assign the id to a widget as you already didp precodeltmaingt textinput id txtsearch text codepre pthen in your py file you can change attributes of the widget by doing thisp precodeselftxtsearchtext new text codepre por any other attributep precodeselftxtsearchheight 30dp codepre
0
how to execute one python file for a certain amount of time and after that run another
pif youre on windows and are lazy you could create a batch job that does p precodepython firsttaskpy sleep 7200 python secondtaskpy codepre
0
converting a string to dictionary in python value error
pthat string really is valid json i think just use the codejsonloadscode functionality to get a dictionaryp
0
is regex always greedy even when i give it look ahead and look behind requirements
pyou can do it in a faster way without regex like thisp precodes twgghuntw res join if xlowerhun else x for x in ssplit codepre
0
installing matplotlib on codenvy
pthe output is the followingp pmatplotlib yes 143 python yes 279 default mar 1 2015 125724 gcc 492 platform yes linux2p prequired dependencies and extensionsp pnumpy yes not found pip may install it belowp psix yes six was not foundpip will attempt to install it after matplotlibp pdateutil yes dateutil was not found it is required for date axis support pipeasyinstall may attempt to install it after matplotlib pytz yes pytz was not found pip will attempt to install it after matplotlibp ptornado yes tornado was not found it is required for the webagg backend pipeasyinstall may attempt to install it after matplotlibp ppyparsing yes pyparsing was not found it is required for mathtext support pipeasyinstall may attempt to install it after matplotlib pycxx yes couldnt import using local copyp plibagg yes pkgconfig information for libagg could not be found using local copyp pfreetype no the cc header for freetype2 ft2buildh could not be found you may need to install the development packagep ppng no pkgconfig information for libpng could not be foundp pqhull yes pkgconfig information for qhull could not be found using local copyp psome dependencies are missing p ptake a look at similar threadsp pa hrefhttpstackoverflowcomquestions27024731matplotlibcompilationerrortypeerrorunorderabletypesstrintmatplotlib compilation error typeerror unorderable types str lt intap pa hrefhttpstackoverflowcomquestions20904841installingmatplotlibanditsdependencieswithoutrootprivilegesinstalling matplotlib and its dependencies without root privilegesap
0
dynamically creating classes in python their constructors
pthe problem is that codeicode variable inside the codelambdacode is evaluated only when you create an instance of the class youve defined in a loop at this time the loop would finish and codeicode would be set to the last item in the list codeparrotcodep pyou should pass codeicode to the lambdap precodezooclassesi typei animal dictinitlambda self ii animalinitself i codepre pdemop precodegtgtgt class animal def initself name selfname name gtgtgt zoo lion bear parrot gtgtgt zooclasses gtgtgt for i in zoo zooclassesi typei animal dictinitlambda self animalinitself i gtgtgt i parrot gtgtgt zooclasseslionname parrot gtgtgt for i in zoo zooclassesi typei animal dictinitlambda self ii animalinitself i gtgtgt zooclasseslion"]().name 'lion' </code></pre> <p>also, thanks to @brenbarn's comment, see a better explanation here: <a href="http://stackoverflow.com/questions/13355233/python-lambda-closure-scoping">python lambda closure scoping</a>.</p> <p>hope that helps.</p>
0
how to find for specifc elements in a list
pyou can use a loop and an if condition to add it to your separate listp precodefor rows in myoriginallist if row0 year and row1 month newfilteredlistappendrow codepre
0
fine control over the font size in seaborn plots for academic papers
pit is all but satisfying isnt it the easiest way i have found to specify when setting the context egp precodesnssetcontextpaper rcfontsize8axestitlesize8axeslabelsize5 codepre pthis should take care of 90 of standard plotting usage if you want ticklabels smaller than axes labels set the axeslabelsize to the smaller ticklabel value and specify axis labels or other custom elements manually eg p precodeaxssetylabelmylabelsize6 codepre pyou could define it as a function and load it in your scripts so you dont have to remember your standard numbers or call it every timep precodedef setpubfig snssetcontextpaper rcfontsize8axestitlesize8axeslabelsize5 codepre pof course you can use a hrefhttpmatplotliborguserscustomizinghtml relnofollowconfiguration filesa but i guess the whole idea is to have a simple straightforward method which is why the above works well p pnote if you specify these numbers specifying codefontscalecode in codesnssetcontextcode is ignored for all specified font elements even if you set itp
0
python regular expression to find dates in list
pyou can try code belowp precodeimport re elements 12010220153410520155another example6 for element in elements matches rematchrd12d12d4 element if matches is not none print 0gt21gt22formatmatchesgroup1 matchesgroup2 matchesgroup3 codepre
0
do something for every fifth object in a list
pwhy not make list for each row in the square and then put those rows into a listp precodesquarelist rowlist1 rowlist2 rowlist3 rowlist4 rowlist5 codepre pthis way you can manipulate a column as you loop through the rowsp precodefor row in squarelist dosomethingrow4 codepre pyou can also extract a column using a list comprehensionp precodecollist1 row0 for row in squarelist codepre
0
basic python functions mathematics involved
pyou can define your function with something likep precodedef ask if s lt k f k elif k lt s and s lt 2k f 2k s else f 0 return f codepre
0
error while using scrapy scrapytelnettelnetconsole no module named conch twisted
ol lipensure you have the python development headers code aptget install buildessential pythondev codepli lipinstall scrapy with codepipcode code pip install scrapy codepli ol
0
safe site api detect whether a site has adult fraud or malicious content
pcheck also following urls online checker is free p pa hrefhttpwwwsitepriceorgadultwebsitecheckeraspx relnofollowhttpwwwsitepriceorgadultwebsitecheckeraspxa and a hrefhttpwwwsitepriceorgapi relnofollowhttpwwwsitepriceorgapiap
0
i cant get the return function working
pjust add a codereprcode method to codewoodenstaffcode classp
0
subprocess call stopping asynchronouslyexecuted python parent process
pive discovered that codeffmpegcode blocks itself when run asynchronously a mailing list revealed that using codenohupcode avoids the problem see a hrefhttpsffmpegorgpipermailffmpeguser2011june001277html relnofollowherea for those interestedp
0
browser as gui for user input to a python script
pyou can use flask for thisp pyou can make a python server and process all the inputs in python here is a great tutorial to start flask p pa hrefhttpswwwyoutubecomwatchvisrz6r7hwdm relnofollowflast tutorialap
0
jpeg compression in python turns negative
pthanks a lot ali m the uint16 data type was the error all along this is how it looks using mask and weights respectively for quantisation a hrefhttpistackimgurcomjssybpng relnofollowimg srchttpistackimgurcomjssybpng altenter image description hereap
0
cannot code an decryption for my encryption
pwell this works though it doesnt give you a perfectly involutive encryption function p precodefrom itertools import ziplongest def encryptchunkerit n for i in range0 lenit n yield itiin def decryptchunkerit n overflow i 0 basewidth lenit n while i lt lenit if overflow width basewidth 1 overflow 1 else width basewidth yield itiiwidth i width def cryptstring n mode if mode encrypt chunks encryptchunkerstring n elif mode decrypt overflow lenstring n chunks decryptchunkerstring n overflow thing ziplongestchunks crypted joinjoinc for c in tup if c for tup in thing return crypted codepre pobservep precodegtgtgt crypt1234567890 3 encrypt 1470258369 gtgtgt crypt 3 decrypt 1234567890 gtgtgt s 1234567890 n 3 assert cryptcrypts n encrypt n decrypt s no assertionerror codepre pcodecryptstring n encryptcode is the same as your codeencryptn stringcode verified on a large number of random strings and values of codencode to get an involution you have to do something like codecryptcryptstring n encrypt n decryptcode p pi dont think its possible to have a perfectly involutive encryption function like the one you described youre throwing information away when you perform the encryption specifically the location of the blanks in your innermost loop this is why you sort of have to add one bit of information whether youre encrypting or decrypting this allows you to determine the correct way to chunk the stringp>
0
how to crawl a javascript page whose content name is defined by a reference
pa hrefhttpsseleniumpythonreadthedocsorgapihtmlseleniumwebdriverremotewebdriverwebdriverfindelementbylinktext relnofollowcodefindelementbylinktextcodea should workp precodedriverfindelementbylinktext2click codepre pof course in you case code2code would be calculated dynamically egp precodecurpage 1 while true try driverfindelementbylinktextstrcurpageclick except nosuchelementexception break logic curpage 1 codepre
0
python while loop syntax
pthe value of the variable codecurrentcode is the condition if its truthy the loop continues if its falsy the loop stops the expectation is that in the last element in the linked list codenextcode will contain a falsy value i assume that value is codenonecode and in that case the loop is equivalent top precodewhile current is not none codepre pif instead the linked list uses codefalsecode as the end marker its equivalent top precodewhile current false codepre
0
python online form submision
pyoure probably getting to that page by posting something via that next button youll have to take a look at the post parameters sent when pressing that button and add all of these post parameters to your callp pthe website emcouldem though be set up in such a way that it only accepts a particular post parameter that ensures that youll have to go through the website itself eg by hashing a timestamp in a certain way or something like that but its not very likely p
0
django heterogeneous queryset proxy models
phow about putting all the logic in one class something like thisp precodedef connectself return getattrself connects selftype def connectaolself pass aol stuff def connectyahooself pass yahoo stuff codepre pin the end you have your codetypecode field and you should be able to do most if not all things that you can do with seperate proxy classesp pif this approach doesnt solve your specific use cases please clarifyp
0
secure use of shutilrmtree ospathjoin and directory traversal
phow aboutp precodemy ospathabspathmyselfdefinedpath new ospathabspathpath if lennew lt lenmy or not newstartswithmy print bzzzt codepre pa hrefhttpdocspythonorg2libraryospathhtml relnofollowhttpdocspythonorg2libraryospathhtmlap
0
adding multiple values of elemattrib into a variable
pthe following will join together all the text elements and put them on separate lines emin the same cellem inside your csv you can change the n separator to or to put them on the same line emhoweverem you might still have issues with some of your other stuff you dont have nested loops there and i dont really understand what you are trying to accomplish so maybe you have more than one of each of those other things too anywayp precode c5 for elem in treeiterfindchildcontextresponselistresponsetextualanalysisexpressionlistexpressionmatchmatched c5appendelemattribtext cwriterowc1 c2 c3 c4 njoinc5 codepre
0
python packman score
pthe score is not updating because you are incrementing a local variable of the method displayscore you can make it a class member of packman for examplep precodedef initself x gamesmousex y gamesmousey initialise packman do something initialize the score variable selfscore 0 codepre pand thenp precodedef displayscoreself displayscore gamestextvalue selfscore size 25 color colorblack top 5 right gamesscreenwidth 10 gamesscreenadddisplayscore increase the score selfscore 1 add one to the current value codepre pyou missed the emselfem argument in the definition of the methodp
0
how to write the same in less code python
pthis is probably the shortest you can do without sacrificing readability but improving on a hrefhttpwwwpythonorgdevpepspep0008 relnofollowpep8a compilance for instancep precode def getuserinfoself month choicerange1 13 day choicerange1 29 year choicerange1966 1994 fname selfassignnamefirstnames lname selfassignnamelastnames print month month day day year year fname fname lname lname eaddress fname lname stryear strday password fname lname 0008383 codepre pas a side note do reconsider your password generation policy its quite insecure in your codep palso did you notice youve probably missed out codemonthcode from codeeaddresscode assignmentp
0
boolean indexing that can produce a view to a large pandas dataframe
pbuilding off of unutbus example you could also use the boolean index on dfindex like sop precodein 11 dfixdfindexidx 999 in 12 df out12 a b c 0 9 23 6 1 999 999 999 2 9 25 4 3 999 999 999 4 9 27 2 5 999 999 999 6 9 29 0 7 10 30 1 8 9 31 2 9 10 32 3 10 9 33 4 11 10 34 5 codepre
0
python file existence checks loop crashes unless i add a print statement
pyou are interfacing with some poorly written ccc code so it is hard to pinpoint where the error isp pthat it is poorly written is apparent from the way the api makes you retrieve list items with a call rather than just using an indexp pgood luckp
0
how to use espeak with python
pim using this at the moment which is working wellon my raspberry pip precodefrom subprocess import call callespeaks140 ven18 zhello from mike codepre
0
check if object attributes are nonempty python
pif your class defines on py2 a hrefhttpsdocspythonorg2referencedatamodelhtmlobjectnonzero relnofollowcodenonzerocodea on py3 a hrefhttpsdocspythonorg3referencedatamodelhtmlobjectbool relnofollowcodeboolcodea or on either a hrefhttpsdocspythonorg3referencedatamodelhtmlobjectlen relnofollowcodelencodea then that will be used to evaluate the truthiness of objects of that class if only codelencode is defined an instance is truthy when it returns nonzero and falsy when it returns zero so for example to make your class simply report if its attributes are nonempty in either py2 or py3 youd addp precode def boolself return boolselflis1 or selfdict1 nonzero bool to make it work on py2 too codepre palternatively if your class instances have meaningful lengths you definep precode def lenself return lenselflis1 lenselfdict1 for example i doubt the length is meaningful in terms of both codepre pand get boolean behavior by sideeffect of supporting codelenmyobjectcodep
0
python ide that you can highlight a methodclass and jump to its definition
pheres a small bundlecommand for textmate that can accomplish python jump to definition for 99 of casesp precodefunctmcurrentword dirtmprojectdirectory output define the class or function definition string that were looking for funcdefdefclass func find all files that contain funcdef filesegrep funcdef dir r l includepy look for a function declaration within a files contents ltfilegt function lookupfunction local linenl b a 1 egrep funcdef awk print 1 if line gt 0 then echo jumping to gt 1line mate 1 l line exit 0 fi iterate files for file in files do echo file lookupfunction file done nothing found echo function func was not found within the current project codepre
0
django file upload gives noreversematch error
pi see some problem in your project urlpy filep precodeurlpatterns urlrngasite includengasiteurls urlradmin adminsiteurls urlr includengasiteurls staticsettingsmediaurl documentrootsettingsmediaroot codepre pyou have mentioned this twicep precodeurlrngasite includengasiteurls urlr includengasiteurls codepre pthis means there are two url paths for codeviewlistcodep precode1 list 2 ngasitelist codepre pi guess this must be the problemhope this helpsp
0
syntax of lists in python
pcodecode do not enclose a list they do not enclose any kind of sequence they enclose when used this way a set a hrefhttpenwikipediaorgwikiset28mathematics29 relnofollowin the mathematical sensea the elements of a set do not have a specified order so you get them enumerated in whatever order python put them in it does this so that it can efficiently ensure the other important constraint on sets they cannot contain a duplicate valuep pthis is specific to python 3 in 2x cannot be used to create a set but only to create a a hrefhttpenwikipediaorgwikiassociativearray relnofollowdicta this also works in python 3 to do this you specify the keyvalue pairs separated by colons thus codesujit amit ajit arijitcodep palso a general note if you say question instead everywhere that you currently say doubt you will be wrong much less often at least per the standards of english as spoken outside of india i dont particularly understand how the overuse of doubt has become so common in english as spoken by those from india but ive seen it in many places across the internetp
0
python getpippy not found
pthis is an interesting coincidence with windows powershell which uses the a hrefhttpmsdnmicrosoftcomenuslibrarysystemmanagementautomationverbscommongetvvs85aspx relnofollowcodegetltsomethinggtcode convetion to name the powershell cmdlets that emretrieve a resourceema theres a shorthand way to call get commandlets by ommiting the codegetcode part thats why it tries to run the file with powershell by just typing codepipcode and of course it failsp pyou should run pip install usingp precodepython getpippy codepre psee a hrefhttppipreadthedocsorgenlatestinstallinghtmlinstallpip relnofollowdocsap
0
tensorflow what does ops constructors mean
pthis is actually something in between ops constructor refers to functions creating new instances of objects being ops for example codetfconstantcode constructs a new op but actualy returns a reference to tensor being a result of this operation namely instance of codetensorflowpythonframeworkopstensorcode but it is not a constructor in the oop sense p pin particular things that have actual logic like codetfaddcode will create both codetensorflowpythonframeworkopsoperationcode to perform addition and codetensorflowpythonframeworkopstensorcode to store the result of the operation and only tensor will be returned this is what cited part of documentation tries to explainp pfor examplep precodeimport tensorflow as tf tensor tfaddtfconstant1 tfconstant2 for op in tfgetdefaultgraphgetoperations print op print tensor codepre pwill result inp precodename const op const attr key dtype value type dtint32 attr key value value tensor dtype dtint32 tensorshape intval 1 name const1 op const attr key dtype value type dtint32 attr key value value tensor dtype dtint32 tensorshape intval 2 name add op add input const input const1 attr key t value type dtint32 tensoradd0 shapetensorshape dtypeint32 codepre pthree ops have been created in background while you still operate on tensor level which has been returned by codetfaddcode its name created by default suggests that it is a tensor produced by codeaddcode operationp h3updateh3 pa simple pythonbased example might be more usefull so tf does something like thisp precode>class b: def __init__(self): print 'constructor of class b is called' pass class a: def __init__(self): print 'constructor of class a is called' self.b = b() def create_something(): print 'function is called' a = a() b = a.b print 'function is ready to return' return b print create_something() </code></pre> <p>as you can see <code>create_something</code> is not a constructor, it calls a constructors of some classes and returns some instance, but itself is not constructor (nor initializer) in the oop sense. it is more like a factory design paradim.</p>
0
python pandas dtypes detection from sql
pthanks to boud and parfait their answers are right p pall my tests shows that missing date fields can make dtype detection to failp preadsqlquery has a parameter to define fields with date type i guess to cure this problemp psadly since now i have been using a complete generic treatment to process a hundred of tables to use readsqlquery parameter parsedates would implies to do a prior work of metadata definition like a json file describing each tablep pactually i also found out that integers are changed to float when there is nan field in the columnp pif i would be reading csv flat files i could understand that data type can be hard to detect but from a database readsqlquery pandas has sqlalchelmy as a dependence and sqlalchemy and even any lower level python database driver cxoracle db api has reflection mechanism to detect data types pandas could have been using those metadatas to keep data types integrityp
0
swig cstringi python return byte type instead of string type
pi solved my problem using codectypescode with the help of a hrefhttpsgithubcombit01101ctypesgen relnofollowhttpsgithubcombit01101ctypesgenap
0
saving a python 27 script that contains arabic
padd this as the first line of your python fileor second if you use it with a binbashp precode coding utf8 codepre pand use this p precodeu unicode string in python 27 codepre pinstead of p precode codepre pthe later only works in python 3p
0
python lxml subelement with text value
phow about the followingp precodeetreesubelementroot atext some text codepre pworks only if you do not need to assign the resultant element to a variablep
0
error when i try to add date in an excel file using python
pyou should convert your datetime object emtodayminusem to a string using one of the datetime functions instead of strp pfor example try replacing thebr codedatetminusappendstrtodayminuscodebr with p precodedateminusappendtodayminusstrftimeymd codepre pthat should workp
0
resize without changing the structure of the image
pwhat you are asking for is impossible resizing of image is a destructive operation you have 54x102 pixels 5508 pixels of data and you are trying to fit that amount of data into a 20x20 image thats just 400 pixels youll always lose some detail structure etc based on the algorithm you used in this case scipysp
0
how to execute something if any exception happens
pits not clear if you need to handle differently error1 error2 etc if not then the following code will do the trickp precodetry dosomething except error1 error2 error3 exceptionvariable handleanyoftheseexceptions codepre pif you do need to handle different errors differently as well as having the common code then in the except block you can have code of the following typep precode if isinstanceexceptionvariable error1 dothingsspecifictoerror1 codepre
0
python argparse issue with optional arguments which are negative numbers
phere is the code that i use it is similar to jeremiahbuddhas but it answers the question more directly since it deals with negative numbersp pput this before calling codeargparseargumentparsercodep precodefor i arg in enumeratesysargv if arg0 and arg1isdigit sysargvi arg codepre
0
form handling html with phppython source code not being interpretedassistance with configuration
pyeah you need a web server of some sort php and python scripts only run on web servers not on clientsbrowsers if you dont have a web server installed on your windows machine and your linux server isnt configured properly apache not working youre not going to be able to run it as a web applicationp pif you have php installed on a machine you can always run it directly on that machine from the shell prompt to screenconsole ex php f filenamephp and that should at least show you if the script has proper syntax to be executed it will also send output to the screen and while that wont render html nicely you can always copyandpaste the output into a text file on windows and then open it in a browser to see that html output you wouldnt be able to test posting a web for to the script yet but you could temporarily imitate that by adding values to itp
0
how to make pandas python render with d3 and leafletjs
pi managed to fix it by using the orient parameter of records instead of indexp pi then used this block a hrefhttpblocksorgd3noob9267535 relnofollowhttpblocksorgd3noob9267535a to get a working mapp
0
drf typeerror type object is not iterable
pi saw you use queryset but it should be lowercasep ptry thisp precodefrom restframeworkgenerics import genericapiview class expeviewsetgenericapiview queryset expediteurobjectsall lowercase serializerclass expediteurserializer def getself request serializer selfserializerclassselfgetqueryset manytrue return responseserializerdata codepre
0
forming a sanitised query string for pattern search in sqlite3 and python
precodequery select from players where playername like codepre pyou just have to separate the variable p
0
print two random different names from a set of names
pafter picking the first name remove it from the list and pick a random name from that new listp
0
django navagation with dropdowns
pyou currently have your menu designed as a tree with pointers to the parent also knows as an a hrefhttpmikehillyercomarticlesmanaginghierarchicaldatainmysql relnofollowadjacency list modela to calculate a tree you need to perform a sql query for each level to build a tree this is really inefficient that article above gives you some strageties for how to query your data to build a tree p pyou might want to look at storing your menu as a higher order data model like an mpttmodel from a hrefhttpsgithubcomdjangompttdjangomptt relnofollowdjangompttap pi would recommend checking out any open source project that implements a menuing systemp pa hrefhttpsgithubcomdiviodjangocms relnofollowdjangocmsa is an example and has a very robust menu system they store pages as mpttmodels and then build a tree querying from their pages the menu app then uses that structure from the pages to render content out through template tagsp pthis should give you idea about how to implement it yourselfp
0
namespace vs regular package
h2codeinitpycode required for python to treat directory like a moduleh2 pfor example if you have a directoryp precoderoot module file1py file2py codepre pwhile you can run these files independently in the codemodulecode directory eg with codepython file1pycode or codepython3 file1pycode you wont be able to import the files as modules in the root directory egp precodeimport modulefile1 codepre pwould fail and in order for it to work you at least need thisp precodemodule initpy file1py file2py codepre pcodeinitpycode initializes the package and you can have code in the codeinitpycode that is run when the module is first imported p precoderuninitialimportsetup codepre pprovide an codeallcode list of names to be importedp precodeall starimport only these names codepre pif imported with the followingp precodefrom module import codepre por you can leave it completely empty if you only want to be able to import the remaining py files in the directory but that is a requirement to be able to do thatp h2namespacesh2 pyou could originally use a hrefhttpdocspythonorg2librarypkgutilhtml rel="nofollow">pkgutil</a>, available since python 2.3. to accomplish adding namespaces, by adding the following into each separate package's <code>__init__.py</code>: </p> <pre><code>from pkgutil import extend_path __path__ = extend_path(__path__, __name__) </code></pre> <p>setuptools uses a similar method, again, all <code>__init__.py</code> files should contain the following (with no other code):</p> <pre><code>import pkg_resources pkg_resources.declare_namespace(__name__) </code></pre> <p>namespaces were more thoroughly addressed in <a href="http://www.python.org/dev/peps/pep-0420/" rel="nofollow">pep 420</a></p> <p>see also more discussion on setuptools and namespaces here:</p> <p><a href="http://peak.telecommunity.com/devcenter/setuptools#namespace-packages" rel="nofollow">http://peak.telecommunity.com/devcenter/setuptools#namespace-packages</a></p>
0
how do you specify a policy name when creating a new role
pas far as i know iam provides no way to associate a policy name with the codeassumedrolepolicydocumentcode im not sure what purpose a name would serve since there can be only one such policy per role and these trust relationships cannot be shared between rolesp
0