text_a
stringlengths
5
12.3k
text_b
stringlengths
36
15.7k
Score
int64
1
3
the dummyassignments static method studentids fields try giving default values fields class assignment def initself name discription deadline grade studentid selfname name selfstudentid studentid selfdescription discription selfdeadline deadline selfgrade grade def strself return studentid selfstudentid assignment name selfname description selfdescription deadline selfdeadline grade selfgrade def validationself errors selfstudendid errorsappendno existing student id selfdescription errorsappendno existing description selfdeadline errorsappendno existing deadline selfdeadline errorsappendno existing deadline return errors staticmethod def dummyassignments ret studentid range print sda assignmentstudentidstudentid retappenda return ret def testassigment assignment print testassigment print assignmentdummyassignments
im trying learn classes something holding em back get nameerror global name self defined happens class field help find wrong thank code class assignment def initself name discription deadline grade studentid selfname name selfstudentid studentid selfdescription discription selfdeadline deadline selfgrade grade def strself return studentid selfstudentid assignment name selfname description selfdescription deadline selfdeadline grade selfgrade def validationself errors selfstudendid errorsappendno existing student id selfdescription errorsappendno existing description selfdeadline errorsappendno existing deadline selfdeadline errorsappendno existing deadline return errors staticmethod def dummyassignments ret studentid range print sda assignmentself name discription deadline grade studentid retappenda return ret def testassigment assignment print testassigment print assignmentdummyassignments
1
i problem netbeans starting netbeans first errored error message then start give error i looked netbeans directory user directory found attempted delete lock file directory when i first tried delete said use so task manager i go processes tab find netbeans i killed task able delete lock then netbeans started
i went tools plugins then chose install three python items show after installation i choose restart netbeans option but instead restarting netbeans closed and opening any ideas fix i normally develop java netbeans install i using mac osx i see takers let ask is way revert new plugin install
1
v absyx v x v edit for pretty printing use something like print leni tuplei
i vector int values like v i want create mm matrix stores distance elements ie take element vector substract ones end i end i want implement python without using numpy i done far def main v llenv filling matrix rangel j rangel mijabsvivj visualize matrix rangel j rangel print mij but i getting error recognize bounds why
2
i found prepending cflagsilocal include dir ldflagsllocal lib dir command line calling setuppy trick
i trying install python module contains c modules the c code relies library available system global install locations usrinclude usrlib case i local installation lib available therefore i would like pass parameters eg incdir libdir calling setuppy build values end setup script is way achieve
3
you probably use builtin bulkloader tool download objects via remote api save selected fields csv format
i want commaseparated list email addresses application stores it large regular request writing blobstore also large request class csvhandlerwebapprequesthandler def getself entities entityallfetch entity entities sstrentityemail filename filesblobstorecreatemimetype applicationoctetstream filesopenfilename f fwrites filesfinalizefilename blobkey filesblobstoregetblobkeyfilename can i task queue backend something else instead thank advance suggestion
1
you need make list row inside enveloping list i used double list comprehension make made formatting little prettier printing matrix also watch indices remember range goes first index one minus second index passed you could also print joinrow row print nicely def main v llenv filling matrix mabsx v x v visualize matrix rangel j rangel print mij print main result
i vector int values like v i want create mm matrix stores distance elements ie take element vector substract ones end i end i want implement python without using numpy i done far def main v llenv filling matrix rangel j rangel mijabsvivj visualize matrix rangel j rangel print mij but i getting error recognize bounds why
1
after running following defaults write comappleversionerpython version to make sure packages install sudo installed correct python version also set versioner option superuser sudo su enter password defaults write comappleversionerpython version exit
i upgraded lion came python i need use default python project i primarily work uses
2
when enter nonunicode string literal python interactive session system default encoding assumed it appears using windows default encoding therefore probably cp cp cpython python default jun msc v bit intel win type help copyright credits license information import sys sysstdinencoding cp olã¡ mundo olxa mundo u olã¡ mundo encode cp olxa mundo if change codepage roughly equivalent latin strings display expected cchcp active code page cpython python default jun msc v bit intel win type help copyright credits license information import sys sysstdinencoding cp olã¡ mundo olxe mundo
i facing huge encoding problem python dealing iso latin character set when using oslistdir get contents folder i getting strings encoded iso ex olxe mundo however python interpreter string encoded different charset in olã¡ mundo decode latin out u olxa mundo how i force python decode string format i seen oslistdir returning strings correctly encoded interpreter ã¡ character corresponds xe iso xa httpenwikipediaorgwikiisoiec any thoughts overcome
2
your list starts empty you index element list one way solve would create lists append filling matrix rangel x j rangel xappend absvivj mappendx or could create matrix fill l x rangel filling matrix rangel j rangel mijabsvivj better yet list comprehension shown absyx v x v i use numpyscipy scipyspatialdistancepdistv
i vector int values like v i want create mm matrix stores distance elements ie take element vector substract ones end i end i want implement python without using numpy i done far def main v llenv filling matrix rangel j rangel mijabsvivj visualize matrix rangel j rangel print mij but i getting error recognize bounds why
1
i found using rather localhost worked ab n c http update may bug ab httpsgroupsgooglecomforummsgnodejstzuhmdoiiyivudlmaaj
i testing eventlet i getting error ab n c httplocalhost this apachebench version revision copyright adam twiss zeus technology ltd httpwwwzeustechnet licensed the apache software foundation httpwwwapacheorg benchmarking localhost patientaprsocketrecv connection reset peer total requests completed the website works localhost returns ok i issue tomcat website worked fine what could issue
3
try using pylibmc memcache driver rather using pythonmemcache i seen issue memcache ubuntu well
i discovered issue trying store lot keys using pythonmemcached here i import memcache this dict entries generated production server v evalopenhomedragoonoutputread memcacheclient unixtmpmemcachedsock debug next i trying set values in lenasetmultiv memcached memcache unixtmpmemcachedsock timed marking dead out the log output memcached server going connnewcmd connparsecmd set dbdeafcaaaff going connparsecmd connnread found key dbdeafcaaaff stored going connnread connwrite failed write due blocking broken pipe going connwrite connclosing connection closed after time in lenasetmulti test out in aget test out default timeout seconds increasing even seconds help memcached getting stucked so question problem memcache i saw people talking storing entries even store
1
yes use pyexe ask questions specific problems
i scrapy script working fine to distribute friends i need executable know much scrapy would someone tell turn scrapy script exe file is pyexe applicable regard
1
instead trying save entire file single write operation write blobstore chunks using csv module make easier allowing write progressively
i want commaseparated list email addresses application stores it large regular request writing blobstore also large request class csvhandlerwebapprequesthandler def getself entities entityallfetch entity entities sstrentityemail filename filesblobstorecreatemimetype applicationoctetstream filesopenfilename f fwrites filesfinalizefilename blobkey filesblobstoregetblobkeyfilename can i task queue backend something else instead thank advance suggestion
1
your problem wrote j instead last line j listex listex j print listexindexi however better approach use enumerate item listex item enumeratelistex item item print
listex cat select brown dog turtle apple listex hampter bird monkey banana cat j listex listex j print listexindexj what i trying accomplish search items listex listex if item listex found listex i would like know print index value item found listex listex thanks
2
there problems code not images px x px trying add image list contain x images to solve scale x adding list you assign image list tree object applying images tree items here fixed code import wx class testframewxframe def initself wxframeinitself none selftree wxtreectrlself style wxtrhideroot selfroot selftreeaddroot gr selftreeappenditemselfroot grooveshark popr selftreeappenditemgr popular sr selftreeappenditemgr search dr selftreeappenditemselfroot download pr selftreeappenditemselfroot pandora statr selftreeappenditempr stations imagelist wximagelist grooveshark imagelistaddwximageimagesgrooveshark custompng wxbitmaptypepngscaleconverttobitmap popular imagelistaddwximageimagespopular custompng wxbitmaptypepngscaleconverttobitmap search imagelistaddwximageimagessearch custompng wxbitmaptypepngscaleconverttobitmap download imagelistaddwximageimagesdownload custompng wxbitmaptypepngscaleconverttobitmap pandora imagelistaddwximageimagesplaylisticon custompng wxbitmaptypepngscaleconverttobitmap stations imagelistaddwximageimagesstations custompng wxbitmaptypepngscaleconverttobitmap selftreeassignimagelistimagelist selftreesetpydatagr none selftreesetitemimagegr grooveshark wxtreeitemiconnormal selftreesetpydatapopr none selftreesetitemimagepopr popular wxtreeitemiconnormal selftreesetpydatasr none selftreesetitemimagesr search wxtreeitemiconnormal selftreesetpydatadr none selftreesetitemimagedr download wxtreeitemiconnormal selftreesetpydatapr none selftreesetitemimagepr pandora wxtreeitemiconnormal selftreesetpydatastatr none selftreesetitemimagestatr stations wxtreeitemiconnormal name main wxappfalse f testframe fshow amainloop
ok i example runable example example extract zip files run otherwise work however run images added tree ctrl simply error code note run without images see zip file import wx class testframewxframe def initself wxframeinitself none selftree wxtreectrlself style wxtrhideroot selfroot selftreeaddroot gr selftreeappenditemselfroot grooveshark popr selftreeappenditemgr popular sr selftreeappenditemgr search dr selftreeappenditemselfroot download pr selftreeappenditemselfroot pandora statr selftreeappenditempr stations imagelist wximagelist grooveshark imagelistaddwximageimagesgrooveshark custompng wxbitmaptypepngconverttobitmap popular imagelistaddwximageimagespopular custompng wxbitmaptypepngconverttobitmap search imagelistaddwximageimagessearch custompng wxbitmaptypepngconverttobitmap download imagelistaddwximageimagesdownload custompng wxbitmaptypepngconverttobitmap pandora imagelistaddwximageimagesplaylisticon custompng wxbitmaptypepngconverttobitmap stations imagelistaddwximageimagesstations custompng wxbitmaptypepngconverttobitmap selftreesetpydatagr none selftreesetitemimagegr grooveshark wxtreeitemiconnormal selftreesetpydatapopr none selftreesetitemimagepopr popular wxtreeitemiconnormal selftreesetpydatasr none selftreesetitemimagesr search wxtreeitemiconnormal selftreesetpydatadr none selftreesetitemimagedr download wxtreeitemiconnormal selftreesetpydatapr none selftreesetitemimagepr pandora wxtreeitemiconnormal selftreesetpydatastatr none selftreesetitemimagestatr stations wxtreeitemiconnormal name main wxappfalse f testframe fshow amainloop why i followed demo wxpython demo app luck
1
the thing confusing page table hash hashes pagetablev contains hashref hash contains key page whose value integer the loop bitshifts integer clear perl code simpler would foreach v ram pagetablevpage now translation python obvious v ram pagetablevpage
hi i working converting perl python something i looking code hash tables perl i come across line code i really know python i know shifts bit strings page pagetable page table hash hashes pagetableentry page table entry structure dirty boolean referenced boolean valid boolean frameno indicates x ie page ram page used aging algorithm bit string ram x numframes could someone please give idea would represented python i got definitions hash tables done references i thanks help give fori iram pagetableramipage pagetableramipage
2
just use enumerate listex cat select brown dog turtle apple listex hampter bird monkey banana cat j listex pos enumeratelistex j print j found position pos listex this print cat found cat select brown position listex
listex cat select brown dog turtle apple listex hampter bird monkey banana cat j listex listex j print listexindexj what i trying accomplish search items listex listex if item listex found listex i would like know print index value item found listex listex thanks
2
something like ast import literaleval r hellonworld printliteraleval hello world edit ok want what want done general sven marnach explained strings actually contain escape sequences those notation string literals you filter strings nonascii characters list def isasciis try sdecode ascii return true except unicodedecodeerror return false william short x twitter xaa xe video guy ray isasciis
i want remove types escape sequences list strings how i input william short x twitter xaa xe video guy ray output william short twitter video guy ray httpdocspythonorgreferencelexicalanalysishtmlstringliterals
3
you could filter words alphanumeric using list comprehension strisalnum l william short x twitter xaa xe video guy ray word word l wordisalnum william short twitter video guy ray if wish filter numbers use strisalpha instead l william short x twitter xaa xe video guy ray word word l wordisalpha william short twitter video guy ray
i want remove types escape sequences list strings how i input william short x twitter xaa xe video guy ray output william short twitter video guy ray httpdocspythonorgreferencelexicalanalysishtmlstringliterals
1
okay much easier understand answer form i move i would write comment answer luckily overwrite system version python ubuntu comes preinstalled your python binaries python python located usrlocalbin directory userspecific stuff usually installed this fine means system python still first try run system python type command line usrbinpython c import bz print bzdoc this print something like î» usrbinpython c import bz print bzdoc the python bz module provides comprehensive interface bz compression library it implements complete file interface one shot decompression functions types sequential decompression if means fine so fix path tells shell find commands usrlocalbin going priority usrlocal ways fix order difficultyannoyancealtering system remove symlink python usrlocalbin this make type python go back executing usrbinpython alias system python sudo rm usrlocalbinpython move usrbin higher precedence path might desirable already stuff usrlocalbin precedence usrbin i adding completeness in shell profile sure ubuntu default i using bashprofile export pathusrbinpath remove python install this extreme first option i presented first option do really need version python if want isolated python environments probably really want virtualenv you probably remove unless reason it going little annoying though basically remove python python pythonw pythonw commands usrlocalbin remove usrlocallibpython this part complete i forget else
i using python ubuntu i got error importing bz module importerror no module named bz i thought bz module supposed come python how i fix problem edit i think i previously installed python compiling source probably point i libbzdev bz module installed now i hoping install python sudo aptget install python but say already installed is way uninstall previous python installation reinstall
3
this cannot done least broad scope asking as others mentioned runtime python know difference something escape sequences something without example print x prints true so way find difference two strings unless try static analysis python script
i want remove types escape sequences list strings how i input william short x twitter xaa xe video guy ray output william short twitter video guy ray httpdocspythonorgreferencelexicalanalysishtmlstringliterals
1
if want strip characters like use translate function strip sxxxxxxhello world prints hello world xxxx hello world delete escapes joinchrchar char range stranslatenone escapes hello world this strip control characters soh start heading stx start text etx end text eot end transmission enq enquiry ack acknowledge bel bell bs b backspace ht horizontal tab a lf n new line b vt v vertical tab c ff f form feed d cr r carriage ret e so shift f si shift dle data link escape dc device control dc device control dc device control dc device control nak negative ack syn synchronous idle etb end trans blk can cancel em end medium a sub substitute b esc escape c fs file separator d gs group separator e rs record separator f us unit separator
i want remove types escape sequences list strings how i input william short x twitter xaa xe video guy ray output william short twitter video guy ray httpdocspythonorgreferencelexicalanalysishtmlstringliterals
3
the problem kb windows update httpsupportmicrosoftcomkb messing dll search routine security fix setting registry value hkeylocalmachinesystemcurrentcontrolsetcontrolsession manager cwdillegalindllsearch allowed properly load dll files properly import pyd modules this may also happen windows versions
i spent last days trying launch examples boostpython importerror dll load failed the specified module could found error trying load compiled using bjam pyd modules i using windows x python x boost i followed different answers stackoverflow sites incl fresh installs python bit boost precompiled manual boost libraries building dll checks dependency walker luck i registered share solution worked i hope may help someone struggling error
1
that assignment user def postloopself user lilith return user acting local instance var to affect global var user would need add global user top function though i recommend usually better ways things use globals one note globals python while assign value global var without global keyword read global nonlocal scopes without this allows make closures
i two files i trying work menupy menus programpy imports menupy import cmdsys user one class loginmenucmdcmd def postloopself user lilith return user intrologin menu def dosmtoggleselfperson return true def doquitselfperson sysexit class storemenucmdcmd introstore menu def dowhoamiselfperson print storemenu user def doquitselfperson quit true return quit programpy menu import import cmdsys lm loginmenu sm storemenu true lmcmdloop print user smcmdloop i expect programpy gets print user print lilith instead prints one why postloop defined docs method executes cmdloop return i thought would return value user lilith lilith would printed prints one edit it recommended i use globals i reading find
1
cmd nothing user lilith introduces new local binding to rebind global name need global user user lilith also avoid globals
i two files i trying work menupy menus programpy imports menupy import cmdsys user one class loginmenucmdcmd def postloopself user lilith return user intrologin menu def dosmtoggleselfperson return true def doquitselfperson sysexit class storemenucmdcmd introstore menu def dowhoamiselfperson print storemenu user def doquitselfperson quit true return quit programpy menu import import cmdsys lm loginmenu sm storemenu true lmcmdloop print user smcmdloop i expect programpy gets print user print lilith instead prints one why postloop defined docs method executes cmdloop return i thought would return value user lilith lilith would printed prints one edit it recommended i use globals i reading find
1
if want fast python code hog features i ported code cython httpsgithubcomcvondrickpyvisionblobmastervisionfeaturespyx
i read post use opencv hogbased pedestrian detector how i detect track people using opencv i want use hog detecting types objects images pedestrians however python binding hogdetectmultiscale seem give access actual hog features is way use python opencv extract hog features directly image
3
you possibly something else working port try command netstat ln grep check alternatively try telnet localhost connection refused port clear use
im trying create website webpy letting open create socket port works every port i port forwarded problem python mainpy i i get error http traceback recent call last file mainpy line module apprun file usrlocallibpythondistpackageswebapplicationpy line run return wsgirunwsgiselfwsgifuncmiddleware file usrlocallibpythondistpackageswebwsgipy line runwsgi return httpserverrunsimplefunc validiplistgetsysargv file usrlocallibpythondistpackageswebhttpserverpy line runsimple serverstart file usrlocallibpythondistpackageswebwsgiserverinitpy line start raise socketerrormsg socketerror no socket could created code far import mysqldb import web import hashlib h urls index register register login login thankyou thankyou app webapplicationurls globals render webtemplaterendertemplates db webdatabase dbnmysql userroot pw dbrealmd class index def getself return renderindex class register def getself return renderregister def postself webinput user hshaiusernamehexdigest pw hshaipasswordhexdigest n dbinsertaccount usernameuser passwordpw name main apprun can someone help please
3
one easy way smooth data using moving average algorithm one simple form moving average calculate average adjacent measurements certain position in onedimensional series measurements an example moving average calculated example if go measurements done in simple example averaging window size you also use windows different sizes depending much smoothing want to make calculations easier faster wider range applications also use algorithm based convolution the advantage using convolution choose different kinds averages like weighted averages simply changing window let coding illustrate the following excerpt needs numpy matplotlib scipy installed click full running sample code future import division import numpy import pylab scipysignal import convolved def movingaverageddata window moving average twodimensional data makes sure window function normalized window windowsum makes sure data array numpy array masked array typedataname ndarray maskedarray data numpyasarraydata the output array dimensions input data mode symmetrical boundary conditions assumed boundary symm return convolveddata window mode boundary symm the following code generates arbitrary noisy data calculates moving average using four different sized box windows m n the shape data array n the shape window array x numpymgridm n the signal lots noise signal numpycosx noise numpyrandomnormalsizem n z signal noise calculating couple smoothed data win numpyonesm n z movingaveragedz win win numpyonesm n z movingaveragedz win win numpyonesm n z movingaveragedz win win numpyonesm n z movingaveragedz win and see different results code plotting initializing plot pylabclose pylabion fig pylabfigure bbox dictedgecolor w facecolor w alpha crange numpyarange color scale data range the plots ax pylabsubplot pylabcontourfx z crange pylabcontourx z crange colors k axtext n ha left va top transformaxtransaxes bboxbbox bx pylabsubplot sharexax shareyax pylabcontourfx z crange pylabcontourx z crange colors k bxtext n ha left va top transformbxtransaxes bboxbbox bx pylabsubplot sharexax shareyax pylabcontourfx z crange pylabcontourx z crange colors k bxtext n ha left va top transformbxtransaxes bboxbbox bx pylabsubplot sharexax shareyax pylabcontourfx z crange pylabcontourx z crange colors k bxtext n ha left va top transformbxtransaxes bboxbbox axsetxlimxmin xmax axsetylimymin ymax figsavefig movingavgsamplepng that folks and plotted results different sized windows the sample code given uses simple box rectangular window two dimensions there several different kinds windows available might want check wikipedia examples
i working creating contour plot using matplotlib i data array multidimensional it long wide so basically list lists length i contour plot working fine i need smooth data i read lot examples unfortunately i math background understand going so i smooth data i example graph looks like i want look like this graph what i want look similar what means i smooth contour plot like second plot the data i using pulled xml file but i show output part array since element array around items long i show excerpt here sample keep mind excerpt the dimension data rows columns the columns change depending data imported xml file i look values i use gaussianfilter change but changes great enough affect contour plot
3
use splat operator apply arbitrary number arguments op def vectorizeitargs op opargs reference salty crane how use args kwargs also linked aboved unpacking argument lists official docs
i attempting wrap call operation variable argument list generalized function fixed arguments like def vectorizeitargs op op function variable number arguments args list arguments i like pass for example lenargs i like call op like opargsargsargs as far i tell op needs arguments explicitly passed like i change argument list single list dictionary any suggestions appreciated
2
in addition problem identified wooble adding staticdir handler script handler handlers processed order staticdir handler never executed since requests caught one
i problem using template google app engine python thing i address static folder yaml i not access template i remove access able look files file structure src calcpy mainpy indexhtml templ calchtml js css yaml handlers url script mainpy mainpy def main application webappwsgiapplication mainpage calc calc debugtrue wsgirefhandlerscgihandlerrunapplication calcpy class calcwebapprequesthandler def getself temp ospathjoinospathdirnamefile templcalchtml outstr templaterendertemp tempval selfresponseoutwriteoutstr the result is status ok contenttype texthtml charsetutf i reach file template addressing working buttttttt i add following line yaml access css js it access able yaml handlers url script mainpy url templ staticdir templ if change order yaml handlers url templ staticdir templ url script mainpy both not working error status internal server error traceback recent call last file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebappwebapppyquot line call handlergetgroups file quotusersemdocumentsworkspacenerkharzsrccalcpyquot line get outstr templaterendertemp tempval file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line render loadtemplatepath debug file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line load return loaduserdjangopath debug file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line loaduserdjango template djangotemplateloadergettemplatefilename file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginelibdjangodjangotemplateloaderpyquot line gettemplate source origin findtemplatesourcetemplatename file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginelibdjangodjangotemplateloaderpyquot line findtemplatesource raise templatedoesnotexist name templatedoesnotexist calchtml please help must simple solution i really dont believe gae much fool thank advanced
1
you mostly need worry if come point something work come back ask note however determines lineending convention programming language use platform runs nixwindowsmac different
i note sure conventions different types line termination different programming languages i know types line feed carriagereturn line feed my question readline different programming languages like python fdreadline cc filegetline buffer java line bufreadline deal line termination if sensitive different types terminations i treat separately
1
python dicts work like javascript dicts you need use way access elements list querystring param
querystring cgiparseqsdecryptedqs selfresponseoutwritequerystring output param v param v selfresponseoutwritequerystringparam attributeerror dict object attribute param the original dict param v param v so second one working right way access values i running python app engine
1
visit browser there likely already process using port port supposed used http probably easiest way see using
im trying create website webpy letting open create socket port works every port i port forwarded problem python mainpy i i get error http traceback recent call last file mainpy line module apprun file usrlocallibpythondistpackageswebapplicationpy line run return wsgirunwsgiselfwsgifuncmiddleware file usrlocallibpythondistpackageswebwsgipy line runwsgi return httpserverrunsimplefunc validiplistgetsysargv file usrlocallibpythondistpackageswebhttpserverpy line runsimple serverstart file usrlocallibpythondistpackageswebwsgiserverinitpy line start raise socketerrormsg socketerror no socket could created code far import mysqldb import web import hashlib h urls index register register login login thankyou thankyou app webapplicationurls globals render webtemplaterendertemplates db webdatabase dbnmysql userroot pw dbrealmd class index def getself return renderindex class register def getself return renderregister def postself webinput user hshaiusernamehexdigest pw hshaipasswordhexdigest n dbinsertaccount usernameuser passwordpw name main apprun can someone help please
2
your custom index appears wrong order query likely done zigzag mergejoin rather using custom index try filtering properties order indexyaml
i query looks like userbase userentryallfilter debug falsefilter disabled falsefilter firstmessage falsefetch and index built serving kind userentry properties name firstmessage name disabled name debug there around entries userentry filtering fethed the problem the aforementioned fetch single line code takes complete any ideas could my guess might something wrong userentry model it quite properties i know start looking
1
this closest thing looking value test else notest otherwise much else
for reason i remember i believe way set variable python condition true what i mean value test where would hopefully set value test condition true and i going test multiple conditions set different variables like value test testtwo and conditions is possible
3
no python ternary else construct way conditionally bind name assignment statement
for reason i remember i believe way set variable python condition true what i mean value test where would hopefully set value test condition true and i going test multiple conditions set different variables like value test testtwo and conditions is possible
2
i figured answer reading doctestpy posting posterity doctest redirects standard output assigning new file descriptor sysstdout the problem function description closing value original sysstdout file descriptor prior doctest redefinition instead i following def printingfuncinarg filenone stuff file none file sysstdout printresult filefile printingfunc capture sys module rather sysstdout runs retrieve doctest redefined stdout attribute sys running inside test edit this also yields easy way check whether running inside doctest def insidedoctestoriginalstdoutsysstdout return originalstdout sysstdout
how i make python code aware whether running doctest the scenario follows i function print output file descriptor passed argument something like future import printfunction def printingfuncinarg filesysstdout stuff printresult filefile but i try use printingfunc doctest test fails specification keyword argument file invoking print output actually goes sysstdout rather whatever default output redirection set doctest module doctest never sees output so i make printingfunc aware whether running inside doctest knows pass file keyword argument calling print
1
check see module path to python shell import sys print syspath if installed correctly see mock directory one directories printed if find mock directory i assuming pip installing module virtualenv packages directory
i tried install mock library django httpwwwvoidspaceorgukpythonmock but type pip install u mock virtualenv try import mock django project shell get importerror no module named mock what i
2
result x x itertoolsizipa b or result mapoperatoradd itertoolsizipa b
suppose i made large list numbers i want make another one i add pairwise first list here first list a and b how might i generate arithmetic addition logic processing pairwise value one one a b a b producing list c a b a b
3
here two possible options use list comprehension use numpy i using shortened versions lists convenience elementwise sum go c list comprehension b c ael bel aelbel zipa b numpy import numpy np nparray b nparray c b
suppose i made large list numbers i want make another one i add pairwise first list here first list a and b how might i generate arithmetic addition logic processing pairwise value one one a b a b producing list c a b a b
1
choiceform form textarea you need give textarea id use id instead
this follow question i asking seems javascript question google app engine question i form form namechoiceform idchoiceform methodpost actiongchoicehandler onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form i want take value textarea send app formdata i tried var choice documentgetelementbyidchoiceformvalue i get undefined value choice what i wrong and also i understand correctly gchoicehandler called twice form xhr how i fix below handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage var user user count count localstoragesetitemchooser user var choice documentgetelementbyidchoiceformvalue var formdata new formdata formdataappendchooser user formdataappendchoice choice var xhr new xmlhttprequest xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata added per aaron dufour answer return script head body changed onsubmit like onsubmitreturn writetostorage per aaron dufour answer form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form body html update see aaron dufour answer solution
2
i suspect really want use factory method pattern you could change code something like name main variables would normally called config file jobtype job univar jobselect superclassoptionfactoryjobtype univar jobselectjob class superclassobject def initself jobtype univar selfjobtype jobtype selfunivar univar this definition called main function redirects request appropriate job sub class def jobself raise notimplementederror staticmethod def optionfactoryjobtype univar return instance superclass based jobtype univar jobtype job return optionjobtype univar else return optionjobtype univar class optionsuperclass def initself jobtype univar superoption selfinitjobtype univar def jobself print job option print univar class optionsuperclass def initself jobtype univar superoption selfinitjobtype univar def jobself print job option print univar however notice implementation require superclass changed every time new subclass created another alternative would make optionfactory method standalone function rather method superclass like name main variables would normally called config file jobtype job univar jobselect optionfactoryjobtype univar jobselectjob class superclassobject def initself jobtype univar selfjobtype jobtype selfunivar univar this definition called main function redirects request appropriate job sub class def jobself raise notimplementederror class optionsuperclass def initself jobtype univar superoption selfinitjobtype univar def jobself print job option print univar class optionsuperclass def initself jobtype univar superoption selfinitjobtype univar def jobself print job option print univar def optionfactoryjobtype univar return instance superclass based jobtype univar jobtype job return optionjobtype univar else return optionjobtype univar
i written code allows term job used universally perform unique task the specific jobs chosen setting initial variable jobtype from initial variable particulay subclass chosen perform appropriate job maybe code make sense name main variables would normally called config file jobtype job univar jobselect superclassjobtype univar jobselectjob class superclassobject def initself jobtype univar selfjobtype jobtype selfunivar univar selfjobtype job selfjobchoice option else selfjobchoice option this definition called main function redirects request appropriate job sub class def jobself selfjobchoicejob class optionsuperclass def initself pass def jobself print job option print univar class optionsuperclass def initself pass def jobself print job option print univar the thought behind code allow singleconstant main function action variety unique tasks based purely variable jobtype which seems fine my question inexperienced coder i gone right way better way things also i set variable univar correctly superclass correctly shared across allany superclass subclasses thanks
1
iterparse function available xmletree import xmletreecelementtree etree event elem etreeiterparsefile events start end event start printelemtag use tag name attributes elif event end elem children elements elemtext elemtail available elemtext none elemtail none printreprelemtail another option override start data end methods etreetreebuilder xmletreeelementtree import xmlparser treebuilder class mytreebuildertreebuilder def startself tag attrs printamplts tag return treebuilderstartself tag attrs def dataself data printreprdata treebuilderdataself data def endself tag return treebuilderendself tag text xml the captial place pidsouth africaplace placepretoriaplace xml elementtreefromstring parser xmlparsertargetmytreebuilder parserfeedtext root parserclose return ordinary element output xml nthe captial place south africa place pretoria n
i xml data looks like xml the captial place pidsouth africaplace placepretoriaplace xml i would like able extract the xml elements currently provided etree the full plain text document start end tags the location within plain text start element character offset important requirement right etree provides fine i cannot see way directly hoped iterating elements document tree would return many small string could reassembled thus providing however requesting text root node returns text root node first element eg the capital doing sax could involve implementing lot already written many times eg minidom etree using lxml option package code go can anybody help
2
i suggest using urllib like source urlliburlopenhttpsomeurlcomsomepagehtmlread openpathtosomefile wbwritesource you could even shorten although wouldnt want shorten plan enclose individual call try except openpathtosomefile wbwriteurlliburlopenhttpsomeurlcomsomepagehtmlread
i tried download something internet using python i using urllibretriever urllib module i get work i would like able save downloaded file location choice if someone could explain clear examples would very appreciated
3
you access form formally using documentforms choiceform also documentformschoiceform each form elements collection form controls you access much way documentforms choiceform elements choice documentchoiceformchoice provided names follow rules valid javascript identifiers if need use square bracket notation document choiceform choice return reference element named choice form name choiceform so get value documentchoiceformchoicevalue
this follow question i asking seems javascript question google app engine question i form form namechoiceform idchoiceform methodpost actiongchoicehandler onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form i want take value textarea send app formdata i tried var choice documentgetelementbyidchoiceformvalue i get undefined value choice what i wrong and also i understand correctly gchoicehandler called twice form xhr how i fix below handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage var user user count count localstoragesetitemchooser user var choice documentgetelementbyidchoiceformvalue var formdata new formdata formdataappendchooser user formdataappendchoice choice var xhr new xmlhttprequest xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata added per aaron dufour answer return script head body changed onsubmit like onsubmitreturn writetostorage per aaron dufour answer form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form body html update see aaron dufour answer solution
2
itertoolsgroupby collects together contiguous items key if want items key sort selfdata first mid group itertoolsgroupby sortedselfdatakeyoperatoritemgetter keyoperatoritemgetter
i data selfdata list when i run code mid group itertoolsgroupbyselfdata keyoperatoritemgetter listgroup i get list i want but i use instead mid group itertoolsgroupbyselfdata keyoperatoritemgetter group second number tuples i get list even though tuples nd position
3
some great answers i haven’t seen one puts together have… since form one input need access value particular one there ways straightforward might use form’s elements property forms documentgetelementbyidchoiceformelementschoicevalue
this follow question i asking seems javascript question google app engine question i form form namechoiceform idchoiceform methodpost actiongchoicehandler onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form i want take value textarea send app formdata i tried var choice documentgetelementbyidchoiceformvalue i get undefined value choice what i wrong and also i understand correctly gchoicehandler called twice form xhr how i fix below handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage var user user count count localstoragesetitemchooser user var choice documentgetelementbyidchoiceformvalue var formdata new formdata formdataappendchooser user formdataappendchoice choice var xhr new xmlhttprequest xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata added per aaron dufour answer return script head body changed onsubmit like onsubmitreturn writetostorage per aaron dufour answer form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form body html update see aaron dufour answer solution
1
don use class factory silly you need consistent interface across implementations class jobaobject def dojobself arg print job arg class jobbobject def dojobself arg print job b arg jobtypes job joba job jobb jobtype job univar job jobtypesjobtype jobdojobunivar hell jobs keep state classes either functions instead def jobaarg def jobbarg job jobtypesjobtype jobunivar
i written code allows term job used universally perform unique task the specific jobs chosen setting initial variable jobtype from initial variable particulay subclass chosen perform appropriate job maybe code make sense name main variables would normally called config file jobtype job univar jobselect superclassjobtype univar jobselectjob class superclassobject def initself jobtype univar selfjobtype jobtype selfunivar univar selfjobtype job selfjobchoice option else selfjobchoice option this definition called main function redirects request appropriate job sub class def jobself selfjobchoicejob class optionsuperclass def initself pass def jobself print job option print univar class optionsuperclass def initself pass def jobself print job option print univar the thought behind code allow singleconstant main function action variety unique tasks based purely variable jobtype which seems fine my question inexperienced coder i gone right way better way things also i set variable univar correctly superclass correctly shared across allany superclass subclasses thanks
1
what want probably possible using com python tutorial it messy hard code hard debug and way work mac instead i i would try take problem excel for instance python i would first directly access mysql i would parse second xls file using xlrd with results mysql query parsed xls file python data structures replicating behaviour vlookup easy i would write results output xls file using xlwt
i looking way automate entire process uses excel amp odbc queries i know excel use odbc driver run queries mysql database but i need query triggered programmatically the individual steps program script able open excel file run mysql query query change values query hits database come excel file save results query excel file sheet use results vlookups another sheet excel file save results vlookups close file flexible language addons necessary anything would help i looking run windows mac
1
you actually using inheritance original code code contains severe bug masks appearing you create instance superclass stores jobtype univar instantiates either option option stores reference the subclasses initialised data jobtype univar attributes override init donothing methods avoid error when call jobselectjob superclass explicitly delegates jobchoice attribute so useful inheritance going overridden everything superclass subclasses instead jobselect instance different subclasses depending jobtype using method resolution call right code jobselect always superclass contains option option explicitly delegates the serious bug i mentioned neither option option actually contains information job job methods anything interesting you call print univar work would normally print selfunivar get univar job seems work global called univar as soon start anything complicated scheme fall badly srgerg answer good example could actually use inheritance factory functions solve problem catplusplus answer good example use appropriate tools simple code example may need real requirements complex got written moment
i written code allows term job used universally perform unique task the specific jobs chosen setting initial variable jobtype from initial variable particulay subclass chosen perform appropriate job maybe code make sense name main variables would normally called config file jobtype job univar jobselect superclassjobtype univar jobselectjob class superclassobject def initself jobtype univar selfjobtype jobtype selfunivar univar selfjobtype job selfjobchoice option else selfjobchoice option this definition called main function redirects request appropriate job sub class def jobself selfjobchoicejob class optionsuperclass def initself pass def jobself print job option print univar class optionsuperclass def initself pass def jobself print job option print univar the thought behind code allow singleconstant main function action variety unique tasks based purely variable jobtype which seems fine my question inexperienced coder i gone right way better way things also i set variable univar correctly superclass correctly shared across allany superclass subclasses thanks
1
most likely defining candidate another module imported where candidate defined have imported module call dbget calling candidategetkeylist work since forces valid candidate call
i contest entity uses listproperty store keys candidate entities here details class contestdbmodel candidates dblistpropertydbkey def createcandidateobjectsself putlist n name enumerateselftmpcandidates putlistappendcandidateparent self name name keys dbputputlist selfcandidates keys selfput class candidatedbmodel name dbstringpropertyrequired true when i query c modelscandidateallancestorcontestfetch everything works fine but i query using listproperty like c dbgetcontestcandidates i get error kinderror no implementation kind candidate can help understand last query work i imported candidate class module query update note dev server case might make difference update as suggested nick works c modelscandidategetcontestcandidates work raises kinderror models import candidate c dbgetcontestcandidates update the offending line occurs test code i try particular failure production server i used exact line elsewhere work dev production servers nick asked imports i test code syspathappendusrlocalgoogleappenginelibsimplejson import simplejson json everything else typical
1
after looking source code elementtree python hard coded fixtag function as workaround i xmletree import elementtree etree etreeversion etree workaround supressing prefixes def fixtagtag namespaces import string given decorated tag form uritag return prefixed tag namespace declaration isinstancetag etreeqname tag tagtext namespaceuri tag stringsplittag prefix namespacesgetnamespaceuri namespaceuri namespaces prefix etreenamespacemapgetnamespaceuri namespaceuri etreenamespacemap prefix nsd lennamespaces namespacesnamespaceuri prefix prefix xml xmlns none else prefix none nsprefix prefix else nsprefix xmlns xmlnss nsprefix namespaceuri else xmlns none prefix none prefix else prefix return ss prefix tag xmlns etreefixtag fixtag etreenamespacemap httpsomenamespace none else for etree use registernamespace function etreeregisternamespace httpsomenamespace in case post ever gets date code maintained
in python etree i suppress xml prefixes elements like python r jun gcc based apple inc build llvm build darwin type help copyright credits license information import xmletreeelementtree etree etreeversion something etreeelement httpsomenamespacetoken etreetostringsomething nstoken xmlnsnshttpsomenamespace etreeregisternamespace httpsomenamespace etreetostringsomething token xmlnshttpsomenamespace the registernamespace function added i trying remove prefix way compatible python etree version here i tried python r jul gcc based apple inc build llvm build darwin type help copyright credits license information import xmletreeelementtree etree etreeversion something etreeelement httpsomenamespacetoken etreetostringsomething nstoken xmlnsnshttpsomenamespace etreenamespacemap httpsomenamespace etreetostringsomething token xmlnshttpsomenamespace this i want the prefixes still blank is way remove completely
3
as others said accessing form data want textarea if give textarea id probably easiest way get value after much discussion determined need xhr here form look like form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typehidden namechooser idformchooser input typesubmit valuesubmit choice form and use javascript function edit form allowing submitted var count function writetostorage var user user count count localstoragesetitemchooser user documentgetelementbyidformchooservalue user
this follow question i asking seems javascript question google app engine question i form form namechoiceform idchoiceform methodpost actiongchoicehandler onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form i want take value textarea send app formdata i tried var choice documentgetelementbyidchoiceformvalue i get undefined value choice what i wrong and also i understand correctly gchoicehandler called twice form xhr how i fix below handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage var user user count count localstoragesetitemchooser user var choice documentgetelementbyidchoiceformvalue var formdata new formdata formdataappendchooser user formdataappendchoice choice var xhr new xmlhttprequest xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata added per aaron dufour answer return script head body changed onsubmit like onsubmitreturn writetostorage per aaron dufour answer form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form body html update see aaron dufour answer solution
1
to start main want notice loops first read line one time assign list words line words but overwriting words words list words last line now put words doclist think loop nesting fix section first def main x docread words xsplit word words doclistappendword now move parts missing python lot useful libraries for lowercasing string try looking httpdocspythonorglibrarystdtypeshtmlstrlower for getting rid punctuation might find function helpful determining whether character letter httpdocspythonorglibrarystdtypeshtmlstrisalpha since homework i hesitant give away code otherwise learn say something get stuck
awful programmer for class assignment i take words text document count order i trouble erasing punctuation replacing upper case letters lower ones any guidance would greatly appreciated docwords docrawinputplease enter name text file docreadopendoc r doclist def main x docread words xsplit word words doclistappendword def wordcount main counter doclist docwordscounter docwordsgetcounter wordcount docreadclose p sorteddocwords print p docwordsp
1
raise raise exceptions first place a lone raise exception handler propagates exception external handlers
i brand new python need help understanding code fragment c b c d try raise c except d print d except c print c except b print b reading python docs seems raise throws exception i figure raise within try block shouldn something like try something catch raise
1
that code kind ridiculous bizarre way things pretty clear going the list b c d list exceptions since exception raise try block immediately handled appropriate except handler succession except b except c except d handlers thus code equivalent print b print c print d except throw uncaught exception b c d exception
i brand new python need help understanding code fragment c b c d try raise c except d print d except c print c except b print b reading python docs seems raise throws exception i figure raise within try block shouldn something like try something catch raise
1
erasing punctuation one option regular expression module resub function in case i remove characters alphanumeric spaces import it ok print resub w its ok lower case a straightforward lower function string object its ok lower ok
awful programmer for class assignment i take words text document count order i trouble erasing punctuation replacing upper case letters lower ones any guidance would greatly appreciated docwords docrawinputplease enter name text file docreadopendoc r doclist def main x docread words xsplit word words doclistappendword def wordcount main counter doclist docwordscounter docwordsgetcounter wordcount docreadclose p sorteddocwords print p docwordsp
1
python eliminate overhead structures like sorry its dynamic nature makes compiler optimizations difficult but i know language would eliminate overhead introduced keeping things dictionaries dict owner probably includes dictionaries creating inside object they marked noowner dictionaries object instances what use slots add slots names fields class attribute python use efficient implementation class it get rid dictionary used hold attributes if dictionaries rewritten use lists would improve situation lists memory efficient dictionaries for best efficiency rework system use numpy arrays each attribute class would become sized array each element stored efficiently spacewise case alternatively could checkout pypy it provides alternate implementation python jit well various timespace optimizations might help sysgetsizeof reporting think reporting sysgetsizeofmyobjcontainer reports size class object size actual container objects you want sysgetsizeofmyobjcontainer similar even accurate include anything besides base object it take account dictionary holding attributes it report size third row report
i got results heapy unclear exactly mean index count size cumulative kind class dict class dict owner dict myobjcontainer myobjcontainer myobj class truefalse values number values could stored bytes i array i really see consume mb memory i like bring mb possible much data inside object organized dictionaries ease access the dictionaries change rather pointless would cause much overhead would beneficial pack data number bitwise operators i able store entire data object bytes i hoping compiler would sort thing automatically like languages seems opposite the class inherits builtin type object reason use decorators would cause much overhead also curious dict owner means consuming half memory edit sysgetsizeofmyobjcontainer indeed reporting bytes this insane i used dictionaries i need access data based index as far i concerned compiler get rid structures access values directly is better way i imagine lists answer
3
i took look python data model documentation if skip ahead class instances section see crucial explanation attribute assignments deletions update instance’s dictionary never class’s dictionary so example aname introduce new key name dict after access name attribute standard attribute lookup mechanism looks dict first
i defined simple class class myclassobject name google and i creating instance call name attribute myclass aname google also calling directly class myclassname google so far i background c java i call myclassname static invocation calling static members instances fine but i observing till i set aname another value changing myclassname also affecting aname once i set aname changing myclassname affect aname begin different values you see whole experiment class myclassobject name google myclassname google myclass aname google myclassname yahoo aname yahoo myclassname hello world aname hello world myclassname hello world myclassname another trick myclassname another trick aname another trick aname i changed value aname i changed value myclassname another trick myclassname changed aname i changed value i would like someone explain reason behind behavior thanks
2
this situation kind strange completely relying functions sideeffects instead returning values however solution def secondlst rate rangelenlst firstlsti rate
i created function updates single list adding interest rate def firstlst rate rangelenlst lsti lsti ratei my question use function update two dimensional list adding interest rate for example lst rate lst printi my code def secondlst rate x lst x lstxy firstlstxyratex any help much appreciated thanks
1
read length limit proc subprocesspopenargs stdinnone stdoutsubprocesspipe stderrnone true chunk procstdoutread chunk bytes this code comment slightly modified it works import subprocess class containerobject pass self container args yes test selfp subprocesspopenargs stdinnone stderrnone stdoutsubprocesspipe shellfalse true chunk selfpstdoutread print printing chunk print chunk
i think i might repeating question i find answers suited requirement pardon ignorance i program running continuously spits binary data serverit never stops killed i want wrap python script read output process arrives i tried subprocess ideas stack overflow use please suggest psubprocesspopenargsstderrpipestdinpipestdoutpipeshellfalse pcommunicateblocks forever expected pstdoutreadreadlinesreadlineblocks selecton pstdoutfilenoblocks best method
2
jython python java sure want i answered normal python windows i assume to use python windows need install windows binary installer download python download page make sure choose binary installer next need install setuptools get python package index pypi once installed python available windows you able open command prompt type python get python prompt look like python r nov msc v bit intel win type help copyright credits license information then install pywhois open command prompt type ceasyinstall pywhois you see output like searching pywhois reading httppypipythonorgsimplepywhois best match pywhois downloading httppypipythonorgpackagessourceppywhoispywhoistargz mdbdcdbbdafb processing pywhoistargz running pywhoissetuppy q bdistegg distdir cdocumelocals tempeasyinstallhugnulpywhoiseggdisttmpaarhii adding pywhois easyinstallpth file installing pywhoisscriptpy script cpythonscripts installing pywhoisexe script cpythonscripts installing pywhoisexemanifest script cpythonscripts installed cpythonlibsitepackagespywhoispyegg processing dependencies pywhois finished processing dependencies pywhois to confirm installed able import python python r nov msc v bit intel win type help copyright credits license information import pywhois netbeans removed python support see httpwikinetbeansorgpythonroadmap information this httpwikipythonorgmoinintegrateddevelopmentenvironments wiki entry lists ides try
i trying install python module windows computer i installed development version netbeans ide use python editor seems install jython program folder force use installation development i trying install pywhois module half hour i getting pretty infuriated kludginess developing python windows netbeans does anyone know install modules setup should i destroy dev environment use something else would less rageinducing
3
when i web project i found jake gordon javascriptstatemachine quite useful a later i needed fsm python i find anything matching javascript one terms simplicity flexibility i ported python it called fysom
these python fsm implementations i found far fysom a slick fsm implementation provides function callbacks state skip montanero fsm fsm decorators pythoncourse fsm tutorial welldocumented example fsm parsing sentences fsmme a graphical fsm editor w python target also see fsmme tutorial python fsm recipe active state code suited text parsing tasks gof state pattern atampt weighted fsm python python fsm so code golf i need parse text file configurations i looking fsm implementation provides ability munge data inputting next state
3
python supports use case directly collections import counter counter abracadabra mostcommon r b c
i got far def mostfrequentstring dict key string key dkey else dkey return print mostfrequent aabbbc returning c b now i need reverse pair sort number decreasing order print letters should i convert dictionary tuples list
2
actually submitting form twice once writetostorage via ajax also normal way form you change two things writetostorage return false last action change onsubmit onsubmitreturn writetostorage this way prevent default submission form done via ajax writetostorage
the following code seem work i try get chooser google app engine python undefined chooser selfrequestgetchooser selfresponseoutwritechooser chooser returns chooser without value is valid javascript var formdata new formdata formdataappendchooser user var xhr new xmlhttprequest ok test localhost xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata is problem xhr call app update i including code choice clarify chooser per daniel roseman comment in choice handler i writetostorage assigns username form user user writes localstorage after writing user name localstorage i also need write database app i use xhr send gchoicehandler handler so chooser i believe string made var user user count i copy choice handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage var user user count count localstoragesetitemchooser user var formdata new formdata formdataappendchooser user var xhr new xmlhttprequest xhropenpost httplocalhostgchoicehandler true xhronreadystatechange function aevt xhrreadystate ampamp xhrstatus consolelogrequest ok else consolelogconnection error xhrsendformdata script head body form namechoiceform idchoiceform actiongchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form body html update i noticed logs text textarea choice chooser sent xhr shown together one always without value info chooser user choice info chooser choice abcd info chooser user choice info chooser choice efgh this code log chooser selfrequestgetchooser choice selfrequestgetchoice logginginfochooser choice tuplechooser choice newchoice user choice choice owner chooser newchoiceput datastore see chooser choice written different rows what i wrong
1
python tempfile module may looking
i find scripting i often need osmkfifo tmpsomefifoname later osremove tmpsomefifoname is way autogenerate temporary filename guaranteed unique directory i bother put try except oserror around things i aware i could checking fname oslistdir tmp regenerating needed i sure must something little elegant
3
use recent version djangouniform it fixes much
i using djangouniforms display fields rather rudimentary example straight book when i render form fields using formcsrftag formasuniformform everything works expected however djangouniform helpers allow generate form tag helperrelated content using following syntax formhelper helper uniform form helperendwith this creates form tag nowhere embed csrftoken when i try use syntax form renders perfectly without csrf token submitting form fails every time does anyone experience is established way add token i much prefer second syntax reuse reasons thanks
1
one way seems work suggested andreas kloeckner comments alternatives welcome the greet modified follows char const greetboostpythonobject obj pyobject pobj objptr pybuffer pybuf ifpyobjectgetbufferpobj amppybuf pybufsimple void buf pybufbuf double p doublebuf p p pybufferreleaseamppybuf return hello world python use print cmodgreeta
i trying use boostpython wrapper c function receives pointer modifies data managed python side numpy array example returns how i get python numpy boostpython collaborate give raw pointer inside function include boostpythonhpp namespace char const greetdouble p p return hello world boostpythonmodulemodule boostpythondefgreet ampgreet in python i try import numpy np npempty dtypenpdouble rawptr adata print cmodgreetrawptr i get error boostpythonargumenterror python argument types modulegreetbuffer match c signature greetdouble
1
see reflecting database objects sa documentation tablename meta autoloadtrue autoloadwithengine
using table creation normal tablename meta columns this first run i create table in future executions i would like use table without indicate columns this seems redundant already specified table schema in words future accesses i like simply tablename meta columns already read schema is way sqlalchemy
1
there builtin function trivial write def roundquarterx return roundx
i running following issue given various numbers like already builtin function exists round closest step like eg or i go ahead hack together function performs desired task thanks advance best regards dan
2
def myroundx return roundx assert myround assert myround assert myround assert myround
i running following issue given various numbers like already builtin function exists round closest step like eg or i go ahead hack together function performs desired task thanks advance best regards dan
3
this general purpose solution allows rounding arbitrary resolutions for specific case need provide resolution values possible shown test cases def roundpartial value resolution return round value resolution resolution print rounding quarters print roundpartial print roundpartial print roundpartial print roundpartial print rounding tenths print roundpartial print roundpartial print roundpartial print rounding hundreds print roundpartial this outputs rounding quarters rounding tenths rounding hundreds
i running following issue given various numbers like already builtin function exists round closest step like eg or i go ahead hack together function performs desired task thanks advance best regards dan
3
your second list contain logs primes contains logs integers lp
mathematical rule shows program gives wrong answer i would grateful could check small piece code tell problem i know problem somewhere line i pinpoint exact cause but i know sum logarithms primes less n less n my program violates rule here code math import log lp create list n range x rangen n x break else lpappendn fill list primes print lp found value lp create second list range lp number corresponding lp logi llappendi fill second list logs primes print sum sumll
3
ok fault i ran shell tests managepy instead python manage virtualenv directory included syspath mock package unavaible thanks help
i tried install mock library django httpwwwvoidspaceorgukpythonmock but type pip install u mock virtualenv try import mock django project shell get importerror no module named mock what i
1
i ended using addsignalwatchfull unfortunately verbose it works fine though i receive messages handler
i using pygst project working fine i trying migrate new introspection system gi i getting different behavior in old pygst i something like imports import pygst pygstrequire import gst imports gobjectsthreadsinit def myhandlerbus message handle message player gstelementfactorymake playbin myplayer bus playergetbus busconnect message myhandler busaddsignalwatch playersetstategststateplaying start main glib loop the message parameter attribute type used selective processing i interested end stream eos error using new system i imports girepository import gst import glib import gobject imports gobjectthreadsinit loop glibmainloopnone false def bushandlerbus message print message handle message gstinitchecknone player gstelementfactorymake playbin myplayer playersetproperty uri filehomekenjibuttonogg bus playergetbus busconnect message bushandler busaddsignalwatch playersetstategststateplaying start main loop however handler always receives parameter message none i tried filtering i still get nothing ie messages none i read lot gstreamer documentation especially gstbus addsignalwatch playbin i find anything related behavior i checked gst gir file i seen addwatch cannot introspected dead end the glib main loop example make things shorter without full gtk example real thing uses gtkmain giving exactly behavior i using gstreamer informed gstversion arch linux i tested behavior gstreamer ubuntu bit is alternative busconnect am i using wrong way i spent quite hours hunting bug i would really appreciate insight thanks
1
i think using subprocess would better allow control stdin stdout stderr well return exit code captured python httpdocspythonorglibrarysubprocesshtml
i working python based tkinter script flow like a csh script run specifying script name arguments unix terminal a python script written take script name argument input user gui the python script needs execute script prompt user run button gui the code running like def run ossystem scriptfile able execute code problem the control switch back python script execution it waits terminal cursor keeps blinking terminal still execution going i certain execution please suggest to switch back control
1
i ended making plugin placed following run selfviewwindowruncommand exec cmd sh scriptsh quiet false i based code git support plugin httpsgithubcomnotanumbergitst
i various shell build scripts project want create one centralized build system options allow shell script run for example user presses cmd b user given option shellscriptsh shellscriptsh shellscriptsh the user presses sublime text runs sh shellscriptsh i reading httpsublimetextinfodocsenreferencebuildsystemshtml unsure integrate option json code sublime text build system how accomplish build system sublime text thanks
1
this wrong range lp gives numbers lp logi changes loop variable llappendi should range llappend loglpi
mathematical rule shows program gives wrong answer i would grateful could check small piece code tell problem i know problem somewhere line i pinpoint exact cause but i know sum logarithms primes less n less n my program violates rule here code math import log lp create list n range x rangen n x break else lpappendn fill list primes print lp found value lp create second list range lp number corresponding lp logi llappendi fill second list logs primes print sum sumll
1
i going guess launch ninjaide terminal source bashrc new environment variable influences child processes whichever shell process sourcing of course logging may living entirely gui eg click button start ninjaide may need go effort set environment variable how depends upon graphical environment using
i trouble getting pythonpath set i added line bashrc export pythonpathpythonpathhomesaythmyprogramspython i ran source bashrc here issue though i type python terminal get python repl i import modules myprogramspython without problem however i run bpython idle console ninjaide etc import fails import temperature traceback recent call last file pyshell line module import temperature importerror no module named temperature i syspathappendhomesaythmyprogramspython get working i wanted pythonpath work consoles automatically how ps using ubuntu
2
the problem insertedtext signal emitted gtkentrybuffer objects gtkentry ones to connect signal use something like entry gtkentry entrybuffer entrygetbuffer entrybufferconnect insertedtext callback
greetings guys girls i new programming gtk need decent opensource twitter client i find one i developing one opensource i using gtk python pygobject pygtk i problems entry connect handler signals deletedtext insertedtext tweettext entry i tryied selftweettextconnectinsertedtext selfontweet selftweettextsetpropertyinsertedtext selfontweet keeps failing make tweettext multine i searched documentation httpreadthedocsorgdocspythongtktutorialenlatest i find nothing related and also searched c documentation related gtk i apreciate someone help thanks advance
1
no ignore check your xml file xml file xml file ampersand would escaped therefore software designed read xml files parse without error you need correct software generated file generates proper wellformed xml all benefits using xml interchange disappear entirely people start sending stuff wellformed people receiving try patch
i reading xml file using python but xml file contains amp characters running python code gives following error xmlparsersexpatexpaterror wellformed invalid token is way ignore amp check python
3
your range expression range lp expands numbers th element lp exclusive using lp yield right result
mathematical rule shows program gives wrong answer i would grateful could check small piece code tell problem i know problem somewhere line i pinpoint exact cause but i know sum logarithms primes less n less n my program violates rule here code math import log lp create list n range x rangen n x break else lpappendn fill list primes print lp found value lp create second list range lp number corresponding lp logi llappendi fill second list logs primes print sum sumll
1
i think need put dots this test string line this test string line this test string line
suppose i following code def foos a dummy function foo for example this test string line this test string line this test string line fooa this test string line this test string line this test string line print name main import doctest doctesttestmod and let save foopy when i run cpythonpythonexe foopy file foopy line mainfoo failed example this test string line exception raised traceback recent call last file cpythonlibdoctestpy line run compileflags testglobs file doctest mainfoo line this test string line syntaxerror eof scanning triplequoted string literal file foopy line mainfoo failed example fooa exception raised traceback recent call last file cpythonlibdoctestpy line run compileflags testglobs file doctest mainfoo line module fooa nameerror name defined items failures mainfoo test failed failures have tried indent docstring have checked indents spaces indent changed single quote double quote errors different doctest go successfully currently thing work join lines extreme long string separate rn do i miss something
3
count means work the bit iterable type number try rangecount
i using python windows i trying create program accepts numbers tells user many positive many negative many zero i got far count count num floatinputtype number number num zero elif num positive elif num negative print positive print negative print zero but i run code i get typeerror float object iterable if i replace float line int i get problem except says int object iterable i also tried changing value count now i took challenge python tutorial book answer i tell i done everything within syntax put forward the tutorial pdf
3
how something like module import mymodule hasattrmodule classname classname moduleclassname myobject classname
with python application i modules classes contain parser text in function i want instanciate use particular module these sorted database i point i know parser python file name class i want import create however how actually python eg filename lexparser classname lexparser i filename import classname parser classname follow i mean
2
well i looking something similar i came across php equivalent question i translated anwer python f examplejpg fd openf fdread xmpstart dfind xxmpmeta xmpend dfind xxmpmeta xmpstr dxmpstartxmpend printxmpstr convert xmpstr parse xml api
can i use pil like example i need read data i looking easiest simplest way i install pyexiv edit i want believe way library pythonxmptoolkit pyexiv needs exempi boost there must another option
3
for performance reasons pycharm generate python stubs net assemblies default you trigger generation putting caret unresolved reference import statement pressing altenter selecting generate stubs binary module quickfix
i like pycharm used python projects i started messing ironpython i figure make pycharm ide matter except vs works fine recognize net libraries for example i code systemenvironment import path environmentgetfolderpathenvironmentspecialfoldermydocuments the code works fine system part underlined grey everywhere message unresolved reference system the ironpython documentation explains system module rather namespace if i typesystem i get type namespace so way make pycharmpydev recognize namespaces well on side note path fine everything fine
3
the jar file nothing archive bytecompiled java code to execute properly try import subprocess run rjava jar xgreenadamfilejarjar proc subprocesspopenrun
i trying open java link i saved folder desktop i get find file the java address xgreenadamfilejarjar this executable jar file i want open desktop open run normal java link want python open import subprocess runxgreenadamfilejarjar procsubprocesspopenrun i get traceback recent call last file cpythontest line module procsubprocesspopenrun file cpythonlibsubprocesspy line init restoresignals startnewsession file cpythonlibsubprocesspy line executechild startupinfo windowserror error the system cannot find file specified what i wrong find file
1
as don kirkby said first must check conditions asked moreover per point view onemany field blockline treeview field check conditions in py field referenced manyone field call blockid onemany class in xml mo blockid field om tree form view visibleinvisible save record appropriate form id current record id must stored mo field saving om line record if store save action record database onemany class visible tree view mo reference id stored may wrong mo id stored om class show related om records in case data database displayed tree view case need check note take reference saleorder saleorderline class details
i added tree view page notebook element while adding data tree view saving database also displayed tree view when i reload page data tree view vanishes empty the code looks like field namearch typexml notebook colspan page stringblock area field colspan nameblockline nolabel modetreeform tree stringblock field nameblockname field namesize field nameactivefrom field nameactivethru field nameactive tree field page notebook field
1
if usowner userproperty need use user gql datafiles dbdatafilegqlwhere usowner user useremail also remember always use placeholders string interpolation sql mean vulnerable injection
i create entity like company dbdatafileusowner user companyname selfrequestgetname companyput user google user account now i try search user like datafiles dbdatafilegqlwhere usowner useruserid assign jinja template var templatevalues datafiles datafiles output html datafile datafiles datafilename chevrons indicate looping endfor get output the data admin dashboard i access any ideas thanks
3
unfortunately could find way implement resize pgmagick uses c api support scale op yet implemented ugly def resizenewsize g pgmagickgeometrynewsize distinguishes whether width height given image pgmagickimageimg rw rh imagesize w h gwidth gheight w h gheightintrh w rw elif h w gwidthintrw h rh imagescaleg width important resizing final size adjusted according width height respectively for example image x resized resize x function calculates final height uses scale image imgscale x otherwise using scale directly would result new image x
i using graphicsmagick simple operations images resizing croppping etc trying use pgmagick via python instead for resizing script issues following commands gm convert imagejpg resize x resizing mages according width main concern command works expect considers width resizing using pgmagick try operation given import pgmagick p img pimagepblobopen imagejpg rb read imgscale imgscale x pgmagick scale seem respect parameter code scales image width height ever appropriate example image x dimensions resulting image x dimensions terms graphicsmagick behaves like gm convert imagejpg resize x resize x how scale image respect width using pgmagick
1
you define foreign keys using strings avoid exactly problem class artc art mforeignkey article fromotherapp mforeignkey otherapparticle
hello i spliting files model getting bigger so problems my models if category model i remove articletocategory manytomany relationship works well but i need how fix i deleted modelpy order load files model package category modelscategory class categorympttmodel relationships rubetedjangogenericmodelsarticle import article rubetedjangogenericmodelsarticletocategory import articletocategory articles mmanytomanyfieldarticle througharticletocategory articletocategory modelsarticletocategory djangodb import models class articletocategorymmodel rubetedjangogenericmodelsarticle import article rubetedjangogenericmodelscategory import category article mforeignkeyarticle category mforeignkeycategory class meta dbtable articlestocategories verbosenameplural articlestocategories thanks
3
the method match looks beginning string you use search instead also regex built match even amount characters researchr azazazaz str
in python code want pattern match string atleast two consecutive alphabets anywhere string i used rematchr azazazaz str this matches string example abc match abc what mistake regex please help thank you
1
i quite understand want example provided one see misinterpreted rematch see search vs match docs python module
in python code want pattern match string atleast two consecutive alphabets anywhere string i used rematchr azazazaz str this matches string example abc match abc what mistake regex please help thank you
1
to answer updated question researchr azaz str or simply like want alphanumerical characters including underscore researchr w str to match really alphanumericals researchr azaz str the research might help expect match anywhere string beginning
in python code want pattern match string atleast two consecutive alphabets anywhere string i used rematchr azazazaz str this matches string example abc match abc what mistake regex please help thank you
1
try filename lexparser classname lexparser parser getattrimportfilename classname note filename must contain py this work module within package import would return top level package in case import sys filename parserslexparser classname lexparser importfilename parser getattrsysmodulesfilename classname this work cases recommeded import function documentation in examples parser class instantiate normally parser parser
with python application i modules classes contain parser text in function i want instanciate use particular module these sorted database i point i know parser python file name class i want import create however how actually python eg filename lexparser classname lexparser i filename import classname parser classname follow i mean
3
since logfile sorted chronologically parse completely datetime import datetime timedelta datetimenow lookback timedeltaminutes oldest lookbackstrftime ymd hms lines open logfilelog r f line f line oldest linesappendline lines message n joinlines send message per mail
i trying analyze java application logs using logj logged within last five minutes i planning use python analyze last five minutes logs ans warnings send mail can one suggest best method getting log lines last five minutes i use python log format warn sample warning warn sample warning warn sample warning warn sample warning
2
i familiar python api selenium probably receive link using getattributeattributename method so something like linkstr link listlinker linkstr linkgetattributehref linkstr domenesider pass elif strhoveddomene linkstr domenesiderappendside
i sure answered somewhere basic question i however life find answer web i feel like complete idiot i ask goes i writing python code produce list page addresses domain this done using selenium problem occurs i try access list links produced selenium here i far selenium import webdriver import time hoveddomene httpwwwexamplecom listlinker domenesider domenesiderappendhoveddomene driver webdriverfirefox side domenesider drivergetside timesleep listlinker driverfindelementsbyxpatha link listlinker link domenesider pass elif strhoveddomene strlink domenesiderappendside printdomenesider driverclose listlinker variable contain links found page instead list contains i guessing selenium specific objects called webelements i however find webelement attributes give links matter fact i find examples webelement attributes accessed python least manner reproduce i would really appreciate help could give sincerely rookie
3
change function definition changebuttontext accept parameters callback functions called trace function always receive three arguments name variable index mode none really interesting function needs match signature callback work to fix change callback function look like def changebuttontextname index mode buttontextsetwidgetget if prefer also put lambda trace call keep function definition clean along lines define variables use widgettracew lambda n changebuttontext your callback remain case
i dropdown menu buttoni trying change text button according choice dropdown menui used tracebut gives error typeerror changebuttontext takes arguments given this example tkinter import import tkinter tk import os def changebuttontext buttontextsetwidgetget apptk apptitleexample appgeometry x widget stringvar widgetset numbers files one two three widgetdropdown optionmenuapp widget files widgetdropdownconfigbg white foreground black fonttimesitalic widgetdropdownmenuconfigbg white fonttimesitalic widgetdropdownpack widgettracew changebuttontext buttontextstringvar buttontextset zero buttonbuttonapptextvariablebuttontextfonttimes widthborderwidth buttonpacksideleft padxpady appmainloop any ideasthanks
1
use rangecount int float iterable
i using python windows i trying create program accepts numbers tells user many positive many negative many zero i got far count count num floatinputtype number number num zero elif num positive elif num negative print positive print negative print zero but i run code i get typeerror float object iterable if i replace float line int i get problem except says int object iterable i also tried changing value count now i took challenge python tutorial book answer i tell i done everything within syntax put forward the tutorial pdf
1