text_a
stringlengths
9
150
text_b
stringlengths
18
20.9k
labels
int64
0
2
python library to generate regular expressions
pperhaps it would be better to use a python html parser that supports xpaths see a hrefhttpstackoverflowcomquestions285990parsehtmlviaxpaththis related questiona look for the bits of interest in the html code and then record their xpaths or at least the ones shared by more than one of the examplesp
0
python s import time timetime is not same as phps time this one has a dot
pok so pythons time comes from the codetimecode module p pwhich emmay or may notem give the best time for your systemp ptimep blockquote preturn the time in seconds since the epoch as a floating point number note that even though the time is always returned as a floating point number not all systems provide time with a better precision than 1 second while this function normally returns nondecreasing values it can return a lower value than a previous call if the system clock has been set back between the two calls a hrefhttpdocspythonorg2librarytimehtmltimetime relnofollowpython time docap blockquote psometimes clock may work betterp blockquote pon unix return the current processor time as a floating point number expressed in seconds the precision and in fact the very definition of the meaning of processor time depends on that of the c function of the same name but in any case this is the function to use for benchmarking python or timing algorithms a hrefhttpdocspythonorg2librarytimehtmltimetime relnofollowpython time doca p blockquote pdepending on your use you should choose one of these for a discussion see here a hrefhttpstackoverflowcomquestions85451pythontimeclockvstimetimeaccuracypython timeclock vs timetime accuracyap pphp time according to the docs does the followingp blockquote preturns the current time measured in the number of seconds since the unix epoch january 1 1970 000000 gmt a hrefhttpphpnetmanualenfunctiontimephp relnofollowphp docsap blockquote pso no matter which one you choose youre most likely to get the same if not better resolution than phps time p pif you want to time a function though you should try the a hrefhttpdocspythonorg2librarytimeithtml relnofollowcodetimeitcodemodulea which automatically chooses from either codeclockcode or codetime</code> depending on the os granularity</p>
0
submitting form using mechanize in python
pyoure close but theres more you need to do after submitting in this case just addp precodedoc responseread ofile ltyour pathgt with openofile w as f fwritedoc codepre pi couldnt actually test this on your website at the moment so im just assuming all your settings before this are correct i only have python 3 at work and mechanize only works on 2x regardless this is generally the way you want to retrieve this sort of outputp
0
how can i have python read variables from a browser
ptwo solutions come through my mindp ol lithe games server code may expose api eg rest api via which your ai could query parameters and execute commandsli limake your ai interact with game just like human would using a hrefhttpseleniumpythonreadthedocsio relnofollowseleniumpythonali ol pusing selenium you can read state at any time by executing js in browser like this assuming your page includes jqueryp pre classlangpy prettyprintoverridecodefrom selenium import webdriver driver webdriverphantomjs drivergethttpexamplecom somevalue driverexecutescriptreturn someidval driverclose codepre
0
deleting a windows registry value with python
pi think deletekey takes the parent to the key you want to delete and the subkey is the key you ant to delete im not on a windows machine so i cant test it right nowp
0
python requests login not logging in
ptry using mechanize for this there is a snippet that is used to login then its pretty easy to get links from that refer this a hrefhttpstackoverflowcomquestions30898033pythonmechanizeloginfacebookusebeautifulshoupgetprofilepicturefailedpython mechanize login facebook use beautifulshoup get profile picture faileda you will also come to know that scrapping the whole data will not be possible p
0
checking if number is within more or less range in python
pyou cant use a range to directly compare emyourem number and the randomly generated number but you can use a range to directly compare their emdifferencesemp pcodeabscode can be used to return the positive version of a number whether it is positive or negativep precodeabs10 10 abs10 10 codepre pyou can use this to ensure your random number is always empositiveemp pyou must be misreading about codewithincode this is either something accessible only to you and your class or you misread what it meant because codewithincode is not a buildin functionp pnow on solving your problem this takes a bit of math and logicp pyou cant work within a range because the number is randomly generated but you can always get a percentage of them and work based on emthatemp pas an example consider this number line where the random number is 10 denoted by codecodep precode020 codepre pyou will always be able to divide the number you guess by the random number and get a number that will range from in this case code010code and code1020code in all cases when codenumberguessed numbergeneratedcode the number calculated in the division operation will be equal to code1codep pi leave you to figure out the implementation of this but the basic concept is that you can figure out how close you are to the number based on how far away you are from the number code1codep pits not perfect either but its an interested and clever way that might get a professors notice if you do it rightp
0
split data to multiple matrices based on first column values
precode a with openinfilecsv as f for line in f l linestripsplit if l0 in akeys al0appendl1 else al0 l1 codepre pthis example uses a hrefhttpstackoverflowcomquestions509211explainpythonsslicenotationarray slicinga which returns pieces of a list as a list p pat the end a holds p precode 1 0 0 3 4 5 0 1 5 0 0 3 0 0 9 0 0 5 0 0 2 2 2 0 1 3 0 0 1 0 0 4 0 codepre
0
cross compiled pyspidev for arm
pthanks for all your helpp pi found the solution so i post it for those who have the same problemp pthis is what i did p precodegit clone httpsgithubcomdocemepyspidev cd pyspidev export archarm platarmpokylinuxgnueabi export crosscompilearmpokylinuxgnueabi export pathpathpathtomycrosscompiler export ccplatgcc pthread export ldsharedcc shared export crossbasepath of destination export cflagsi path to python cross compiled include icrossbaseusrinclude export ldflagsl path to python cross compiled libs lcrossbaselib lcrossbaseusrlib python setuppy install prefixcrossbase codepre penjoy p
0
cannot complete flaskmigration
pi ran into a similar issue after performing the python managepy db migrate command the database tables were not created there was only an alembic table in the database p pi found the solution in the flaskmigrate documentation a hrefhttpsflaskmigratereadthedocsorgenlatest relnofollowhttpsflaskmigratereadthedocsorgenlatestap blockquote pthe migration script needs to be reviewed and edited as alembic currently does not detect every change you make to your models in particular alembic is currently unable to detect indexes once finalized the migration script also needs to be added to version controlp pthen you can apply the migration to the databasep blockquote precodepython managepy db upgrade codepre pthis command created the tables and applied the database migrations p
0
django form checking every object without showing them
pi think we could achieve that by overriding the a hrefhttpsdocsdjangoprojectcomen19topicsformsmodelformsthesavemethod relnofollowcodemodelformsavecodea methodp precodeclass worldformformsmodelform class meta model world fields name def saveself committrue superworldform selfsavecommitfalse isnew not selfinstancepk selfinstancesave if isnew its a new world fill it with countries selfinstancecountryaddcountryobjectsall else selfsavem2m return selfinstance codepre
0
how can i set a custom response header for pylons static public files
pin a standard pylons setup the public files are served from a staticurlparser this is typically setup in your configmiddlewarepymakeapp functionp pyou need to subclass the staticurlparser like antonin enfrun describes though calling it a controller is confusing because its doing a different purpose add something like the following to the top of the configmiddlewarepyp precodefrom pastefileapp import fileapp from pasteurlparser import staticurlparser class headerurlparserstaticurlparser def makeappself filename headers your headers here return fileappfilename headers contenttypeapplicationoctetstream codepre pthen replace staticurlparser in configmiddlewarepymakeapp with headerurlparserp precode staticapp staticurlparserconfigpylonspathsstaticfiles codepre pbecomesp precode staticapp headerurlparserconfigpylonspathsstaticfiles codepre
0
tango with django exercise 831 add page
pi found the solution to my problem so ill post it for anyone who might come across the same problem as i didp pin categoryhtml i changed p precodelta hrefrangocategory categorynameslug addpagegtpagesltagt codepre pwith p precodelta href url addpage categoryslug gtpagesltagt codepre pplease take note that the syntax of lines changed because i started using a hrefhttpdjangoregistrationreduxreadthedocsorgenlatestquickstarthtml relnofollowdjangoregistrationreduxap
0
is it possible to load the model once and reuse it again in python
pfirst you should check how much of a bottleneck this is and if it is really worth avoiding the io an sgdclassifier is usually quite small you can easily reuse the model but the question is not really about how to reuse the model i would say but how to get the new user instances to the classifierp pi would imagine codeuseridcode is a feature vector not an id rightp pto make the model do prediction on new data you need some kind of event based processing that calls the model when a new input arrives i am by far no expert here but i think one simple solution might be using an http interface and use a lightweight server like a hrefhttpflaskpocooorg relnofollowflaskap
0
python ifand not working as expected
pyou can just cast codeintcode and check for a codevalueerrorcodep precodedef rolldice while true try numsides intinputenter number of sides for die numrolls intinputenter number of rolls for die break except valueerror printenter an integer codepre hr precodegtgtgt rolldice enter number of sides for die 5 enter number of rolls for die foo enter an integer enter number of sides for die foo enter an integer enter number of sides for die bar enter an integer enter number of sides for die 1 enter number of rolls for die 2 gtgtgt codepre
0
making django readonly foreignkey field in admin render as a link
pcerins answer does not work in my django 18 project because readonlyfields should not contain string userlink but a reference to defined functionp precodeclass profileadminadminmodeladmin httpsdocsdjangoprojectcomen18refcontribadmindjangocontribadminmodeladminlistdisplay def userobj changeurl reverseadminauthuserchange argsobjuserid return marksafelta href0gt1ltagtformatchangeurl objuseremail usershortdescription edit linked user rawidfields user listdisplay user lastname firstname specialization listdisplaylinks firstname lastname readonlyfields user user codepre pnote that userobj overrides both single model edit and model list display for profileuser field note also that readonlyfields uses both user and user one renders linked email another one user namep
0
how to reliably check windows release version in python
pstarting in windows 81 microsoft changed the way the underlying version functions work so while windows 81 strongshouldstrong return 63 as the version number it doesnt unless the application is specifically manifested for windows 81 so for windows 81 and server 2012 r2 codeplatformplatformcode wont work as expected on my windows 81 box i get this as the outputp precodegtgtgt import platform gtgtgt platformplatform windowspost2008server629200 codepre pthe above shows windows 81 clearly identified as nt version 62 which is wrong it should have been 63p psee a hrefhttpstackoverflowcoma223257671354698my answera on this other thread for a way to get the true windows version number even on windows 81 and server 2012 r2p
0
parsing a json file and adding it to a model
pi solved the problem by replacing p precodeimport os osenvirondjangosettingsmodule jsonapisettings codepre pby p precodefrom jsonapiwsgi import codepre pwhere codejsonapicode is my project name thanks for the help p
0
why doesnt warp function in python get executed when i call it
pyou are calling codedecorcode with a single argument that argument is whatever codeprinttextcode returns well codeprinttextcode prints something and then returns none so far your output is just codehello worldcode none is now passed to codedecorcode and it returns the codewrapcode function nowhere is codewrapcode actually called and your final output is just codehello worldcodep pyou are misunderstanding the use of decorators the correct syntax is thisp precodedecor def printtext printhello world codepre pthat is a shortcut for thisp precodedef printtext printhello world printtext decorprinttext codepre pnow you can see that it is the returns of codedecorprinttextcode the codewrapcode function that is being called and everything is printedp
0
how do i color a date in pyqt4 calendar widget
pim not exactly sure what youre trying to do here but since im hacking away at the tutorial on pyqt4 from zetcodecom myself i thought i might throw in a few suggestionsp pyou can change the font color of codelblcode by adding a stylesheet if you click on a date in the calendar the printed label will turn greenp precodedef showdateself date selflabelsettextdatetostring selflabelsetstylesheetcolor green codepre pif you want to color the background of your label go about it this wayp precodedef showdateself date selflabelsettextdatetostring selflabelsetstylesheetbackgroundcolor red codepre hr pit just occurred to me that you might mean emprintem instead of empaintem so heres a way to print the date in your style formatp precode in your initui method selfdatelabel qtguiqlabelself date calselecteddate selfdatelabelsettextformatdateday datemonth dateyear output 2092013 change your showdate method to this def showdateself date mydateformat formatdateday datemonth dateyear selfdatelabelsettextmydateformat output 112013 selfdatelabeladjustsize codepre
0
decoding json dictionary with python
pok looking at the online docs for the requests module i see that calling coderjsoncode will do the json parsing for you and give you back a python dict the thing you are posting is the output of that dict so the json part has already been taken care of for youp pthis code should work in both python 2 and python 3 once you have extracted the data to jsonresponse using codejsonresponse rjsoncodep precodeextractedvalues jsondata jsonresponseresults for item in jsondata subitemdict for key in twitterid officesplit subitemdictkey itemgetkey will give none if key does not exist extractedvaluesappendsubitemdict printextractedvalues codepre pprintsp precodetwitterid reptoddyoung office 1007 longworth house office building twitterid sendonnelly office 720 hart senate office building twitterid sendancoats office 493 russell senate office building codepre
0
how to ensure double quote in multiline strings
ppython doesnt stop you from using doublequotes inside your multiline strings the trouble is only when you place them next to each other codecode you can either escape your double quotes as codecode or simply leave a space between them and the triplequotes code codep pstrongescapingstrongp precodeq select from table where dtdate gt datesdatedate gtgtgt print q select from table where dtdate gt asdf codepre pstrongspace before the triplequotesstrongp precodeq select from table where dtdate gt dates datedate gtgtgt print q select from table where dtdate gt asdf codepre
0
debugger not starting with error typeerror init missing 1 required positional argument params
pturns out i had another python module codequeuecode in my project which was conflicting with codequeuecode in the standard library after renaming that everything is workingp
0
how to shift list indexes by a certain value in python
pyou could consider a a hrefhttpsdocspythonorg3librarycollectionshtmlcollectionsdeque relnofollowcodedequecodea insteadp precodegtgtgt from collections import deque gtgtgt d deque1234 gtgtgt drotate1 gtgtgt d deque2 3 4 1 codepre
0
pygletavbin misses beginning and end of video
pive also run into the problem with the beginnings of files being glitchy when played through pyglet i fixed it by reencoding and forceadding a few extra keyframes at the start of the filep precodeavconv i glitchyfilemp4 forcekeyframes 001002003 cv h264 ca copy notglitchyfilemp4 codepre pthis approach should work with suitably recent versions of ffmpeg too just replace codeavconvcode with codeffmpegcode ive only tested it with h264encoded video streams on linux with avbin10 and libav built locally from a hrefhttpsgithubcomlibavlibav relnofollowtheir git master branchap pit is a hack not a solution since it doesnt tell you why pyglet is ignoring keyframes early in the stream nor does it cause pyglet to read them correctly but it makes the problem go awayp
0
python openpyxl xlsx if column is x print current row
pplease import xlrd and run this code and modify as youp precodeimport xlrd workbook xlrdopenworkbookfilexls for s in workbooksheets for r in rangesnrows for c in rangesncols print row r print column c print value scellrcvalue codepre
0
iterating over a string in python
punidiomatically but conciselyp precodeimport time import sys autotype lambda instrmaplambda chsysstdoutwritech timesleep02 instr autotypehello world codepre pthe main problem with the above code is that its not usual to sequence two functions using tuple if you dont care for their return values p
0
calling r script from python
pcodetypeargparsefiletypewcode creates a file object so you are trying to concatenate the string to the file object if you want the output written to a file you can pass the file object to codesubprocesscode and have it write the stdout directly to the filep precodesubprocesscheckcallrscript scriptrstdoutargso codepre pp
0
what api package or library is easiest to find the location of an ip address
pyou can take a look at a hrefhttpuserinfoio relnofollowuserinfoioap pissuing a codeget httpapiuserinfoiouserinfoscode will return you all the information youre asking for you can also specify the ip address in the parameters codeget httpapiuserinfoiouserinfosipaddress888888888888codep pthe response looks like itp precode requestdate 20140918t041125154z ipaddress 1927723795 position latitude 377758 longitude 1224128 accuracy 3 this is the accuracy radius in kilometers continent name north america code na country name united states code us city name san francisco code 94103 codepre
0
spotipy how to read more than 100 tracks from a playlist
pmany of the spotipy methods return paginated results so you will have to scroll through them to view more than just the max limit ive encountered this most often when collecting a playlists full track listing and consequently created a custom method to handle thisp precodedef getplaylisttracksusernameplaylistid results spuserplaylisttracksusernameplaylistid tracks resultsitems while resultsnext results spnextresults tracksextendresultsitems return tracks codepre
0
grouping a dataframe and applying tuple
pthis seems to do the trickp precodegroupedapplylambda x pdserieslistxitertuplesindexfalse codepre
0
python 3 nonblocking read with pyserial cannot get pyserials inwaiting property to work
pyou have to run the open port function first then at the end close it using the close functionp
0
best way to store a triangularhexagonal grid in python
pdont use hgtilesabcp pmake tiles a three dimensional list by this way codehgtiles z for z in range10 for y in range10 for x in range10code now you can access a tile using codehgtilesabccodep ppscodea adeltasj0code should be codea deltasj0code and so on for for the other assignmentsp
0
if multiple substrings match string in specific order
precode if indexa lt indexb true else this codepre puse the index method to determine which one comes first the if statement gives a conditional as to what you do once you find out which comes first do you understand what im trying to say p
0
storing for loop iteration data
precoderesults for i in range5 filedata filedataa i filedatab i2 resultsappendfiledata print results codepre
0
how to create structured arrays with list and array in python
pyour error occurs onp precoded cp codepre phere is a simple approach using regular python lists on the title rowp precodeimport numpy as np a p q r s t u b nparray1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 c npvstacka b print c d c0lenc listc0indexp print d codepre
0
build nested dictionary in shell script
pyou can create a json file with your dictionary and pass to python script with argparsep pfor examplep precodeimport os import argparse import json def executejsonfile if ospathisfilejsonfile with openjsonfile as jsondata data jsonloadjsondata here you can process your dictionary data print data parser argparseargumentparserdescriptionthis script will take json file as argument parseraddargumentjson arg parserparseargs jsonfile argjson executejsonfile codepre popen command shell and enterp precodecpython27pythonexe argdictpy ctempjson codepre
0
how to open new bash terminal using python
pi dont know exactly how to explain it in code but i can point you in the right direction its an example from windows command prompt though when you are in command prompt the way to open a new window is to type start prompt from the already open one maybe if you apply this same methodology to your script it will work hopefully i was of some help to youp
0
multiple values json string python django
pwithin your page you can build an array and post those values manually as stated belowp precodevaluesdatetime1 value1datetime2value2 codepre por you could loop over all items and build the listp precodeeachdatetime functioni item datetimevaluesappenditemvalue codepre pwithin your view you can get a list of values passed asp precoderequestpostgetlistdatetime codepre
0
is my bisection search algorithm so wrong
precodelo 0 hi 100 mid hi lo2 print please think of a number between 0 and 100 while true print is your number strmid userinput rawinput enter h to indicate the guess is too high enter l to indicate the guess is too low enter c to indicate i guessed correctly if userinput h hi mid mid hi lo2 elif userinput l lo mid mid hi lo2 elif userinput c print game over your secret number was strmid break else print sorry i did not understand your input codepre
0
write a function filterlongwords that takes a list of words and an integer n and returns the list of words that are longer than n
pyour main problem is passing words as a single string rather than an iterable of strings the secondary problem is not specifying the separator between words for the missing split here is my versionp pi made codelongwordscode a generator function because in actually use one does not necessary need the sequence of long words to be a list and i gave an example of this in the output formattingp precodedef longwordswordlist length return word for word in wordlist if lenword gt length def main words inputenter words separated by spaces split length intinputminimum length of words to keep printwords longer than are formatlength joinlongwordswords length main codepre pthis results in for instancep precodeenter words separated by spaces a bb ccc dd eeee f ggggg minimum length of words to keep 3 words longer than 3 are ccc eeee ggggg codepre
0
i want to cut variable on another variables using python
precodec1 c2 c3 c4 csplit codepre pshould do the trick this takes advantage of the destructuring assignment feature of python where a sequenceiterable is matched with the variables on the leftp
0
use python to resize the active window to half the screen size in linux
pthe lag you getting is caused by xrandr command its going to be slow anyway you can reduce this time by parsing output of codexdpyinfo grep dimensionscode from python you could call this command using subprocesspopenp
0
google drive api download sheet problems
pso to put and end in this after a long time weve could not find a solution to this problem and ended up using a different method to approach this situationp pheres what we didp ul lisearched all the unique sheets we wantedli licopied linked them to a separate file on driveli liused the api to fetch each of those files separatelyli ul pthis resulted in success since it was a pretty straight forward solution using the official apisp pit was kinda of a hassle to have to copy everything to other files but afaik it is the only way to do it for nowp
0
understanding tensorflow lstm models input
pbasically lstm takes the size of your vector for once cellp precodelstm rnncellbasiclstmcelllstmsize forgetbias10 codepre pthen how many time series do you want to feed its up to your fed vector the number of arrays in the xsplit decides the number of time stepsp precodexsplit tfsplit0 timestepsize x outputs states rnnrnnlstm xsplit initialstateinitstate codepre pin your example i guess the lstmsize is 256 since its the vector size of one word the timestepsize would be the max word count in your trainingtest sentencesp pplease see this example a hrefhttpsgithubcomnlintztensorflowtutorialsblobmaster7lstmpy relnofollowhttpsgithubcomnlintztensorflowtutorialsblobmaster7lstmpyap
0
how to add strings to a list created by the readlines function
pi dont think you should be modifying the list you are iterating over try iterating over a copy and modifying the original also you are not actually writing the new line back to the file try thisp precode number strintinputnumber inputname inputlastname inputfirstname file txttxt open file with default mode for reading f openfile lines freadlines fclose close the file sooner rather than later loop for each line in the file for line in listlines lt create a copy to iterate over the name is the values indexed from 0 first character to 4 fourth to last character name line04 check if name has been appended before if name inputname if value of name is inputname concentrate the number onto the line found true printnyour name has been found in the filen newline line1 number n linesremoveline linesappendnewline break the loop break otherwise continue the loop else found false overwrite the file with the updated data with openfile w as myfile myfilewritelineslines codepre pthe codereadlinescode method just gives a list of the lines read from the file modifying it does not modify the file once you have a modified list overwrite the file now the number should be there on the second runp phope that helpsp
0
call 2 python functions every n seconds
pi also believe the problem is that em4hem is interrupted by the other function you could create a counter var inside em5minem and call 4h from therep precodeusrbinenv python import threading counter 0 def 5min threadingtimer300 5minstart counter 1 if counter 48 counter 0 4h print5 min def 4h codepre pit is probably not the best solution but is the best one i knowp
0
python write more then one line into csv
puse a hrefhttpsdocspythonorg2librarycsvhtmlcsvcsvwriterwriterows relnofollowcodewriterowscodea instead of codewriterowcodep precodewith openfilename w as f writer csvwriterf delimiter dosomething writerwriterowsrows codepre
0
swig python callback with function template and shared pointer as return value
pthe swig object you get back is a proxy for the codejobmecode it should work just like a codejobtcode wherever you need itp pah i think i see the problem you need to instantiate the codejobtcode and codeclientwaitforjobcode for each codeprcode you havep precodeinclude boostsharedptri sharedptrjobtltfoogt include ltjobthppgt templatejobname jobtltfoogt template clientwaitforjobltfoogt codepre pso codetemplatecode instantiates a template but it doesnt guess all the possible types you might use to instantiate it withp
0
binding to the minimizemaximize buttons in tkinter
pfor minimization you should be able to bind to codeltunmapgtcode you can read more a hrefhttpswwwtcltkmantcltkcmdbindhtmm13 relnofollowhereap pim not sure what to suggest for maximization maybe the codeltconfiguregtcode event or codeltresizerequestgtcodep
0
confused about list variable assigment
pits not variable assignment its lookup codepositioncode is an index when it has a value of code0code codenumberspositioncode returns code1code the first element in codenumberscode for codepositioncode code1code it gets code3code etcp ppython sequences like codelistcode are indexed 0up so the first element in a sequence is at index code0code and the last is at index codelenseq 1codep
0
writing a simple python programany help would be much appreciated
pnerdherd and mhawke have already explained the issue with printinfo and with indents but it sounds like youre still confused by how to get 3 nurseassistants instead of 25 for example you say now how to figure out how to program ratiosp pby using floats you can run into the problem that not every decimal floatingpoint value is exactly representable as an ieee floatingpoint value and that one can be solved by programming ratios eg by using codefractionsfraction1 2code instead of code10 20code or by using decimal floats like codedecimal1 decimal2code but thats not actually the problem youre havingp pthe problem youre having is that you want to round up and that doesnt happen automatically you have to do it explicitly eg by calling codemathceilcode and there are two places you could do it with different semantics so you have to decide which one makes sense for your problemp poption 1 is to round up as soon as possible like thisp precodedef getnursespatients nurses mathceil10 30 patients return nurses def getassistantsnurses nurseassistants mathceil10 20 nurses return nurseassistants codepre poption 2 is to round up as late as possible like thisp precodedef printinfopatients nurses nurseassistants print the number of patients for this shift is mathceilpatients print the number of nurses needed is mathceilnurses print the number of nurses assistants is mathceilnurseassistants codepre pin your case these actually will turn out to give the same answers assuming the number of patients is always an integer which hopefully it is but hopefully you can see how these can give different answers in similar cases so you have to decide which is correctp pmeanwhile codemathceil266666code is going to print out as 30 when you may want 3 instead to do that just change codemathceilnursescode to codeintmathceilnursescode etcp
0
how to check if a web pages content has been changed using seleniums webdriver with python
pyou cannot rely on codepagesourcecode for what you are doing what selenium will report is most likely going to be what the browser first received as the docs a hrefhttpsseleniumgooglecodecomgitdocsapijavaorgopenqaseleniumwebdriverhtmlgetpagesource2829 relnofollowmentionap blockquote pget the source of the last loaded page strongif the page has been modified after loading for example by javascript there is no guarantee that the returned text is that of the modified pagestrong please consult the documentation of the particular driver being used to determine whether the returned text reflects the current state of the page or the text last sent by the web server the page source returned is a representation of the underlying dom do not expect it to be formatted or escaped in the same way as the response sent from the web server think of it as an artists impressionp blockquote pemphasis mine the doc is for the java bindings but the behavior is not determined by the java bindings but by the part of selenium that lives browserside so this applies to the python bindings toop pwhat you should be doing to get the actual state of the page isp precodedriverexecutescriptreturn documentdocumentelementouterhtml codepre pthis will give you a serialization of the dom tree of the entire pagep
0
what is the best way in pythondjango to let users add files to the database
pyou could simply write static files to disc and then serve them as static files that would be easier but it depends on your other requirementsp pbut from what i understand in your question youd needp ol lia form to uploadli lia upload handler itself which inserts into the dbli lia view that renders based on a pathli linot sure about the urlspy entry youll want something in there to separate this content from the rest of your site and youll probably also want something to safeguard against the file extensions that you serve there li ol pemnote this has security hole written all over it i would be super careful in how you test thisemp
0
python argparse subparsers and linking to the correct function
pthis should work but a manual mapping would be more straight forward in my opinionp precodeimport argparse class proxy def getattrthing def caller type if type serverobject get instance of server with right type return getattrserverobject thing return caller parser argparseargumentparser entryparseraddargumentservertype destservertype requiredtruechoiceshttp ftp ssh subparser parseraddsubparsersdestoperation for operation in check build deploy configure verify entryparser subparseraddparseroperation entryparsersetdefaultsfuncgetattrproxy command options parserparseargs this will call proxy function caller with type argument optionsfuncoptionsservertype codepre
0
tumblr scraping bot not getting images scrapy
pyou are always getting the first image and storing only that one inside a list so a list with only one element this is what this line saysp precodeimageimageurls urljoinresponseurl rel0 codepre pyou should maybe use a better xpath to extract the right information maybe something likep precodeimgxpath idcontentdivclasscopyimgsrc imageimageurls responsexpathimgxpathextract return image codepre pthis is just an example you should check if that is the correct xpathp
0
batchadding properties in python
pyou can define a metaclass to dynamically create all the properties that needs lazy loading this metaclass gets the property names from a list codelazypropscode defined in your own class and within codenewcode generate the properties in your class p pthe code is like thisp precodeclass lazymetatype def newcls clsname bases clsdict d dictclsdict props dgetlazyprops def lazyloadattr def wrappedmethodself variable attr if not hasattrself variable selfload return getattrself variable return wrappedmethod for prop in props method lazyloadprop property propertymethod dprop property return typenewcls clsname bases d your class uses lazymeta as metaclass class lazyclass metaclass lazymeta lazyprops test1 test2 def loadself print loading selftest1123 selftest2456 codepre pnow when you instantiate a object of lazyclassp precodegtgtgt l lazyclass gtgtgt ltest1 loading 123 gtgtgt ltest2 456 codepre pemnote i used codetest1 test2code in place of codetest1 test2code because python treat variables starting with double underscore specially and it prevents codegetattrcode from working properlyemp
0
what is the performance hit of this orderby django query
pwithout seeing your full query and your schema its impossible to do more than speculatep pbut i believe the order of columns in a multicolumn index in mysql is important this would mean that your index on codetimestamp is likely unusable for ordering by timestamp if you changed the order to instead be timestampcode it probably would be useable for order by timestamp however it may hurt performance for other queriesp pif your usage requires an index for both you may need to create a second index on just the timestamp columnp
0
flattening nested loops decreasing complexity complementary pairs counting algorithm
pi think some or all of these would help but im not sure how i would prove it yetp p1 take values and reduce it to a distinct set of values recording the count of each element onp p2 sort the resulting array n log np p3 if you can allocate lots of memory i guess you might be able to populate a sparse array with the values so if the range of values is 100 100 allocate an array of 201 and any value that exists in the reduced set pops a one at the value index in the large sparse arrayp p4 any value that you want to check if it meets your condition now has to look at the index in the sparse array according to the x y relationship and see if a value exists therep p5 as unutbu pointed out its trivially symmetric so if ab is a pair so is bap
0
how to find all django foreign key references to an instance
pyou can use djangos reverse foreign key support p psay you have two models like sop precodeclass foomodelsmodel name modelscharfieldmaxlength10 class barmodelsmodel descr modelscharfieldmaxlength100 foo modelsforeignkeyfoo codepre pthen you know you can do codebarinstancefoocode to access the foo object it keys to but you can use the reverse foreign key on a codefoocode instance to get all the codebarcode objects that point to it using eg codefoobarsetcode p
0
writing a single table value in sqlite3
pif you are not familiar with sql you could try using an orm which maps db tables to python classes and objects i am a big fan of storm you can find it herep pa hrefhttpsstormcanonicalcom relnofollowhttpsstormcanonicalcomap
0
r r stage 4 create and train the ranker
ppython is telling you it cant find the script codetrainpycode in the current working directory did you skip this step in the a hrefhttpswwwibmcomsmarterplanetusenibmwatsondeveloperclouddocretrieverankgetstartshtml relnofollowtutorialap blockquote pnavigate to the downloaded trainpy scriptp blockquote pthis means codecdcode to the same directory as the filep
0
python bit operations on a list of ints
pdo you mean something like thisp precodedebossarray 0 for i in xrange4 def setbitdint index offset dintindex 1 ltlt offset print debossarray 0 0 0 0 setbitdebossarray 2 3 print debossarray 0 0 8 0 codepre
0
joining hundreds of columns and column indexes into a string
ptry this p precodeld dfsetindexidfillnatodictorientrecords ll join k strv for kv in xiteritems if v for x in ld ll skill2500 skill1100 skill430 skill320 skill2100 skill4700 skill3450 skill1230 skill550 codepre
0
comparing packets in python
pso you have a few problems here mostly in your python syntax br 1 an if statement in python looks like the following brcodeif 1 1 print hello world codep p2 notice that you try to use the codeprintcode command after you use codereturncode this will not work because once you use return the function will finish running for example br codedef test return hello world will run and exit the function print hello wolrd2 will not run since the function was finished on the line above codep pafter you have fixed these problems i suggest you look over your code and fix it to the right python syntaxp
0
database commit which is the preferred way and why
pstrongthe method 1strongp ul liwill take more time because it must commit the changes to the database item by itemli liit takes more io access to the hard driveli liif an error occurs in the second query the first query is already commitedli ul pstrongthe method 2strongp ul liwill perform faster because it commits the changes only one timeli liit takes less ioli liif an error occurs in the second query the first query is rolled backli ul pthe second method is similar to a bulk insert since it commits all the changes only when all queries are executedp
0
how to create django like button for anonymous users
pyou emcantem 100 restrict multiple votes but you can make it very difficult for a regular user by usingp ul lia cookieli lia db entry with the voters ipli ul
0
how to manage a single form of data in django admin
pyou can just redirect user from list view to detail view of first element on list it wont even need to modify anything in admin just create separate view that will redirect user to page and register in on url that will be normally occupied by list view remember that your view must be registered in codeurlspycode before django adminp
0
sklearns plsregression valueerror array must not contain infs or nans
pthe issue is caused by a bug in scikitlearn i reported it on github a hrefhttpsgithubcomscikitlearnscikitlearnissues2089issuecomment152753095 relnofollowhttpsgithubcomscikitlearnscikitlearnissues2089issuecomment152753095ap
0
how to set synchronous transmission under reverse proxy using nginx
pyou mean streaming yeah you probably want to play with strongproxybufferingstrong strongproxystorestrong andor strongproxytempfilewritesizestrongp pa hrefhttpwikinginxorghttpproxymoduleproxystore relnofollowhttpwikinginxorghttpproxymoduleproxystoreap pa hrefhttpwikinginxorghttpproxymoduleproxybuffering relnofollowhttpwikinginxorghttpproxymoduleproxybufferingap pa hrefhttpwikinginxorghttpproxymoduleproxytempfilewritesize relnofollowhttpwikinginxorghttpproxymoduleproxytempfilewritesizeap pstrongside notestrong since nginx is singlethreaded then you really want to use that feature otherwise one upload may block entire server for quite a long timep
0
unicodedecodeerror utf8 codec cant decode byte 0xc3 in position 34 unexpected end of data
pinstead of your forloop do something likep precodestart sitedecodeutf8findltimg idimgsized classslideimg 40 codepre
0
how i solve this indexerror
pwhat i did to solve this problem i changed the if a little bit i changed p precodeifx01 ifx1amp11 codepre pto p precodeifx00 ifx1amp10 codepre pand in this way i could fix the problemp
0
getting the learned representation of the data from the unsupervised learning in pylearn2
pi think you can use the encode and decode functions of the autoencoder to get the hidden representation egp precodel1path dael1pkl l1 serialloadl1path encode layer 1 l1input l1getinputspacemaketheanobatch l1encode l1encodel1input l1decode l1decodel1encode l1encodefunction theanofunctionl1input l1encode l1decodefunction theanofunctionl1encode l1decode codepre pthen the representation will bep precodel1encode l1encodefunctionyourdata codepre
0
how to access a class from a dynamically imported module
pactually 5 minutes after posting this question i was able to solve it but just in case someone else is trying to do the same thing here it isp pafter you have imported your module dynamicallyp precodemoduleobject importlibimportmoduleaudiomodule codepre pyou can obtain the class by doing the followingp precodemoduleclass inspectgetmembersmoduleobject inspectisclass codepre pthen you need to create an object of that class with the module this is done byp precodeclassobject getattrmoduleobject moduleclass codepre pnow when i print the classobject i get the followingp precodegtgtgtprint classobject audiomoduleaudshell codepre pnow i just need to figure out how to get a list of methods within the class and access those methodsp
0
list of list want to output variable not value
pyou are printing a your list c is actuallyp precodec 123 234 codepre pif you modify a before printing c the new values in a will be shown as python passes by reference and c contains a reference to ap
0
keep track of django model history
pfound a nice a hrefhttpswwwdjangopackagescompackagespdjangoauditlog relnofollowappa which provides awesome api and helpful in most of the cases like it provides api to track insertupdateddeleted instances with timestamp and user who did it documentation is written quite nicely too p pattachp pa hrefhttpdjangoauditlogreadthedocsorgenlatestmodelhistoryhtml relnofollowauditlog auditloga to the existing model and it will attach these extra fields to keep track of the changes in the modelp precodeactionid primary key for the log entry actiondate the point in time when the logged action was performed actionuser the user that performed the logged action actiontype the type of the action createdchangeddeleted any field of the original x model that is tracked by the audit log codepre
0
failed to write to file but generates no error
pyou have to put your cursor at the beginning of the file you can do that with codeseekcode methodp precodemyscriptseek0 codepre psee this answer a hrefhttpstackoverflowcoma29496482119117httpstackoverflowcoma29496482119117ap
0
python and ffmpeg video streaming not displaying via html5
pwith this linep precodeconn2sendallgenheadersencodeinputfromffmpeg codepre pyour code repeatedly sends the http headers once for every 1024 bytes of video you only need to send the headers once after the get request is received then send the body which will be the video datap palso read the request before replying conn2recv1024 ive found this to be necessary however i am not using windowsp pone other thing the http headers are supposed to be separated by coderncode not just codencode so try changing that if the above doesnt fix itp
0
creating threads from the same class but with different methods connected in python
pif you want to stick with classes good ideap pbuild two new classes inheriting from mythread having both their implementation of printtime functionp
0
web scraping a problem site
pas richiehindle mentioned your best bet on windows is to use the webbrowser class to create an instance of an ie rendering engine and then use that to browse the sitep pthe class gives you full access to the dom tree so you can do whatever you want with itp pa hrefhttpmsdnmicrosoftcomenuslibrarysystemwindowsformswebbrowser28loband29aspx relnofollowhttpmsdnmicrosoftcomenuslibrarysystemwindowsformswebbrowser28loband29aspxap
0
python optimization
pheres a short recursive solutionp precodedef allwordsn charschri for i in xrange33 127 if n 1 return chars return w c for w in allwordsn 1 for c in chars for i in xrange1 5 for w in allwordsi print w codepre pps is it an error that character 127 is excludedp
0
how to create a dataframe series as a substring of a dataframe index
pconsider the codepddataframecode codefte5codep precodefte5 pddataframenpones3 2 01234 34567 56789 x y fte5 codepre pa hrefhttpsistackimgurcom1ahwwpng relnofollowimg srchttpsistackimgurcom1ahwwpng altenter image description hereap pif you already have 5 digit zipcodes that start with code0code then they must be codestrcode already the simplest way to get at the first 3 characters in a vectorized way is to use the codestrcode string accessor rather than use codeapplycodep precodefte5indexstr3 index012 345 567 dtypeobject codepre pwe can assign it to codefte5zip3code with codeinsertcodep precodefte5insert2 zip3 fte5index3 codepre
0
python cumulative insertion of values in a sparse matrix lilmatrix due to repeated indices
pyou could use a a hrefhttpsdocspythonorg2librarycollectionshtmlcollectionsdefaultdict relnofollowdefaultdicta that maps the m column indices to their value and use the codemapcode function to update this defaultdict like sop precodefrom collections import defaultdict d defaultdictint use your array type here def fj s dj s mapf j s m1 dkeys dvalues keys and values are always in the same order codepre pinstead of codemapcode you can use codefiltercode if you dont want to create a list of codenonecode uselesslyp precoded defaultdictint use your array type here def ge de1 se0 filterg enumeratej m1 dkeys dvalues keys and values are always in the same codepre
0
how to calculate each string length that belongs to a list of strings by python
pjust a couple of remarks use codewithcode to handle files so you dont have to worry about closing them after you are done readingwriting flushing etc also since you are looping through the file once why not create the list too you dont need to go through it againp precode open file and writing each sequences length with openseqtxt r as f sequences totallen 0 for line in f newseq linestrip sequencesappendnewseq newseqlen lennewseq totallen newseqlen printnumber of sequences formatlensequences printtotal lenght formattotallen printbiggest sequence formatmaxsequences keylambda x lenx printt with length formatlensortedsequences keylambda x lenx1 printsmallest sequence formatminsequences keylambda x lenx printt with length formatlensortedsequences keylambda x lenx0 codepre pi have included some postprocessing info to give you an idea of how to go about it if you have any questions just askp
0
creating new column using output of if else statement causes error
pthis answer mainly tries to explain the error that youre seeing as im not a codepandascode user ill let the other answers speak to better ways to write this codep hr pcodedfmonthcode returns an array codesomearray 6code will return another array constructed such that codenewarrayi truecode iff codesomearrayi 6codep pbecause of situations like this in numpy an array does not have a truth value unlike normal python sequences so to test if an array is truthy you need to specify what you mean eg to specify that emallem elements must be truthy youd want codedfmonth 6allcodep
0
how do i remove a range subsection of a list in python
precodegtgtgt all range17 gtgtgt current 4 gtgtgt item for item in all if item current and item current1 1 2 5 6 gtgtgt current 0 gtgtgt item for item in all if item current and item current1 1 2 3 4 5 6 codepre
0
how can i split a list of lists of tuples if i dont have a column formed by only one element in the column selected
pin the following code we first redefine codedividedatacode so that it is a bit more flexible and efficient and later we test our new implementation on the two different types of data that you showed us with respect to the criterium to use with your data i had to improvisep pthe new codedividedatacode has no more fixed tests that are chosen according to the type of the value passed to the function but leverages pythons ability to threat functions as data codetestcode must be a function that you define elsewhere in you code or define on the fly in the call to codedividedatacode using the codelambdacode syntaxp precodefrom future import printfunction def dividedatadata colnum testnone doc string placeholder if no test function was passed return quite arbitrarily a shallow copy of the original list and an empty list if testnone return data set0 set1 for row in data if testrowcolnum set0appendrow else set1appendrow return set0 set1 mydata 0 y 0 n 1 n 2 y 3 y 0 y 0 y 1 y 2 y 3 n theirdata slashdot usa yes 18 none google france yes 23 premium digg usa yes 24 basic kiwitobes france yes 23 basic slashdot france yes 19 none digg new zealand yes 12, 'basic'], ['google', 'uk', 'yes', 18, 'basic'], ['kiwitobes', 'france', 'yes', 19, 'basic'], ['google', 'uk', 'no', 21, 'premium'], ['(direct)', 'new zealand', 'no', 12, 'none'], ['(direct)', 'uk', 'no', 21, 'basic'], ['google', 'usa', 'no', 24, 'premium'], ['digg', 'usa', 'no', 18, 'none'], ['google', 'uk', 'no', 18, 'none'], ['kiwitobes', 'uk', 'no', 19, 'none'], ['slashdot', 'uk', 'no', 21, 'none']] c2y, c2n = dividedata(their_data, 2, lambda answer: answer=='yes') c1y, c1n = dividedata(my_data, 1, lambda tup: tup[1]=='y') print(c2y, c2n, sep='\n') print(c1y, c1n, sep='\n') </code></pre>
0
sorting data in file in python
precodeclass myclassobject def initself name x y selfname name selfx x selfy y item1 item2 filename somefiletxt with openfilename r as f for line in f a linesplit name x y a0 a1 a2 if name item1 item1appendmyclassname x y elif name item2 item2appendmyclassname x y else raise valueerroritem is improperly named codepre pin order to use the class effectively you need a constructor the codeinitcode method this lets you pass arguments to the class and store them as instance variables codenamecode codexcode and codeycode then you iterate through each line of the file split the line based on spaces and then add the instance of codemyclasscode to the appropriate listp
0
force strformat to use two digits when displaying hexidecimals
pyoud use code04xcode to pad the output to 2 digits with a code0xcode prefix then format that again to fit your 6character widthp precodeprint formatformatval 04x 6 codepre pi used the a hrefhttpsdocspythonorg2libraryfunctionshtmlformat relnofollowcodeformatcode functiona instead since you are not interpolating into a larger stringp psince now the field is going to be 4 characters wide always you can also just hardcode the two spaces padding with a string formatp precodeprint 04x formatval codepre pdemop precodegtgtgt format3 04x 0x03 gtgtgt formatformat3 04x 6 0x03 gtgtgt 04x format3 0x03 codepre
0
spanish text in py files
pyou should specify your source files encoding by adding the following line to the very beginning of your code assuming that your file is encoded in utf8p precode encoding utf8 codepre potherwise python will assume an ascii encoding and fail during parsingp
0
is it possible to add a value named none to enum type
pyou can do this using the codeenumcode constructor rather than creating a subclassp precodegtgtgt from enum import enum gtgtgt gtgtgt color enumcolor none 0 red 1 green 2 blue 3 gtgtgt colornone ltcolornone 0 codepre pedit this works using the codeenum34code backport for python 2 in python 3 you will be able to create the codeenumcode with the codenonecode attribute but you wont be able to access using dot notationp precodegtgtgt colornone syntaxerror invalid syntax codepre poddly you can still access it with codegetattrcodep precodegtgtgt getattrcolor none ltcolornone 0gt codepre
0
python windows directory mtime how to detect package directory new file
pthere are two things about your first code snippet that concern mep ul lipyou cast the float from getmtime to int dependening on the frequency this code is run you might get unreliable resultspli lipat the end of the code you assign dirmtime to a variable mdmtime fnmtime which you check against seems not to be updatedpli ul
0
how to generate a ulli tree without recursive using python or other language
pmaybe something like thisp precodenewobject endobject class tree def initself namea childs selfname name selfchilds childs def strself indent0 result for i in selfchilds if i is new resultappendsltulgtn indent indent1 elif i is end indent1 resultappendsltulgtn indent else resultappendsltligtsltligtn indent i return joinresult print treetest new introduction new sub intro end module 1 end codepre
0
typeerror unsupported operand types for numpyndarray and str
pa hrefhttpresourcesarcgiscomdehelpmain101indexhtml018z00000051000000 relnofollowcodearcpysarastercodea creates a raster object however it requires an existing emraster datasetem as an input it cannot accept a numpy array as input the appropriate tool for that is a hrefhttpresourcesarcgiscomenhelpmain102indexhtml03q30000007q000000 relnofollowcodearcpynumpyarraytorastercodeap
0
python 3 traceback typeerror
pa couple of things p ol liyou should probably print the guess so that the user knows whether it is too high or too lowli licodelowanscode doesnt make any sense codeanscode will either be h l or c assuming the user follows the rules codelowcode and codehighcode need to be numbers in order to generate the codeguesscode appropriatelyli ol palso your logic was incorrect the below code works p precodeprintplease think of a number between 0 and 100 low 0 high 100 check false while true guess low high2 printmy guess is i guess ans inputenter h if guess it too high l if too low or c if correct printans if ans h high guess elif ans l low guess elif ans c printgame over your secret number wasformatguess break else printsorry i did not understand your input codepre
0
building a deb of a python project fails dpkgbuildpackage is trying to delete files as directories
pdo not install anything in codeusrlocalcode and if you want to package a new version of software that already has an official package dont try to make a pakcage from scratch modify the existing one insteadp
0
get matching elements values in two arrays
pyou can replace the list comprehension replacing the temporary lists and for loop with map likep precodename lambda n nname match setmapnamealistampsetmapnameblist codepre
0
pyqt4 and threading closing mainwidget after qthread finished and listwidget updated
pafter reading your question and your code in understand that you have two thread the main thread and worker thread and when youre worker is donei mean here that thread is reached the last line of your code you want to notify the main thread to close the worker and switch to another windowprobably or do something elsep ptodo this obviously you need to communicate with the ui threadmainthread so youll need to add this lines in your strongworkerthread classstrongp precodesignal qtcorepyqtsignalstr create a signal codepre pthen go to the last line from your thread and be sure that when your worker reach that line the job will be done and add this line to notify the main threadp precodeselfsignalemitsome string here this will send the string over the signal to your ui thread codepre pnow strongjump to your installwizzard class and add this lines inside your init method add this line below selfthread workerstrongp precodeselfthreadsignalconnectselffinished finished is a method inside your class codepre pnow inside your finished method you can terminateclosequit youre method easily using something like that p precodeselfthreadquit as you might guessed this will quit your thread codepre palso you can replace quit with terminate if you want to force the worker to be closed please but please read this warning from the qt documentation for qthreadterminatep blockquote pstrongwarningstrong this function is dangerous and its use is discouraged the thread can be terminated at any point in its code path threads can be terminated while modifying data there is no chance for the thread to clean up after itself unlock any held mutexes etc in short use this function only if absolutely necessaryp blockquote pand if you care about the string which it will be sent over signal from the worker add new parameter to you finished method to get access to the string and this is it p pi know that i am too late to answer your question1 years ago but it might be helpful for other developersanyway cheersp
0
how to set a variable by its name in python
pare you looking for functions like these they allow modifying the local namespace you happen to be inp precodeimport sys def getvarname return sysgetframe1flocalsname def setvarname value sysgetframe1flocalsname value def delvarname del sysgetframe1flocalsname codepre
0
issue packaging scrapy spider with cxfreeze or py2exe
ptake a look to a hrefhttpcxfreezereadthedocsorgenlatestfaqhtmlusingdatafiles relnofollowhttpcxfreezereadthedocsorgenlatestfaqhtmlusingdatafilesap pmy solution using cxfreezep pmodify the file strongcpython27libsitepackagesscrapyinitpystrongp precodeimport sys scrapy version import pkgutil if getattrsys frozen false version versiondecodeasciistrip else version pkgutilgetdatapackage versiondecodeasciistrip codepre pand the file strongcpython27libsitepackagesscrapyresponsetypespystrongp precodeimport sys from mimetypes import mimetypes from pkgutil import getdata def initself selfclasses selfmimetypes mimetypes if getattrsys frozen false mimedata mimetypes else mimedata getdatascrapy mimetypes selfmimetypesreadfpstringiomimedata codepre pand in setuppy include this build exe optionp precodeincludefiles cpython27libsitepackagesscrapyversionversion cpython27libsitepackagesscrapymimetypes,"mime.types")]} </code></pre>
0