text_a
stringlengths
9
150
text_b
stringlengths
18
20.9k
labels
int64
0
2
how to dynamically change variable name in formvarsvarname
precodefor i in range0 counter 1 formvarstable2field formvarsexamplefields i dbtable2insertdbtable2filterfieldsformvars codepre palso if you are not using the dynamically generated tables to store data in the database be sure to set codemigratefalsecode in the table definitions otherwise the dal will actually create each of those tables in the databasep
0
how to serve a folder at a specific context using pythons simplehttpserver
psth like this only you need to parse the request path into parts if you need more refined approach adapted from test python server use as neededp precode a simple custom http server class testhandlerhttpserversimplehttprequesthandler def dogetself if the main path is requested load the template and output it if selfpath or selfpath out contemplatetplmain maintemplatedata selfsendresponse200 selfsendheadercontenttype texthtml selfsendheadercontentlength strlenout selfendheaders selfwfilewritebytesout utf8 return else do the default behavior for other requests return httpserversimplehttprequesthandlerdogetself start the server httpd socketservertcpserverip port testhandler printapplication started on httpsd ip port httpdserveforever codepre
0
pyaudio recordingcapturing and stopterminate in python on raspi
pi just add relevant comments in front of commands let me know if you want to clear more ab8 itp precodeimport pyaudio wave sys chunk 8192 format pyaudiopaint16 channels 1 rate 44100 recordseconds 10 waveoutputfilename audiowav p pyaudiopyaudio stream popenformatformat channels channels rate rate input true inputdeviceindex 0 framesperbuffer chunk print recording frames for i in range0 intrate chunk recordseconds data streamreadchunk framesappenddata print done recording streamstopstream stop audio recording streamclose close audio recording pterminate audio system close wf waveopenwaveoutputfilename wb wfsetnchannelschannels wfsetsampwidthpgetsamplesizeformat wfsetframeraterate wfwriteframesbjoinframes wfclose codepre
0
python iterating through a list of list with a specifically formatted output file output
pif data is something like this 123234p precodefor j in data textfilewritesn tjoinstrx for x in j codepre
0
pyside auto scroll down in qscrollarea
pthis should be a succinct way to get the behaviour desired please checkp precodebar selfscrollverticalscrollbar barrangechangedconnect lambda xy barsetvaluey codepre porp precodebarrangechangedconnect lambda xy barsetvalue 9999 codepre
0
how to send email with smtplib module through the proxy
pthe following will workp precodeserver smtplibsmtpsslsmtpgmailcomport465 serverloginusernamegmailcompassword serversendmailfrom to msg codepre
0
selecting columns from a pandas dataframe based on row conditions
precodein 201 df pddataframenprandomrandn10 4 in 202 df out202 0 1 2 3 0 1380064 0391358 0043390 1970113 1 0612594 0890354 0349894 0848067 2 1178626 1798316 0691760 0736255 3 0909491 0429237 0766065 0605075 4 1214366 1907580 0583695 0192488 5 0283786 1315771 0046579 0777228 6 1195634 0259040 0432147 1196420 7 2346814 1251494 0261687 0400886 8 0845000 0536683 2628224 0238449 9 0246398 0548448 0295481 0076117 in 203 dfiloc dfiloc1 gt 0values out203 0 3 0 1380064 1970113 1 0612594 0848067 2 1178626 0736255 3 0909491 0605075 4 1214366 0192488 5 0283786 0777228 6 1195634 1196420 7 2346814 0400886 8 0845000 0238449 9 0246398 0076117 codepre pbasically this solution uses very basic a hrefhttppandaspydataorgpandasdocsversion0152indexinghtml relnofollowpandas indexinga in particular a hrefhttppandaspydataorgpandasdocsversion0152indexinghtmldifferentchoicesforindexing relnofollowcodeiloccodea methodp
0
how to create and attach a normal cookie to a response by tipfy
preading the docs for tipfy securecookie seems to only mean that the cookie is validated to not have been altered clientside and nothing to do with http vs httpsp blockquote psecure cookies are cookies that are not alterable from the client side because they add a checksum that is validated in the server when readp blockquote ptake a look at the docs here for more info a hrefhttpwwwtipfyorgwikiextensionssession relnofollowhttpwwwtipfyorgwikiextensionssessionap
0
pandas update value if condition in 3 columns are met
pthe third parameter of a hrefhttpdocsscipyorgdocnumpyreferencegeneratednumpylogicalandhtml relnofollowlogicalanda is to assign the array used to store the resultp pcurrently the method timrich provided might be the best in pandas 013 in development theres a new experimental a hrefhttppandaspydataorgpandasdocsdevindexinghtmlthequerymethodexperimental relnofollowquerya method try it p
0
which is the best way to compress json to store in a memory based store like redis or memcache
panother possibility would be to use mongodbs storage format a hrefhttpbsonspecorg relnofollowbsonap pyou can find two python implementations in the implementation page on that sitep pedit why not just save the dictionary and convert to json on retrievalp
0
python example of urllib2 asynchronous threaded request using https
phere is the code from a hrefhttpeventletnet relnofolloweventleta p precodeurls httpwwwgooglecomintlenallimageslogogif httpswikisecondlifecomwimagessecondlifejpg httpusi1yimgcomusyimgcomiwwbetay3gif import eventlet from eventletgreen import urllib2 def fetchurl return urllib2urlopenurlread pool eventletgreenpool for body in poolimapfetch urls print got body lenbody codepre
0
cannot read compressed bz2 file from httparchiverouteviewsorg
phope this helps now p pyou are trying to read an mrt file this can be done using thisp pa hrefhttpsgithubcomyoshiyukiyamauchimrtparseblobmasterexamplesprintallpy relnofollowhttpsgithubcomyoshiyukiyamauchimrtparseblobmasterexamplesprintallpyap pand the docs for the same is here a hrefhttpsgithubcomyoshiyukiyamauchimrtparse relnofollowhttpsgithubcomyoshiyukiyamauchimrtparseap
0
unable to get redirect work in google app engine
pi encounter a similar problem while trying gae the official site a hrefhttpsdevelopersgooglecomappenginedocspythongettingstartedpython27templates relnofollowhttpsdevelopersgooglecomappenginedocspythongettingstartedpython27templatesa has changed the related code just like anthony metioned in his post but here are some problems toop ol liin the templatevalues variable in class mainpage codeguestbooknamecode was encoded by codeurlliburlencodecode which will fail since this function takes a dict or a tuple as a variable rather than a string urllibquoteplus should be used instead li litwo forms in indexhtml shares the same encoded variable codeguestbooknamecode which is not pretty if your language is nonenglish in which case some code2fcode like strings will appears in the content so my solution is send a extra non encoded codeguestbooknamecode for the second form li ol
0
kivy turning an app into a widget
pi dont understand the question your app does nothing special and all the functionality is in the maincontroller widget what more separation do you need than thatp precodefactoryregistermain clsmaincontroller factoryregisterloaddialog clsloaddialog factoryregistersavedialog clssavedialog codepre palso these factory lines are unnecessary widgets automatically register themselvesp
0
deleting a windows registry value with python
pok p pnot a pythonic solution but it worksp precode cdocuments and settingsadmingtreg add registrykeyenvironment v ame t regexpandsz d ame f reg delete keyname v valuename ve va f cdocuments and settingsadmingtreg delete registrykeyenvironment v ame f der vorgang wurde erfolgreich ausgefhrt codepre psuccessp
0
python append folder name to filenames in all sub folders
pyou can use a hrefhttpsdocspythonorg35libraryoshtmloswalk relnofollowcodeoswalkcodea to iterate over the directories and then a hrefhttpsdocspythonorg35libraryoshtmlosrename relnofollowcodeosrenamecodea to rename all the filesp precodefrom os import walk path rename for dirpath files in walkparent for f in files renamepathjoindirpath f pathjoindirpath pathsplitdirpath1 f codepre
0
python conventions with respect to if conditions
pthe first is fine assuming that codedcode will always fit your criteria but the second example is more robustp pfor example when coded acode the condition codeif d and floatd gt 1code will raise the codevalueerrorcode where as the codetry exceptcode will catch it and work properlyp pso if your criteria of d will be either a blank string or a number string is absolute then the first is fine however if codedcode could have other values then you may want to use the secondp
0
access hive hiveserver2 using python
pif using the a hrefhttpgethuetumblrcompost49882746559tutorialexecutinghiveorimpalaquerieswithpython relnofollowhue shella hue comes as dependency if you want to streamline it you would need to isolate the a hrefhttpsgithubcomclouderahuetreemasterappsbeeswaxsrcbeeswaxserver relnofollowthrift implentationa lib and a hrefhttpsgithubcomclouderahuetreemasterappsbeeswaxgenpy relnofollowgenerated pythona from the a hrefhttpsgithubcomclouderahueblobmasterappsbeeswaxthrifttcliservicethrift relnofollowhiveserver2 thrift interfaceap
0
weighted clustering of tags
pyou could use a a hrefhttpsenwikipediaorgwikimixturemodelgaussianmixturemodel relnofollowgaussian mixture modela which can be seen as a generalisation of kmeans which allows soft clusters you can have k clusters and each entry belongs to all clusters with a certain amount this amount is the probability of the entry under that cluster luckily there is a hrefhttpscikitlearnorgstablemodulesmixturehtml relnofollowscikitlearn codea for thisp pyou can treat the set of tags across all products as defining a feature space for the entries the presence of a tag on a product means that product will have a nonzero entry equal to the weight in the position corresponding to that tag from there you have a fixed vector to describe entries and gmms can be appliedp hr phowever it is really hard to evaluate unsupervised learning approaches like this rather you should evaluate methods in light of the downstream task they are used for like suggesting products to people or detecting fraud or detecting duplicates etc p
0
gdb finds debugging information but cannot put breakpoint
pthere can be two reasonsp ul lithe library is not mapped yet orli liyou hit bug 54151 have a look at a hrefhttpsbugzillaredhatcomshowbugcgiid54151 relnofollowhttpsbugzillaredhatcomshowbugcgiid54151ali ul
0
m2crypto error unable to find vcvarsallbat
pyou need to run pip install from a command prompt with both the needed python programms and visual studio in the search path codepathcodep popen a visual c command prompt and note the result of p precodeecho path codepre pand add the relevant visual c visual studio directories to your python command prompt similar to thisp pset pathcpathtovspathp
0
reading request parameters in python
pi know it should be very simple and know how to do it in javanetphp and ror but not in pythonp pwell its not simple in python the languagep pit is simple in many python web frameworksp pdont make the mistake of comparing python the language with php the web framework or ror the web frameworkp ppython like java or vb or ruby is a programming language not a web frameworkp pto get stuff from apache into python you have three choicesp ol lipa cgi script a dreadful choicepli lipmodpython not a great choicepli lipmodwsgi a much better choicepli ol pif youre stuck with modpython because this is homework for instance youll need to read a modpython tutorial in addition to a python tutorialp pthis for example seems to be what youre doing a hrefhttpwwwmodpythonorglivecurrentdochtmltutpubhtml relnofollowhttpwwwmodpythonorglivecurrentdochtmltutpubhtmlap
0
facing memoryerror while doing multithread txt file ios looking for better solution
psounds like you are leaking memory python will use all available system memory before giving memoryerror and 4 mb does not sound much where you leak memory depends on your code which you didnt give in your questionp phave you watched the memory usage in the task manage of the osp phere is a tool to debug python memory usage needs python debug compiliationp pa hrefhttpguppypesourceforgenetheapy relnofollowhttpguppypesourceforgenetheapyap puse it to analyze your code memory usage and see what objects you are creating which dont get freedp
0
pyqt sending parameter to slot when connecting to a signal
pin general you should have each menu item connected to a different slot and have each slot handle the functionality only for its own menu item for example if you have menu items like save close open you ought to make a separate slot for each not try to have a single slot with a case statement in itp pif you dont want to do it that way you could use the a hrefhttpdoctrolltechcom45signalsandslotshtmladvancedsignalsandslotsusage relnofollowqobjectsendera function to get a pointer to the sender ie the object that emitted the signal id like to hear a bit more about what youre trying to accomplish thoughp
0
python split consecutive delimiters
pi think your solution is perfectly ok heres an equivalent onep precodefilterbool aaasplita codepre pprobably not as perspicuous as a list comprehension thoughp
0
beautifulsoup select string based on dictionary key
ponce youve parsed your html with beautifulsoup it can give you all the textp precode2gtgtgt x ltdiv idsrpmain classgtnltcode idvoltronsrpmaincontent styledisplaynonegtnnfmtheadlinefounder and ceo at solarthermochemical llcnisconnectedenabledtruensharedconnectiontoken240506fce660nnltdivgt 2gtgtgt soupbs4beautifulsoupx 2gtgtgt ysoupgettext 2gtgtgt y unnnfmtheadlinefounder and ceo at solarthermochemical llcnisconnectedenabledtruensharedconnectiontoken240506fce660nn codepre pnow further analysis of that text is left to other tools such as regular expressionsp precode2gtgtgt import re 2gtgtgt mo researchrfmtheadline y 2gtgtgt printmogroup1 founder and ceo at solarthermochemical llc codepre
0
reverse dictionary output keeps changing
pi have been able to reproduce your error of an inconsistent output there are probably two issues in your algorithmp ol liyou assume that the keys will be iterated over in order li liyou are iterating an object while altering it this is especially weird in python 3x where codeitemscode returns a view of the items rather than an explicit iterable see a hrefhttpstackoverflowcomquestions10458437whatisthedifferencebetweendictitemsanddictiteritemsthis questionali ol pit appears that you can solve both of these issues by using the following linep precodefor kv in sorteddictoitems codepre pthis has provided a consistent correct output in my tests im not super confident as to emwhyem this works and the lack of explanation might be a statement on why you shouldnt be iterating over a changing object to begin withp hr pfor fun heres a different asinine solutionp precodeimport networkx as nx d accurate exact precise exact precise astute smart clever smart clever bright talented make keys uppercase and values lowercase d kupper listmapstrlower v for kv in ditems fill out all of the edges expanded nxconverttodictoflistsnxgraphd convert the uppercase values to lowercase and filter out the uppercase keys filtered k listmapstrlower v for kv in expandeditems if kislower codepre
0
how to trigger a script execution after dropbox updates a specific directory
pcheck out codefswatchcode ive used it before to do something similar this is a line from a program i used it on p pcodefswatch print0 e dir xargs 0 n1 clientpycodep
0
how do you generate random unique identifiers in a multi process and multi thread environment
pis there not a unique piece of data in each thread it is difficult for me to imagine two threads with exactly the same data though i dont discount the possibilityp pin the past when i have done things of this nature there is usually something unique about the thread user name or client name or something of that nature the solution for me was to concatenate the username for example and the current time in milliseconds then hash that string and get a hex digest of the hash this gives one a nice string that is always the same lengthp pthere is a really remote possibility that two different john smiths or whatever in two threads generate the id in the same millisecond if that possibility makes one nervous then the locking route as mentioned may be needed p pas was already mentioned there are already routines to get a guid i personally like fiddling with hash functions so i have rolled my own in the way mentioned on large multi threaded systems with successp pit is ultimately up to you to decide if you really have threads with duplicate data be sure to choose a good hashing algorithm i have used md5 successfully but i have read that it is possible to generate a hash collision with md5 though i have never done it lately i have been using sha1p
0
python how to optimize calculations
pfirst if for every word you have unique line numbers use sets instead of lists finding set intersection is much faster than the intersection of lists especially if lists are not orderedp psecond precompute list lengths now you compute it twice for every single inner cycle stepp pand third use codenumpycode for this kind of computationp
0
pil imagesize returns the opposite widthheight
h2a this is a standard stateh2 pnumpy arrays carry images from strongcodeopencv2codestrong with another convention once inspected by strongcodedatashapecodestrong so does the pilpillow strongcodeimagesizecodestrongp hr pmay review and validate as in a hrefhttpstackoverflowcomq265341483666197python pillow v260 paletted png 256 how to add an alpha channelap pcodeprint datashapecode gives code1624 3856code and codeprint imsizecode gives code3856 1624codep
0
call iptables command within python script
pyour command is full of syntax errors due to missing spaces as shown belowp precodeiptables subprocesscall iptables i forward eth 0 m protocol tprotocol here dport here port j dnat todestination here ipaddress here codepre pas generated your iptables line will look likep precodettcpdport 80j dnat todestination1234 codepre pcodettcpdportcode is parsed as a single argument ditto for code80jcode and codetodestination1234codep
0
what is a response object in python
pserver and client use codehttp protocolcode to sendreceive informationp pcoderesponsecode stores all information from server codehttp headerscode for example cookies status code and codehttp bodycode mostly html but it can be json or file or otherp pwikipedia a hrefhttpsenwikipediaorgwikihypertexttransferprotocol relnofollowhttp protocolap pbtw coderequestcode stores codehttp headerscode and codehttp bodycode too sometimes codehttp bodycode can be emptyp
0
setuptools easyinstall mysqlpython123
pyou should use a hrefhttppypipythonorgpypivirtualenv relnofollowvirtualenva and a hrefhttppypipythonorgpypipip relnofollowpipap pvirtualenv automatically creates a setuptools version within the new environment so the default one is intactp pyou may want to read how the packaging and installing works a hrefhttpuswaretechcomblog200906betterpythonpackagemanagementusingsourceandversioncontrolsystems relnofollow1a a hrefhttpwwwarthurkozielcom20081022workingvirtualenv relnofollow2ap
0
how to print python array within html email body
pi would construct a string with the dates and then insert into your htmlp precodedatelist avdates dateliststring joindatelist edit this to match the desired output html lthtmlgt ltheadgtltheadgt ltbodygt ltpgtthese are the available dates ltpgt dateliststring ltbodygt lthtmlgt codepre
0
two similar python codes one doesnt work
pyoure getting stuck inp precode elif root pwr gt x increments root to cycle thru again root root 1 pwr 2 codepre pif coderoot 2 gt xcode setting codepwr 2code in every iterationp pyou need to break the loop somehow if coderootcode gets to bigp
0
running a separate function alongside a loop in python
pyes osfork youcan make the function run in a different process or the threading module to make it run in another thread if the function uses global variables you need to use the threading module and make it run in another thread and if not id suggest to do it anyway less resource wasteful assuming the function doesnt allocate alot of memory or otherwise uses alot of resources you code should look something like thisp precodeclass displaythreadthreadingthread init function if you need to pass info to the tread otherwise dont write one but if you do make sure to call threadinit first in your function def run overrides the run function display what you want on the display class downloadthreadthreadingthread init function if you need to pass info to the tread otherwise dont write one but if you do make sure to call threadinit first in your function def run overrides the run function download what you want codepre pand your main script should look likep precodethread1 displaythread thread2 downloadthread thread1start thread2start thread2join waits for download to finish while the display in being updated by the other thread codepre pand if you want to stop the display thread assuming it goes on forever you will have to add something likep precodeoskillthread1getpid signalsigkill codepre pafter the join and do what you want with the downloaded infop pthe multi process version is very similar and you should be able to understand how to make it from my example and the osfork docs if you are having trouble with it let me know and ill edit thisp
0
holiday program error in python
preplace your holiday function as p precodedef holidaystartlength length length start length length 7 daylength codepre
0
file locks in sqlite
pdo you require shared access to the database during unit tests if not use a inmemory sqlite database for those tests from the a hrefhttpwwwsqlalchemyorgdocsdialectssqlitehtmlconnectstrings relnofollowsqlalchemy documentationap blockquote pthe sqlite memory identifier is the default if no filepath is present specify sqlite and nothing elsep precode inmemory database e createenginesqlite codepre blockquote pno need to manage temporary files no locking semantics guaranteed a clean slate between unit tests etcp
0
i have to search for a file with extension txt but the path is changing every day
ptry this p precodepath c this is the path what i get back from an another script oschdirpath for files in oslistdir if filesendswithtxt print files codepre pcodecode instead of codecodep
0
django 17 relation authuser does not exist in migrate but fine in tests
pyou need to do 2 thingsp precodepython managepy makemigrations codepre pand thenp precodepython managepy migrate codepre pthe migrate does indeed apply the migrations but they first need to be created these two steps are more or less the replacement of the old syncdbp
0
recommended way to populate foreign key
precodeif formisvalid comment formsavecommitfalse commentstory storydetails commentsave return codepre
0
i cannot get wordpress running in local mode on windows using gae
pi had the same issue and tried out all kind of things ending up uncommenting the line p precodeextensionphpopenssldll codepre pin the codephpinicode file in my application folder that did the trick and wordpress is now running in my dev environmentp
0
unable to log in to a website with requests
precodeimport rerequests srequestssession mainurlhttpsangelcologinutmsourcetopnavhome headerscontenttypeapplicationxwwwformurlencodedhostangelcooriginhttpsangelco useragentmozilla50 windows nt 61 wow64applewebkit53736 khtml like gecko chrome4402403157 safari53736 mostly you need to pass the headers default headers dont work always so be careful here r1sgetmainurlheadersheaders authenticity token is extracted from this page using the regex i mentioned below this is required when you login to the page tokenresearchltinput nameauthenticitytoken typehidden valuegtgtr1textresrei print tokengroup1 headersrefererhttpsangelcologinutmsourcetopnavhome headersupgradeinsecurerequests1 payloadloginonlytrueuseremailyouremailuserpasswordyourpasswordauthenticitytokentokengroup1utf825e2259c2593 the value of utf8 gets urlencoded once you send the request r2sposthttpsangelcousersloginheadersheadersdatapayloadcookiesr1cookies print r2statuscode codepre
0
django 18 is not able to load templates
pchange p precodeinstalledapps djangocontribadmin djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribmessages djangocontribstaticfiles codepre ptop precodeinstalledapps djangocontribadmin djangocontribauth djangocontribcontenttypes djangocontribsessions djangocontribmessages djangocontribstaticfiles myapp codepre pthis will make the templateloader find your filesp phis answer is correct you can create a dir templates on your app a hrefhttpistackimgurcomnlcwtpng relnofollowenter image description hereap p thanks sebastian woznyp
0
receiving xml document with python via http
pexample with standard libraryp ul lia hrefhttpfragmentsturtlemeatcompythonwebserverphp relnofollowhttpfragmentsturtlemeatcompythonwebserverphpali ul por use some lightweight web frameworkp ul lia hrefhttpwebpyorg relnofollowwebpyali ul
0
python typeerror cant multiply sequence by nonint of type float
passuming your sequence is a list object to multiple a constantor scalar by a listvector you will need to use something like p precodek10 arr1234 newarrmaplambda x kx arr codepre palternatively it might be worth using numpy to get these functions in by defaultp
0
how do i transfer varibles through functions in python
pit appears as though you are not returning the result of the read functionp pthe last line of your read function should be return ap pand then when you call the read function you would say a readp
0
use user input within as input in a function python
pyou need to call your function codepensioncode as it doesnt just implicitly see the variables you named before it and call itself p padditionally you have indentation problems and use codeinputcode eminsideem codeintcode like so or else youre trying to convert your user prompt into an integerp precodeincome intinputwhat is your annual income pensioncontribution intinputwhat is your monthly pension contribution def pension pensioncontribution income if pensioncontribution gt income12 075 print your pension contribution is too high monthly pension contributions may not exceed 75 of your gross monthly income else printyour annual pension contribution is r pensioncontribution 12 call your function pensionpensioncontribution income codepre
0
how to save unicode with sqlalchemy
pi can not reproduce your error i can provide a few tips regarding unicode handling with sqlalchemy that may or may not helpp ul liinstead of using codeconvertunicodecode just use the sqlalchemytypesunicode column type that will always do the right thingli liyou are assigning a str instance codekeycode to the codekeycode column even though you used codeconvertunicodetruecode you will either want to assign a unicode value or use a nonunicode code column typeli lialways check if the encoding for your postgresql database is set correctly to utf8li linormally you do not need the codeencodingcode and codeconvertunicodecode parameters for createengineli ul
0
pivoting a pandas dataframe with duplicate index values
pyou can use groupby to aggregate by the common factors take the max of time to get the most recent dates and then unstack the msg to view confirmedsettings and sale side by sidep precodedfgroupbyuid msg gender agetimemaxunstackmsg msg confirmedsettings sale uid gender age 1 m 37 12915 41315 3 m 35 41915 nan 4 m 21 22115 31515 5 m 18 32815 nan codepre
0
how can i change a users twitter name with a bot
pyou can use the codepost accountupdateprofilecode api endpoint to update your twitter username see a hrefhttpsdevtwittercomrestreferencepostaccountupdateprofile relnofollowthe relevant documentationa for detailsp
0
reset an open serial port
ptry using the handle to close the port instead of invoking the constructor again if you the port is open and you call serialserialcom4 9600 it will attempt to reopen the port again and failp pif serialport was assigned successfully then serialportclose should close itp
0
python functionconverting texting language to english
pfor something a bit more elaborate try a hrefhttpsgithubcomlysdexialookaheadlev relnofollowlookaheadleva i made it for a similar situation just put your thumblish into a yaml file and call it its designed to be a web service but you could probably modify it to suit your needsp
0
python determine frequency of numbers showing up in dice rolls
precodefrom collections import defaultdict def rolldicen list the results of rolls d defaultdictint for i in rangen res roll dres 1 accumulate results printres print results sort and print results since theres only 11 items there is no sense using iteritems here wed just have to change it for py3k for keyvalue in sortedditems percent floatvaluen100 print results use explicit field widths to make sure the bargraph is aligned print 02d14dt26ft3formatkeyvaluepercentintpercent rolldice2000 codepre
0
pythonmatplotlib contour plot with bilinear interpolation
pthis one seems to workp precodeimport matplotlib import numpy as np import matplotlibcm as cm import matplotlibpyplot as plt from scipyinterpolate import interp2d httpenwikipediaorgwikifilebilininterppng xi nparray00 10 yi nparray00 10 zi nparray00 10 10 05 another example xi nparray00 025 10 yi nparray00 075 10 zi nparray00 05 10 05 07 05 10 10 10 i want 20 levels to be shown contourbreaks 20 ticks nplinspacezimin zimax contourbreaks endpointtrue attempt 4 interp2d does to correct bilinear interpolation fig pltfigure axes figaddsubplot111 aspectequal f interp2dxi yi zi kindlinear xi2 nplinspace0 1 100 yi2 nplinspace0 1 100 zi2 fxi2 yi2 axescontourxi2 yi2 zi2 ticks11 colorsk fill axescontourfxi2 yi2 zi2 ticks cmapcmjet figcolorbarfill ticksticks show the plots pltshow codepre
0
calculating the entropy of an attribute in the id3 algorithm when a split is perfectly classified
pthe entropy of a split measures the uncertainty associated with the class labels in that split in a binary classification problem classes 01 the probability of class 1 in your text x can range from 0 to 1 the entropy is maximum with a value of 1 when x05 here both classes are equally probable the entropy is minimum when one of the classes is absent ie either x0 or x1 here there is no uncertainty regarding the class hence the entropy is 0p pbrbr graph of entropy yaxis vs x xaxisp pa hrefhttpistackimgurcomgxndcpng relnofollowimg srchttpistackimgurcomgxndcpng altgraph of entropy yaxis vs x xaxisap pbrbr the following calculation shows how to deal with the entropy calculation mathematically when x0 the case when x1 is analogousp pa hrefhttpistackimgurcomrcrwepng relnofollowimg srchttpistackimgurcomrcrwepng altenter image description hereap pbr in your program you could treat x0 and x1 as special cases and return 0 for other values of x the above equation can be used directlyp
0
cant execute python script from php
pthe reason is because of the php doesnt have the permission to writeread the py script in desktop so just change the directory of the py to the same directory as the php file then eveything runs smoothlyp
0
how to get nth result from simple function in python
pfirst your function needs to know what codencode to use thats simple enough just tell it codencode as an argumentp precodedef fibonaccin codepre pif you want to return the first codencode fibonacci numbers youll need to keep a a hrefhttpdocspythonorg2tutorialintroductionhtmllists relnofollowlista of themp precode numbers 0 1 start off with the first 2 numbers codepre pthen compute the fibonacci numbers pretty much the way you did before except stopping at the codencodeth one and adding together the last two list elements instead of codeacode and codebcodep precode xrange2 n is a sequence going from 2 to n1 for i in xrange2 n add together the last two fibonacci numbers and append the result to the list numbersappendnumbers2 numbers1 codepre pfinally return the listp precode return numbers codepre pthe end resultp precodedef fibonaccin numbers 0 1 for i in xrange2 n numbersappendnumbers2 numbers1 return numbers codepre pthis will return a list of the first codencode fibonnaci numbers for coden gt 2code youll need to specialcase coden 0code or coden 1code if you want to handle those valuesp
0
pythonnotify module cron gioerror
pcrontab is considered an external host it doesnt have permission to write to your display p pworkaround allow anyone to write to your display type this in your shell when youre logged inp precodexhost codepre
0
converting json to csv in python list indices must be integers not str
pour input is stronglistlistdictionarystrongp pmeans we have to iterate main list and pick first value from the itemp precodedata r postheader username 09 apr 2015 195855 1 of 6 post example message n nexample message postthreadurl httpwwwexamplewebsitecommessage1 postsymbol eg posttitle example title codepre pstronguse variable names correctly do not create same name variablestrongp pdemop precodeimport csv import json data r postheader username 09 apr 2015 195855 1 of 6 post example message n nexample message postthreadurl httpwwwexamplewebsitecommessage1 postsymbol eg posttitle example title datalist jsonloadsdatareplacen open file by with statement so no need to close file ie fpclose with openfilenamecsv wb as fp create csv file object root csvwriterfp write first row in csv file rootwriterowpostheader post", "post_thread_url", "post_symbol", "post_title"]) #- iterate every item from the data list: for i in data_list: # as item i is again list, so pick first element from the list which is type dictionary. # i &gt;&gt;&gt;is list # i[0] &gt;&gt;&gt; is dictionary # i[0]["post_header"] &gt;&gt; get value of post_header root.writerow([i[0]["post_header"], i[0]["post"], i[0]["post_thread_url"], i[0]["post_symbol"], i[0]["post_title"]]) </code></pre>
0
how to transform a column field into a list
psorry for taking so long to answer had a busy week ok i thought you meant a string field not a float field so forget about the splitstuff im leaving the answer above as it may help someone else looking for how to transform a string field into a list and use its values for a field calculationp pif im getting this right now you mean the value of the first row of column angoriz right so if this value doesnt change then just use it hard coded on the function like thisp pon the expression fieldp precodemyfunctionangoriz codepre pand on the codeblockp precodedef myfunctionoldfield return oldfield 34123 just type the value of the first row here codepre pif you dont want to hard code the value of the first row then you would have to retrieve it somehow but im not sure how you could do this on the field calculator probably you would have to solve this in a completely different way with a script in arcpy or sop pupdate there is also the possibility of using global variables inside the field calculator this means variables that are persistent between function calls because the function gets called by the field calculator for each row and normally all variables inside a function die between calls it is impossible to remember something on local variables but you could use a global variable to save the first rows value and use it on the other following calls i havent tried it but maybe something like this would workp precodefirstvalue none def myfunctionoldfield global firstvalue if firstvalue none this will be true only if this is the first callrow firstvalue oldfield save the value on the global variable return oldfield firstvalue codepre
0
exceeding the size of lists in python
pabout the memory limit how about creating a custom list class that internally is a linked list of lists or arrays magically traverse from one to the other internally and add more as needed as the caller uses your custom list with the external interface youve provided which will be similar to those members needed to facilitate the append remove etc needs of the arrays used in your problemp pemnoteem im not a python programmer not a clue how to implement what i said in python maybe i dont know the context here so i will understand if im voted downp pmaybe use a hrefhttpwwwibmcomdeveloperworkslibrarylpyconhtml relnofollowgeneratorsa as theyre called in python to yield results of your internal lists as if it were one huge single list possibly with a hrefhttpstackoverflowcomquestions280243pythonlinkedlistlinked listap
0
python how to ensure that import comes from defining module
pheres a draft script that solves the problem less than 100 lines a hrefhttppastebincomcfsr6b3s relnofollowhttppastebincomcfsr6b3sap
0
jythonpython not recognizing for loop
pis the value of twplcount zero by any chancep
0
samuelcolvins djangobootstrap3datetimepicker not showing calendar when clicked on input field
h1settingspyh1 pin the installed apps add bootstrap3datetimep h1templateh1 padd the following lines into the html head tagp p block header load static p precode ltlink relstylesheet hrefnetdnabootstrapcdncombootstrap 300 cssbootstrapcssgt ltlink relstylesheet hrefnetdnabootstrapcdncombootstrap300cssbootstrapthemecssgt ltscript srcajaxgoogleapiscomajaxlibsjquery190jqueryjsgtltscriptgt ltscript srcnetdnabootstrapcdncombootstrap300jsbootstrapjsgtltscriptgt codepre p formmedia endblock p
0
python filenotfounderror when using open
plets say you run codepwdcode and it returns codehomemynamecode if you then run codehomemynamecodemyprogrampycode the working directory of your program is emnotem codehomemynamecodecode its codehomemynamecode the working directory of a process in inherited from the parent process not set based on where the script is locatedp
0
wtform fieldlist with selectfield how do i render
padd a codesubmitfieldcode to your to codeorderformcodep precodesubmitsomething submitfielduadd something codepre pand then call it from your view and use the codeappendentrycode method of codefieldlistcodep precodeif formsubmitsomethingdata formorderentriesappendentry return rendertemplateyourtemplatehtml formform codepre phope that helps p
0
why is is python throwing error at the second method in of this class
pyoure missing parentheses here codeselfformulab selfformulabcode should be codeselfformulab selfformulabcodep
0
how to i list down the results of a function python
pthis helpp precodedef add ask true res while ask num1intinputenter first number num2intinputenter second number total num1num2 userselect inputdo you want to add ny yes n no n if userselect not in y n print error elif userselect y ask true else ask false resappendtotal return res print add codepre
0
regex to find string a only before string b occurs python
preading the file line by linep precodeimport re from itertools import takewhile with openyourfile as fh printrematchrlevel igroup1 for i in takewhilelambda x sample not in x fh if level in i codepre pif you slurp the whole file akshat mahajans way in a string sp precodem rematchrlevel m ssplitsample 10 if m print mgroup1 codepre ppure regex way ugly emfrom the start of the string reach the first level occurrence at the start of a line and forbids the word sampleemp precodem rematchrslbslsamplebltllevel sllevel s if m print mgroup1 codepre
0
excel printing in to different column
pi think only a slight modification is required you are putting a newline in between the x y values that does not need to be there this should produce rows with x y p precode for j in range21shnrows fwritestrshcellj0value fwrite fwritestrshcellj1value fwriten codepre
0
how to install texttable in python
pyou have to download the module from the a hrefhttpspypipythonorgpypitexttable relnofollowpython websiteap pdecompress the archive and go into the directory then execute the script codesetuppycode with codeinstallcode in argumentp precodepython setuppy install codepre pyou can find more information in a hrefhttpdocspythonorg2install relnofollowthe documentationap
0
updating python tkinter gui using after method
pit looks like the problem is herep precodeapplicationentryvarapplication codepre pcodeapplicationcode is a class rather than an object so my guess is that you should be using an instance of codeapplicationcode both places in that code p
0
writing keyvalue pairs to a tabdelimited file with variable s of values
precodegtgtgt x y for x x2 in mydictiteritems for y in x2 fish kate cat andy cat colby cat jeff spider kate spider susan dog andy codepre
0
mirroring something to another side in python
pi prefer pointy trees and just to be different using codestrcentercode over codestrrjustcodep precodedef treeheight symboli width height2 1 for i in rangeheight printsymbol i21centerwidth gtgtgt tree12 i iii iiiii iiiiiii iiiiiiiii iiiiiiiiiii iiiiiiiiiiiii iiiiiiiiiiiiiii iiiiiiiiiiiiiiiii iiiiiiiiiiiiiiiiiii iiiiiiiiiiiiiiiiiiiii iiiiiiiiiiiiiiiiiiiiiii codepre
0
filter the table by a search query with search fields is in a dictionary
pyou can use a dictionary in filterp precoded checkin 12042016 checkout 13042016 location india modelinstanceobjectsfilterd codepre
0
how do i check to see if a variable is inside a list housed in a dictionary in python
pcodeannotationlicensecode is a list containing two tuplesp precodegtgtgt annotation customerid 35 guestos 1287 license vmware vm 01 veeam backup vm 02 gtgtgt alist annotationlicense gtgtgt alist0 vmware vm 1 gtgtgt alist1 veeam backup vm 2 gtgtgt product licenseid alist0 gtgtgt product vmware vm gtgtgt licenseid 1 gtgtgt codepre phope this clarifies the situationp
0
why does my python script stop executing when i try to make my api call
pwhat does this do for you with your keyp precodeusrbinpython import json as jsonmod import pprint import urllib2 apikey 1 or whatever url httpstrombergdnsaliasorgstrombrgtechtidbitshtml accessing alchemy api to get the relevance url httpaccessalchemyapicomcallsurlurlgetrankedkeywordsapikeysampurlsampoutputmodejson apikeyurl sample url httpaccessalchemyapicomcallsurlurlgetrankedkeywordsapikey83da2d0deaef076648b28972905d2f8c1f5e3c0fampurlhttpwwwgooglecomampoutputmodejson text urllib2urlopenurlread json jsonmodloadstext pprintpprintjson codepre pfor me it prints a json object describing an authentication errorp
0
python choosing random object from a list
pid suggest using a hrefhttpdocspythonorg2librarybisecthtml relnofollowbisectap precodefrom bisect import bisect class elementobject def initself value selfa value def reprself return elementformatselfa data element3 element5 element7 element1 last 0 breakpoints for element in data breakpointsappendlast elementa last elementa printbreakpoints for randomvalue in xrangelast pos bisectbreakpoints randomvalue printrandomvalue datapos codepre pyou have to build the list with the breakpoints just once then you can use it with the pretty fast bisect algorithm as long as you likep pthe last loop is just to demonstrate the resultp pedit an alternative approach to get the breakpoints i didnt like the forloopp precodevalues valuea for value in data breakpoints sumvaluespos1 for pos in xrangelenvalues codepre
0
why are my pygame images not getting the alpha set after changing from windows to mac
pa hrefhttpstackoverflowcoma130780803157252httpstackoverflowcoma130780803157252a not mine foudnd itp ptheres perpixel alpha colorkey alpha and persurface alpha youre asking for colorkeyp pwhen you call a hrefhttpwwwpygameorgdocsrefsurfacehtmlsurfaceconvertalpha relnofollowcodeconvertalphacodea it creates a new surface for perpixel alphap pand from a hrefhttpwwwpygameorgdocsrefsurfacehtmlsurfacesetcolorkey relnofollowsetcolorkeyap blockquote pthe colorkey will be ignored if the surface is formatted to use per pixel alpha valuesp blockquote pso load image with codeconvertcode since you want to use a color key then call codesetcolorkeycodep blockquote palso i saw nothing in the docs about passing 1 as first argument to setcolorkeyp blockquote pthats probably from a tutorial which has a loadimage function to grab the topleft pixels color valuep
0
python implicit conversion of object to str
pyou can use reprp precodeclass a def initself selfb reprb def reprself return lta with selfb insidegt class b def reprself return ltbgt a a printrepra codepre pits works for mep
0
problems matching string between quotes but not if lines starts with
pyour hang up will be matching a line starting in a codecode cause that prevents you from being able to just do codes codep pyou can solve that with this regexp precodess codepre phowever that will only capture the first string in quotes you can just add another capture on to this to grab the second string in quotesp precodess codepre pbut if you need to support capturing an indeterminate number of strings in quotes youll need to use a hrefhttppypipythonorgpypiregex relnofollowcoderegexcodea or something similar with a regex like thisp precodess codepre
0
write a program in python 35 that reads a file then writes a different file with the same text that was in the first one as well as more
pgood first try and with that i can go through your code and explain what you did right or wrongp precodefileobjectopenlinestxtr for ln in fileobject println codepre pthis is fine though generally you want to put a space before and after assignments you are assigning the results of codeopencode to codefileobject and add a space after acode when separating arguments so you might want to write that like sop precodefileobject openlinestxt r for ln in fileobject println codepre phowever at this point the internal reference in the codefileobjectcode have reached the end of the file so if you wish to reuse the same object you need to a hrefhttpsdocspythonorg3libraryiohtmlioiobaseseek relnofollowcodeseekcodea back to the beginning position which is code0code as your assignment only states write to the file and not on the screen the above loop should be omitted from the file but i get what you want to do you want to see the contents of the file immediately though sometimes instructors are pretty strict on what they accept moving onp precodecount1 fileinputopennumberedlinestxtw for line in fileobject codepre plooks pretty normal so far again minor formatting issues in python typically we name all variables lowercase as names with capitalization are generally reserved for class names if you wish to you may a hrefhttpsdocspythonorg3tutorialclasseshtml relnofollowread about thema now we enter into the loop you gotp precode printcount linestr codepre pthis prints not quite what you want as code linecode is enclosed inside a quote it is treated as a string literal so its treated literally as text and not code given that you had assigned codelinecode you want to take out the quotes the codestrcode at the end simply just print out the string object and it definitely is not what you want also you forgot to specify the codefilecode you want to print to by default it will print to the screen but you want to print it to the the codenumberedlinestxtcode file which you had opened and assigned to <code>file_input</code>. we will correct this later.</p> <pre><code> count=+1 </code></pre> <p>if you format this differently, you are assigning <code>+1</code> to <code>count</code>. i am guessing you wanted to use the <code>+=</code> operator to increment it. remember this on your quiz/tests.</p> <p>finally:</p> <pre><code>file_object.close file_input.close </code></pre> <p>they are meant to be called as functions, you need to invoke them by adding parentheses at the end with arguments, but as <code>close</code> takes no arguments, there will be nothing inside the parentheses. putting everything together, the complete corrected code for your program should look like this</p> <pre><code>file_object = open("lines.txt", 'r') count = 1 file_input = open("numbered_lines.txt", 'w') for line in file_object: print(count, line, file=file_input) count += 1 file_object.close() file_input.close() </code></pre> <p>run the program. you will notice that there is an extra empty line between every line of text. this is because by default the <a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow"><code>print</code></a> function adds a new line <code>end</code> character; the line you got from the file included a new-line character at the end (that's what make them lines, right?) so we don't have to add our own here. you can of course change it to an empty string. that line will look like this.</p> <pre><code> print(count, line, file=file_input, end='') </code></pre> <p>naturally, other python programmers will tell you that there are pythonic ways, but you are just starting out, don't worry too much about them (although you can definitely pick up on this later and i highly encourage you to!)</p>
0
python unittest asserting dictionary with lists
pmaybe you can check for the two elements separatelyp precode objdict objexporttodict selfassertequalresultingdictionarystate objdictstate selfassertcountequalresultingdictionaryneighbours objdictneighbours codepre
0
how to capture division in sql query
ul liuse codescode to match nonspace not codescode seems you missed backslashli liyou dont need to escape codecode in python regular expressionli ul hr precodegtgtgt refindallrss ab bd and ce is not equal to be a b b d c e b e codepre
0
it seems that i am getting error requestsexceptionsconnectionerror getaddrinfo failed because a minus
pthe exception was raised after several attempts to call codegetaddrinfocode which is used to translate the hostname codep5trcemv2comcode into a network address you must have had some network problems your dns server was temporarily not reachablep pthe fact that it then worked when you changed your script has emnothingem to do with that error your dns server became reachable againp
0
how to add href value in django view
phere you gop precodeltligtlta hrefpolls questionid gt questionquestiontext ltagtltligt codepre
0
protocol or correct syntax for adding even and odd random integers
pits just what it says codenumscode is not iterable codenumscode is a single integer not a list perhaps you meant to iterate over codenumlistcode insteadp
0
distinguishing subparser arguments
pas you can see in a hrefhttpsdocspythonorg2libraryargparsehtmlsubcommands relnofollowdocumentationa there is codedestcode argument to codeaddsubparserscode this argument tells in which variable name of the subparser must be storedp pif you use in your codep precodesubexample exampleaddsubparsersdestparsername codepre pthen after parsing arguments you can use them asp precodeif argsparsername who pass elif argsparsername what pass codepre
0
parse datetime with hours 124 instead of 023
pid probably just go for something simple likep precodefrom datetime import datetime import re s 20121501 24 y d m h mapint refindalld s dt datetimey m d h 1 20120115 230000 codepre
0
python tarfile progress
pseems like you can use the codefiltercode parameter of codetarfileaddcodep precodewith tarfileopenlttarball pathgt w as tarball tarballaddltsome filegt filter myfilter def myfiltertarinfo increment some count add tarinfosize to some byte counter return tarinfo codepre pall information you can get from a codetarinfocode object is available to youp
0
finding a point along an arc
precodeclass circleobject def initself center00 radius1 center and radius define a unique circle selfcenter center selfradius radius def isonself point if pointoncircle return true return false def getnewpointself start10 distance1 directionclockwise inputs circle instance of the circle class start tuple of x y the exists on circle distance distance to travel in radians direction clockwise or widdershins assert circleisonstart start point is not on the circle code to calculate new point here basic geometry use google end return end def getpointsonanarcself x1 y1 x2 y2 large clockwise startdistance enddistance your function signature will only work if it is a class method the alternative is to change the signature and explicitly pass in a circle object to the function sx sy getnewpointstartx1 y1 distancestartdistance directionclockwise ex ey getnewpointstartx2 y2 distanceenddistance directionwiddershins return sx sy ex ey codepre
0
return only returning last item
precoderesult ireplaceprice y codepre prebinds coderesultcode to the new codenamedtuplecode object returned by codereplacecode as this happens once for each item in the list only the last one is returned from your function you should use codelistappendcode insteadp precoderesultappendireplaceprice y codepre por better yet a list comprehensionp precodedef dishlistchangepricedl list percentage float gt list x 1 percentage1000 return dreplacepricedpricex for d in dl codepre pyou probably shouldnt be using codereplacecode the leading underscore in the method name suggests that it is intended for private use within the class see a hrefhttpswwwpythonorgdevpepspep0008 relnofollowpep8a regarding identifiers with leading underscores however as codereplacecode is a hrefhttpsdocspythonorg35librarycollectionshtmlcollectionssomenamedtuplereplace relnofollowdocumenteda and is available in both versions of python its unlikely that it will disappear or be changed nevertheless a safer way is to explicitly instantiate a new codedishcode within a list comprehension like thisp precodedef dishlistchangepricedl list percentage float gt list x 1 percentage1000 return dishdname dpricex dcalories for d in dl codepre
0
how do i put a progress bar in a messagebox in tkinter in python
pi think you have an error in your code codepbarttkprogressbarapp code should be replaced by codepbarttkprogressbarroot1 code in this class instantiation the first argument is the parent widget and i bet it should be coderoot1code in your codep pbut as written by brc in comment we cant be sure as long as you do not describe your error give us the traceback for examplep
0
knn with rfecv returns the classifier does not expose coef or featureimportances attributes
perror is pretty self explanatory knn does not provide logic to do feature selection you cannot use it sklearns implementation to achieve such goal unless you define your own measure of feature importance for knn as far as i know there is no such general object and so scikitlearn does not implement it svm on the other hand like every linear model provides such information p
0
useful default repr for nested class instances
pthis is a slightly modified version of what john zwinck proposedp pit considers how to format sequences and changes the format slightly its not perfect at the moment though i think in particular it will break for dictionaries as the iterable component will only print the keyp precode def reprself indent2 result selfclassname n items selfdictitems for ikv in enumerateitems if in k continue if isinstancev abstractbase vstr n indent 2 vreprindent 4 elif isinstancev collectionsiterable s strv bstart s0 bend s1 newindent indent 3 vstr n newindent 1 bstart for jitem in enumeratev if isinstanceitem abstractbase if j vstr newindent vstr itemreprnewindent 2 else vstr repritem vstr n vstr newindent 1 bend else vstr strv result indent k vstr if i lenitems 1 result n result resubn n result return result codepre
0
file uninitalized when using python in c
pit seems that the ironpython compiler included in visual studio is not able to handle this kind of filehandling in combination with the poster libraryp pbut it is possible to call the python file with a c project and not a cpython projectp
0
how do i make it so the code only shifts the letters and not the space
pall you have to do is check if the current character is not one you want to skipp precodefor i in range0lens if not a space cipher this character if si sichrordsi intshift codepre pthere is however a possibility that one of your characters will be ciphered to a space in which case that character would be skipped when reversing the cipherp palso a simple cipher like this should not be considered secure in the leastp
0
fishers exact test for bigger than 2 by 2 contingency table
pyes it is ok to do fishers exact test on 5x2 or 5x3 tables p pthere arent any clean widely tested solutions out there in python one solution would be to use a hrefhttpsrpy2readthedocsio relnofollowrpy2a and call the r function from python p precodeimport rpy2robjects as robjects from rpy2robjectspackages import importr stats importrstats v robjectsintvector4410456 m robjectsrmatrixvnrow3 res statsfishertestm print m gtgtgt 1 2 gtgtgt 1 4 4 gtgtgt 2 4 5 gtgtgt 3 10 6 print pvalue formatres00 gtgtgt pvalue 0668165917041 codepre panother solution would be to dig into the fortran code that the r version uses and to call that code directly here is a link to someones a hrefhttpsgithubcommaclandrolfisherexact relnofollowgithub projecta where they did exactly thatp
0