text_a
stringlengths
5
12.3k
text_b
stringlengths
36
15.7k
Score
int64
1
3
how intopic urlliburlopen httpstackoverflowcomquestionshowdoiinsertanattributeusingbeautifulsoup content beautifulsoupbeautifulsoupintopic tlist contentfindall table tbl tlist tblattrsappend border do forget try lxmlhtml fast parse well
how i insert attribute using beautifulsoup for example insert border tag attribute edit i answered question particular class table even intopic urlliburlopenfilectesttesthtml content beautifulsoupintopic tlist contentfindall table mytableclass tbl tlist tbl border print tblattrs
1
colon special character python string output special email headers try inserting blank line output output nprint customer
really odd experience took hour figure i cgi script written python takes form data forwards email problem colon string would cause python output nothing email does anyone know for example output print customer works though output print customer prints output my email function works essentially serversendmailfromaddr toaddrs msg msg output just wondering colon special character python string output
3
allow make guesses the mail actually sent body appears empty you question say you using builtin python mailing library if open mail mail reader look headers print line present if problem ending mail headers rn pair mail reader thinks print mail header print part body malformed email if add rn headers everything fine
really odd experience took hour figure i cgi script written python takes form data forwards email problem colon string would cause python output nothing email does anyone know for example output print customer works though output print customer prints output my email function works essentially serversendmailfromaddr toaddrs msg msg output just wondering colon special character python string output
1
go read following official modwsgi documentation httpcodegooglecompmodwsgiwikiprocessesandthreading it explains various modes things run gives general guidelines data scope sharing
in regular application like windows objectsvariables created global level available entire program entire duration program running in web application written php instance variablesobjects destroyed end script everything written database so python running apachemodwsgi how work regards memory b how create objects persist web page requests ensure threading issues apachemodwsgi
1
macports terrible pythondjango development everything seems data i team following postgres download install postgresql read readme installing download psycopg source httpinitdorgpubsoftwarepsycopg edit setupcfg set pgconfig librarypostgresqlbinpgconfig then install python setuppy install i recommend using virtualenv well want stay away base mac os x python install much possible
i recently installed django psycop however python refusing use error can someone please help import psycopg traceback recent call last file stdin line module file libraryframeworkspythonframeworkversionslibpythonsitepackagespsycopginitpy line module psycopgpsycopg import binary number string datetime rowid importerror dlopenlibraryframeworkspythonframeworkversionslibpythonsitepackagespsycopgpsycopgso symbol found pqbackendpid referenced libraryframeworkspythonframeworkversionslibpythonsitepackagespsycopgpsycopgso expected flat namespace libraryframeworkspythonframeworkversionslibpythonsitepackagespsycopgpsycopgso
1
look foreignkey docs it says when object referenced foreignkey deleted django default emulates behavior sql constraint on delete cascade also deletes object containing foreignkey this behavior overridden specifying ondelete argument so default behavior cascade delete change specifying something like class foobarmodelsmodel user modelsforeignkeyuser ondeletemodelssetuserobjectsgetorcreateusernamefoooobarrrr
i cannot find option cascade update delete model api am wondering manual help pass db option sycning db idea
1
here example one might format coordinate record description using strformat crd rafbfcfalphafbetafgammaf spz datadictr cryst abcalphabetagammasp p z printcrdformatdata cryst p the format specifier crd interpreted way r tells format stringinterpolate value strr left justified width af tells format stringinterpolate float value right justified total width digits decimal point the complete description format specified works given
i would like format text protein data bank file format basically i need start text specific columns right i formatting using ljust rjust i feel like magic function i could use give word column start any help would greatly appreciated thanks if statckoverflow searching failed please point direction
1
just guess exclusion list meta class set false boolean fields like use checkbox show post data unchecked the form tell difference boolean form field set false one page first place need explicitly exclude
i custom changeuserform modelform user allows user update account information however i save form userisactive userisstaff userissuperuser get set false any thoughts going formspy class userchangeformformsmodelform username formsregexfieldlabelusername maxlength regexr w helptext required characters fewer letters digits errormessages invalid this value may contain letters numbers characters firstname formscharfieldlabelfirst name maxlength lastname formscharfieldlabellast name maxlength email formsemailfieldlabelemail address newpassword formscharfieldlabelnew password widgetformspasswordinput requiredfalse newpassword formscharfieldlabelconfirm new password widgetformspasswordinput requiredfalse class metaauthformsuserchangeform model user exclude password lastlogin datejoined def cleannewpasswordself password selfcleaneddataget newpassword password selfcleaneddataget newpassword password password raise formsvalidationerrorthe two password fields match else lenpassword lenpassword raise formsvalidationerroryour password must minimum characters return password def saveself committrue user superuserchangeform selfsavecommitfalse lenselfcleaneddata newpassword usersetpasswordselfcleaneddata newpassword commit usersave return user class userprofileformformsmodelform class meta model userprofile exclude user viewspy loginrequired def profilerequest context requestmethod post userform userchangeformrequestpost instance requestuser userprofileform userprofileformrequestpost instance requestuserprofile userformisvalid userprofileformisvalid userformsave userprofileformsave return rendertoresponse accountsprofilecompletehtml contextinstancerequestcontextrequest else userform userchangeforminstance requestuser userprofileform userprofileforminstance requestuserprofile contextupdatecsrfrequest context userform userform context userprofileform userprofileform return rendertoresponse accountsprofilehtml context contextinstancerequestcontextrequest
1
django not provide automatic purging there however handy command available help manually httpsdocsdjangoprojectcomendevtopicshttpsessionsclearingthesessionstore
does table need purged taken care automatically django
3
you serialize python object like there section django documentation httpsdocsdjangoprojectcomendevtopicsserializationid here key part look jsonserializerserializequeryset ensureasciifalse streamresponse
i bit newbie python go easy i writing ajax handler django everything pretty straightforward i banging head bit better part day i like return json string contains dict contains queryset modelspy class projectmodelsmodel uniquename modelscharfieldmaxlength uniquetrue title modelscharfieldmaxlength blanktrue description modelstextfield project description blanktrue projectdate modelsdatefield project completion date published modelsbooleanfield class projectimagemodelsmodel project modelsforeignkey project relatedname images image modelsimagefielduploadtogetimagepath title modelscharfieldmaxlength sortmetric modelsintegerfield viewspy projects projectprojectobjectsfilterpublishedtrue responsedict success true maxgroups result analysis projects queryset projects projects this one works i remove projects dict response jsondumps responsedict this one works projects response serializersserialize json responsedict relations images return httpresponse response mimetype applicationjavascript i commented two serialization lines the first one seems work simple dicts since projects included dict fails project project object json serializable the second one seems work querysetsmodels since outer part dict nonmodel complains str object attribute meta note i using wadofstuff serializer understanding would resolve onetomany relationship defined model but even i get working serializing projects i projectimages output question what best way serialize whole responsedict surely i first person want right question why i unable get manytoone relationship work many thanks help update just found one django json serialization mixed django models dictionary looked promising i get queryset object attribute meta
1
you quite relationship you need arrange link looked way the obvious look directly submissionlink sessionquerylinks filterlinkslink u httpfacebookcom first submissionlink none submissionlink linkslinku httpfacebookcom sessionaddsubmissionlink submission submissionstitleu facebook homepage linksubmissionlink sessionaddsubmission sessioncommit you also use hybrid attributes get something looks bit like example substantially convoluted also relationship relation deprecated
i learning use sqlalchemy i trying following storing title link two separate tables temp submissionstitleu facebook homepage linku httpfacebookcom sessionaddtemp sessionflush transactioncommit via class linksbase tablename links id columninteger primarykeytrue link columntext created columntimestamp defaultdatetimenow def initself link selflink link class submissionsbase tablename submissions id columninteger primarykeytrue created columntimestamp defaultdatetimenow title columntext linkid columninteger foreignkey linksid link relationlinks def initself title link selftitle title selflink link however i always get error attributeerror unicode object attribute sainstancestate what going is better way code
3
have look httpcodeactivestatecomrecipes edit modified use userdefined password arbitrary length requires pycrypto thrown together minutes without test sight edit updated version httpsgistgithubcom
i want encrypt arbitrarylength string password python i would prefer deal padding key generation ivs i honestly know much cryptography yet i like avoid messing i also prefer using wellknown cypher aes my ideal library let call magiccrypt would work like magiccrypt import aes p plaintext k password crypt aesk c cryptencryptp p cryptdecryptc true i checked pycrypto mcrypto pycryptopp gpgme keyczar neither seem offer really easy use mode keyczar comes closest reason wants use keyset saved filelike object something similar as far i know i resort calling mcrypt popen offer mode works exactly like part reason i guessing really technical reason exist do know easy use secure crypto library python if easiest yet secure way using already mentioned libraries
2
yup need add code comment the problem oslistdir returning base file names rename called expects find files whatever directory python thinks by adding ospathjoin build fully qualified path file rename work correctly in comments op stated files got moved folder lead believe rename needed fully qualified path second argument also learned files renamed footxt instead become txt etc preserving file extension this code import os sys path inputinput path dirs oslistdirpath rangelendirs capture fully qualified path original file originalfile ospathjoinpath dirsi build new file name number file extension file name code goes boom newfile ospathjoinpath stri originalfilesplit print renaming formatoriginalfile newfile osrenameoriginalfile newfile verified python showing relevant bits command line you see empty files bartxt footxt renamed path inputinput path input pathusersbfellowsso dirs oslistdirpath dirs bartxt footxt rangelendirs osrenameospathjoinpath dirsi stri stopped python helcaraxeso bfellows ls al total drwxrxrx bfellows bfellows sep drwxrxrx bfellows bfellows sep rwrr bfellows bfellows sep rwrr bfellows bfellows sep helcaraxeso bfellows python v python
code meant ask directory list al files directory rename position list problem i always get error file found print list apperently find files list blank import os sys path inputinput path dirs oslistdirpath rangelendirs osrenamedirsi stri given input files i want rename base file name number preserving file extension thus input atxt testtxt testtxt output txt txt txt
2
djangodb import models djangocontribauthmodels import user class topicmodelsmodel user modelsforeignkeyuser authuser would worked it python library syntax django orm appmodel syntax but pass model string desperately trying solve circular dependency and circular dependency code eff
consider following django model djangodb import models djangocontrib import auth class topicmodelsmodel user modelsforeignkey authmodelsuser name modelscharfieldmaxlength namemaxlength unique true versionnumber modelsintegerfielddefault createdat modelsdatetimefieldautonowadd true modifiedat modelsdatetimefieldautonow true updatefrequency modelsintegerfield this model validate even installing authuser table in authmodelsuserobjectsall out user admin the statement djangoadmin shell python managepy syncdb error one models validate topic user relation model authmodelsuser either installed abstract i using django v pinax ubuntu sqlite database the following questions help much foreign key user table django how i create foreign key user table django
3
list mcrypto see msecret example httpwwwheikkitoivonennetmsecret seems pretty much exactly want disclaimer used listed pypi alpha quality httppypipythonorgpypimsecret update time answering wrote simplecrypt simple wrapper pycrypto aes encryption python similar rob answer also includes pbkdf generate secure key
i want encrypt arbitrarylength string password python i would prefer deal padding key generation ivs i honestly know much cryptography yet i like avoid messing i also prefer using wellknown cypher aes my ideal library let call magiccrypt would work like magiccrypt import aes p plaintext k password crypt aesk c cryptencryptp p cryptdecryptc true i checked pycrypto mcrypto pycryptopp gpgme keyczar neither seem offer really easy use mode keyczar comes closest reason wants use keyset saved filelike object something similar as far i know i resort calling mcrypt popen offer mode works exactly like part reason i guessing really technical reason exist do know easy use secure crypto library python if easiest yet secure way using already mentioned libraries
3
center keyword argument positional argument you use positional arguments south understand see custom fields keyword arguments you could solve providing center default value centernone would fine following example code link defining keyword name passed init name stored database dictionary options may blank setting default value helps
i using custom django model field widget render googlemap widget admin also want use south project handle database migrations however much effort unable generate custom south rule fits custom model last many instrospection rules tried class googlemapmarkerfieldmodelscharfield metaclass modelssubfieldbase description un marcador de google maps widget googlemapmarkerwidget def initself center args kwargs kwargs maxlength kwargs helptext arrastre el cursor en el mapa para seleccionar el punto selfcenter center supergooglemapmarkerfield selfinitargs kwargs def formfieldself kwargs defaults center selfcenter formclass googlemapmarkerformfield defaultsupdatekwargs return supergooglemapmarkerfield selfformfielddefaults def topythonself value isinstancevalue googlemapmarker return value isinstancevalue list return googlemapmarkermapfloat value elif isinstancevalue basestring try return googlemapmarkermapfloat valuesplit except valueerror pass def getprepvalueself value return ff valuelatitude valuelongitude addintrospectionrules googlemapmarkerfield center center websitefieldsgooglemapmarkerfield and traceback getting traceback recent call last file managepy line module executemanagersettings file homearmongeworkspaceenvlibpythonsitepackagesdjangocoremanagementinitpy line executemanager utilityexecute file homearmongeworkspaceenvlibpythonsitepackagesdjangocoremanagementinitpy line execute selffetchcommandsubcommandrunfromargvselfargv file homearmongeworkspaceenvlibpythonsitepackagesdjangocoremanagementbasepy line runfromargv selfexecuteargs optionsdict file homearmongeworkspaceenvlibpythonsitepackagesdjangocoremanagementbasepy line execute output selfhandleargs options file homearmongeworkspaceenvlibpythonsitepackagessouthmanagementcommandsschemamigrationpy line handle oldorm lastmigrationorm file homearmongeworkspaceenvlibpythonsitepackagessouthutilspy line method value functionself file homearmongeworkspaceenvlibpythonsitepackagessouthmigrationbasepy line orm return fakeormselfmigrationclass selfapplabel file homearmongeworkspaceenvlibpythonsitepackagessouthormpy line fakeorm ormcacheargs fakeormargs file homearmongeworkspaceenvlibpythonsitepackagessouthormpy line init selfmodelsname selfmakemodelapplabel modelname data file homearmongeworkspaceenvlibpythonsitepackagessouthormpy line makemodel field selfevalincontextcode app extraimports file homearmongeworkspaceenvlibpythonsitepackagessouthormpy line evalincontext return evalcode globals fakelocals file string line module typeerror init takes least arguments given
1
the what new document one place introduced these views introduced proposed python backported seen serve bestofallworlds pieces dict refer before keys values items methods simply made lists this wastes memory copying dict information iterkeys itervalues iteritems methods waste memory featureful thing could iterate could these new views logical features set operations efficient comparison iterable multiple times
i came across three types i used collectionscounter viewkeysviewitems viewvalues method the value three methods returned type dictkeys dictitems dictvalues they iterable i noticed but question three types exist or usage
3
here suggestion create two version script dump everything one in proper thing laying code separate files smart filenames now run first command time python mygameallinonepy the dollar sign represents command line prompt and run second time python mygamepy the time command tell much time game actually took run real time much cpu time took run commands say ten times take average time this called profiling help decide approach best even makes difference
sorry question incredibly easy answer i sound like idiot i wondering i would execute script one file pygame event loop blits etc switch another file selectworldpy event loop blits etc if i call main function create slowdown i still original file open i fine selectworldtransition sort thing thanks advance
1
the read method returns file contents chunks you call returns empty string httpdocspythonorgtutorialinputoutputhtmlmethodsoffileobjects
i tried different ways result always seems i get python read end file it stops halfway i tried binary ascii modes result i also checked special characters file cuts none additionally i tried specifying much read still cuts place it goes something like fopenarchivesarchivelog r logtextfread print logtext it happens whether i call bash python whether i normal user root however works fine file directory i fopenarchivelog r logtextfread print logtext this works like dream any idea
1
what asking essentially define good players easy problem as mentioned simple average score pickingthehighestscore ideal answer depending game design i like recommend read elo rating system chess modified versions design player rating system one simple possible way set window like recent games use average score window players play less games window would placement state again easy problem heavily depends game good luck update i assumed game player vs player if another story most games keep highest score matter many times play game going entry leaderboard since say anything game i idea fair as i mentioned earlier could set window avg score highest score you even reset leaderboard every month remove players played week it depends game want please remember matter make sure rules crystal clear players otherwise would easily upset frustrated
i need create functionmethod python calculates high score leaderboard each player played number rounds game recieving score round i want know best way sort top ranking players accounting score and number rounds played the possible scores round f d d d c c c b b b a a obviously simple average work take account number rounds played whats best way set fair sorting function edit i reading really great answers i want try clear question bit i want players score and number rounds played count towards ranking way fair meaning player b higher rank player a basically high score reflect general effort skill number rounds played plus score means higher ranking edit after reading answers i think best way simple total sum players points across rounds i sure answer assign green check correct
1
there many ways could try example let fa make however try take difficulty account score one higher previous for every game play receive score create total score add game score every time total score that way person receives a person receives a gets score simply sort accordingly each function drawbacks course this function best consider getting b would exceed a even though a much better score give details want rank much easier get algorithm
i need create functionmethod python calculates high score leaderboard each player played number rounds game recieving score round i want know best way sort top ranking players accounting score and number rounds played the possible scores round f d d d c c c b b b a a obviously simple average work take account number rounds played whats best way set fair sorting function edit i reading really great answers i want try clear question bit i want players score and number rounds played count towards ranking way fair meaning player b higher rank player a basically high score reflect general effort skill number rounds played plus score means higher ranking edit after reading answers i think best way simple total sum players points across rounds i sure answer assign green check correct
1
if you’re trying match ipv address use regex import text regex researchregex textgroup refindallregex text
how prevent parital matches using research using dictionary key pattern python for question i would like avoid iterating nested list dictionary value i tried appending regular expressions search pattern results error partial match server e match researche server match print matchgroup
1
i want database get big unwieldy database scaling big topic still fits realm optimization summed three simple rules don don experts only profile first what means question probably optimizing size data good idea how much data really what queries execute regularly data queries slow what database natively help what might seem first blush lot data often nothing worry a good rule thumb dataset fits memory big dataset even big dataset often case small part relevant non completed rows really affect queries you make work well creating right combination indexes database easily find operate rows actually query and might using database wrong thing what describing data comes hangs around gets processed gets archived sounds suspiciously similar queue persistent distributed queues widely available have look celery python framework built queuing may better fit problem trying solve
i relatively new sqlalchemy done basic database creation insert update delete i found quite simple use far my question i want move records one database another backup database what simplest way sqlalchemy
1
yes works the exact implementation depends webserver case nginx recommended mark location internal prevent external access nginx asynchronously serve files django need one thread per request get problematic higher numbers parallel requests remember send xaccelredirect header nginx instead xsendfile see httpwikinginxorgxsendfile information
i research regarding file downloads access control using django my goal completely block access file except accessed specific user i read using django xsendfile one methods choice achieving based so questions etc my rudimentary understanding using xsendfile django user requests uri get protected file django app decides file return based url checks user permission etc django app returns http response xsendfile header set server file path the web server finds file returns requester i assume webs server also strips xsendfile header along way compared chucking file directly django xsendfile seems likely efficient method achieving protected downloads since i rely nginx serve files vs django leaves questions is explanation xsendfile least abstractly correct is really secure assuming i provide normal frontend http access eg httpwwwexamplecomdownloadssecretfilejpg directory file stored ie keep publichtml directory or could techsavvy user examine headers etc reverse engineer way access file distribute is really big difference performance am i going bog application server providing b chunked downloads mb files directly django sortof nonissue the reason i ask versions near equal django version would preferable due ability things python like log number completed downloads tally bandwidth downloads etc thanks advance
3
i never use appengine i guess requestcookies normal dictionary object like example django you try following userid selfrequestcookies cookie exists
in code i using userid selfrequestcookiesget userid userid usergetbyid int userid look right even though technically worksit looks imprecise is better way i check existence cookie
1
try except clauses handy situations like need clear obvious workflow hair trigger invalidate everything catch to clear approach various nuances involved securely trackingmanaging user session leaving data client try userid selfrequestcookies userid raise keyerror exception set isinstanceuserid basestring assert userid raise valueerror exception userid try userid intuserid except valueerror loggingwarnu userid value cookie type could u coerced integer value typeuserid userid isinstanceuserid int raise assertionerroru userid value cookie invalid u typevalue ss typeuserid userid except keyerror userid key exist cookie object loggingdebug no userid value cookie except assertionerror the cookie value invalid clearthecookieandstartagainprobably except exception e something else went wrong loggingerroru an exception count exception e clearthecookieandstartagainprobably raise e else usergetbyiduserid
in code i using userid selfrequestcookiesget userid userid usergetbyid int userid look right even though technically worksit looks imprecise is better way i check existence cookie
1
um problem exactly tried port test port since blocked isp google mx server listening port if isp allow outgoing connections port able send smtp messages way trying you get sorted isp regarding rejection messages sending email directly like increase likelihood rejected flagged spam particularly set address something match domain associated ip address smtp client sends mismatched domain ehlo message content message looks spammy the actual behavior vary according individual mx server configured
i tried playing around python learn smtp protocol more precisely i trying send mail straight host smtp server little success for example say i want send mail gmailcom address i lookup mx record gmailcom nslookup typemx gmailcom gmailcom mx preference mail exchanger altgmailsmtpinlgooglecom gmailcom mx preference mail exchanger gmailsmtpinlgooglecom gmailcom mx preference mail exchanger altgmailsmtpinlgooglecom then i following python import smtplib tried port test port since blocked isp smtplibsmtpaltgmailsmtpinlgooglecom i tried several everyone one i always got errno a socket operation attempted unreachable network errno a connection attempt failed connected party properly respond period time established connection failed conneted host failed respond exception i read somewhere mail servers reverse lookup ip rejecting connection got domain how i also read somewhere many mail servers reject incoming mails dynamic ip addresses i obviously private customer isp how check ip address dynamic static are reasons servers seem reject connection or something
2
test logic tests never part production production mean use released client etc code so bad idea anywhere within script ideally separate files
when write scripts self sufficient bad idea use name main place write tests
3
serializing really generalized possible sqlalchemy mapped classes classes might properties stored database must inferred across multiple levels indirection relationship properties in short know serialize particular class particular use lets pretend need care column values specific instance specific class consideration res here crude function return dict containing values sqlalchemyormattributes import managerofclass sqlalchemyormproperties import columnproperty def getstatedictinstance cls typeinstance mgr managerofclasscls return dictkey getattrinstance key key attr mgriteritems isinstanceattrproperty columnproperty recreate instance dict def createfromstatedictcls statedict mgr managerofclasscls instance mgrnewinstance key value statedictiteritems setattrinstance key value return instance if need something complex probably handling relationships shown columns manytomany relationships probably add case looking sqlalchemyormpropertiesrelationshipproperty iterating collection serializing intermediate dict class left exercise
ok i bit problem i need able create sort importexport functionality sqlalchemy now objects i defining get columns i attr value resclassdictiteritems isinstancevalue instrumentedattribute data evalres strattr paramdictattr data now correctly gets attributes object however i cant certain parameters init since i one handling objects so could situation like class someclassmodelbase mycolumn columnstring stuff def initself mycolumn selfmycolumn mycolumn so case i correspondance name field name parameter recieved init i currently contraining ones define classes init parametes default value i could obj someclass exec obj attr paramattr however i would like get away even constrain is way i achieve
2
most unices already usrbinpython overwriting one bad idea python version used packages system changing one may break when installing python package executable installed usrbinpython i would claim archlinux broken better use want run python archlinux bit special since use usrbinpython python despite default executable name python usrbinpython this confusing seen bug mean use symlink python archlinux script uses python almost certainly break so unices symlinking usrbinpython python bad idea archlinux terrible idea instead install version need call usrbinpythonxx
so i read httpswikiarchlinuxorgindexphppython and clear wiki i install python via pacman s python is reasonable create symlink python ln python usrbinpython i forsee switching python time soon or better way managing multiple python versions like i usually use debian system updatealternatives config python mac os x system python select clarification what i trying find best practice managing various python versions archlinux system i new archlinux familiar ubuntu debian mac os x
2
best practice put tests separate units use unittest module this separation allows keep main code clean need lots testing helper functions encourages write good comprehensive tests since inhibited cluttering main code
when write scripts self sufficient bad idea use name main place write tests
2
it really depends code purposes script for big complex projects sure put tests separate place but working something small might good solution tests along code main idea doctest great python module allows write tests docstrings in case name main look like name main import doctest doctesttestmod i find nice clean
when write scripts self sufficient bad idea use name main place write tests
3
the python reference manual read says also note nonblocking mode less data requested may returned even size parameter given there also draft pep matter apparently accepted a pep python enhancement proposal so sad state affairs cannot rely read give full file one call if file text file i suggest use readlines instead it give list containing every line file as far i tell readlines reliable
i tried different ways result always seems i get python read end file it stops halfway i tried binary ascii modes result i also checked special characters file cuts none additionally i tried specifying much read still cuts place it goes something like fopenarchivesarchivelog r logtextfread print logtext it happens whether i call bash python whether i normal user root however works fine file directory i fopenarchivelog r logtextfread print logtext this works like dream any idea
2
your pyhelloworldglade incorrect make sure created correct glade application glade glade applications installed used if downloaded file make sure correct the error message says expected gladeinterface got interface so xml file interface tag pygtk library expects gladeinterface tag
i made gui glade i want put python program i adapting instructions tutorial i found online load glade file httpwwwpygtkorgarticlespygtkgladeguicreatingaguiusingpygtkandgladehtm when i problems i tried something basic one button calling thing tutorial copy pasting code still work i also took look httpwwwlinuxjournalcomarticlepage function called slightly differently selfwtreegtkgladexml gladefilewindowname instead without windowname implemented equivalent mine fix i definitely pygtk working i made something without using glade worked fine the error i getting usrsharethemesnoxgtkgtkrc murrine configuration option gradients longer supported ignored helloworldpy libgladewarning expected gladeinterface got interface helloworldpy libgladewarning finish parserfinish state traceback recent call last file helloworldpy line module hwg hellowworldgtk file helloworldpy line init selfwtree gtkgladexmlselfgladefile runtimeerror could create gladexml object i running xubuntu the murrine configuration thing comes gtk application opens i included case relevant here code i took tutorial working usrbinenv python import sys try import pygtk pygtkrequire except pass try import gtk import gtkglade except sysexit class hellowworldgtk this hello world gtk application def initself set glade file selfgladefile pyhelloworldglade selfwtree gtkgladexmlselfgladefile get main window connect destroy event selfwindow selfwtreegetwidgetmainwindow selfwindowshow selfwindow selfwindowconnectdestroy gtkmainquit name main hwg hellowworldgtk gtkmain
2
i know really understand but simply need return first ajax call key entity calculation question when user makes response firstly get entity key update property answer step the ajax call return question json example to fetch empty answered question qry calculationallfilter answer none ref qryget the json response key unicoderefkey question refquestion step you update entity key key answer variable http get post request ref dbgetkey refanswer answer refput
i calculation entity datastore say million objects entity it following properties python runtime class calculationdbmodel question dbstringpropertyrequiredtrue answer dbstringproperty suppose examples question property things like really important all calculation objects start empty answer properties when user connects app ajax call made app supposed fetch calculation object empty answer property send user browser the user browser evaluates question sends back different server handler how i update specific calculation object answer property if someone could provide code would great not really experienced app engine query stuff confusing what best solution i want conserve much servercpu possible thanks
1
javascript files works uimodules javascript files included way appended page end body tag though head tag if really want file included head tag simply output value params corescripts head tag template raw params corescripts
in following code snippet i trying add javascript files tornado server html file head tag debugscripts script srcsrcmainjs typetextjavascriptscript class entriestornadowebuimodule def javascriptfilesself return srcmainjs class mainhandlertornadowebrequesthandler def getself params params corescripts debugscripts path ospathjoinospathdirnamefile indexhtml selfrenderpath paramsparams params corescripts debugscripts i trying add script tag html gets parsed text generates ampltscript typeampquottextjavascriptampquot srcampquotsrcmainjsampquotampgtampltscriptampgt so i came across javascriptfiles method tornado specs i getting examples implementations can anyone help
2
you find solution docs if need create relationship model yet defined use name model rather model object class carmodelsmodel manufacturer modelsforeignkey manufacturer class manufacturermodelsmodel
i defined two models one references like class usermodelsmodel loves modelsmanytomanyfieldarticle relatedname lovedby class articlemodelsmodel author modelsforeignkeyuser you see problem classes references no matter order two classes implemented python always raises nameerror exception complaining either one class defined
3
try usung serialiser optional fields argument serializeditems serializersserializejson itemlist fields auxinfo may also suggest using init method add fields considdered bad form django would much better achieved like class mymodelmodelsmodel title modelscharfield description modelstextfield def auxinfoself return i database
i wrote init method one models adds auxiliary information object dynamically adding attribute object reflect column database class mymodelmodelsmodel title modelscharfield description modelstextfield def initself args kwargs selfauxinfo i database this seemed working fine i found case work i code view i set status variable package list mymodels json like djangocore import serializers djangoutils import simplejson use serializers django models serializeditems serializersserializejson itemlist dataitems serializeditems serializeditems string datastatus status package data dict using simplejson python objects resp simplejsondumpsdata return httpresponseresp mimetypeapplicationjavascript the problem seems django serializers serialize model fields attributes object auxinfo come i also pretty sure using serializers simplejson right way thanks help
1
httpsgithubcomkevinwpyflakesvimissues you recommend users clone pyflakesvim repo git clone recursive suggest fact use git submodule update init recursive pyflakesvim saved git submodule or go pyflakesvim git submodule init ampamp git submodule update the point pyflakesvim needs fresh local copy pyflakes ftpluginpluginpyflakes systemwide installed version old
i playing pyflakes plugin vim i open python file i get error messages screenshot any ideas fix thanks advance
1
have trying appstats help httpcodegooglecomappenginedocspythontoolsappstatshtml with software profiling api call
the new pricing model resources datastore reads datastore writes but i could find detailed information exactly measured hard optimize datastore utilization i profile any clues httpcodegooglecomappenginearticlesmanagingresourceshtml doesnt give details
2
from documentationfilesystemsproctxt these numbers identify amount time cpu spent performing different kinds work time units userhz typically hundredths second so figure utilization terms percentages need find userhz machine find long since system booted the second one easy btime line file use for userhz check how get number mili seconds per jiffy
procstat shows ticks user nice sys idle iowait irq sirq like cpu how i calculate individual utilizations user nice etc values like values shows top vmstat
2
you confused logical for example key image check following image image image link false true true instead want key image key link easier read key image link
i dictionary item it strings keys values lists eg item title u python item image u linktoimage item link u link article i want check value length link image may empty i following key value itemiteritems lenvalue key image key link raise dropitemitem empty item return item so item dropped value image key my problem condition work the item still dropped image link empty any idea whats wrong i new python
3
you key image key link key image key link always true
i dictionary item it strings keys values lists eg item title u python item image u linktoimage item link u link article i want check value length link image may empty i following key value itemiteritems lenvalue key image key link raise dropitemitem empty item return item so item dropped value image key my problem condition work the item still dropped image link empty any idea whats wrong i new python
2
if doubt implement magic methods the defaults reason fine in case completely unnecessary implement hash would implement implement eq well unless expect someone set dictionary methods str useful in case result include the class name avoid confusion anything else whether function alive if alive str result identify function say name
i class called weakboundmethod source codereviewse i like guidelines i implement hash also python automatically provides repr function i guess i bother redefining what str i understand human readable text representation object i define well guidelines about hashing function i like generate hash based self func bound method wrapping how i
1
i ended custom xml stripping like xmlstart htmldatafind xml xmlend htmldatarfind mytag xmlstart loguseractionreqgethost chunked data htmldata htmldata htmldataxmlstart xmlend lenhtmldatalen mytag htmldata htmldataxmlend can find simple solution
i following code open read urls htmldata urlliburlopenreqread i believe standard way read data http however response chunked tranferencoding response starts following characters ebrnrn xml version encodingutf this happens due mentioned chunked encoding thus xml data becomes corrupted so i wonder i get rid metadata related chunked encoding
1
this code calculates user utilization spread cores import os import time import multiprocessing def main jiffy ossysconfossysconfnames scclktck numcpu multiprocessingcpucount statfd open procstat statbuf statfdreadlinessplit user nice sys idle iowait irq sirq floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf statfdclose timesleep statfd open procstat statbuf statfdreadlinessplit usern nicen sysn idlen iowaitn irqn sirqn floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf floatstatbuf statfdclose print usern user jiffy numcpu name main main
procstat shows ticks user nice sys idle iowait irq sirq like cpu how i calculate individual utilizations user nice etc values like values shows top vmstat
3
ok gonna write notepad first i press enter early i solved problem i really sure why solution solves problem as turns reason one able read one cut early created python script whereas created earlier even though i closed file file appear fully written disk or i grabbing buffer something like by del f and trying grab file i got whole file and yes i use fclose writing file so problem solved anyone give reason i garbage collect manually instance i think i python
i tried different ways result always seems i get python read end file it stops halfway i tried binary ascii modes result i also checked special characters file cuts none additionally i tried specifying much read still cuts place it goes something like fopenarchivesarchivelog r logtextfread print logtext it happens whether i call bash python whether i normal user root however works fine file directory i fopenarchivelog r logtextfread print logtext this works like dream any idea
1
yes using mvc facilities way go even though using qtreewidget still working class derived qabstractitemview therefore model setmodel calls available take model one widgets creating set widgets whenever change data one widgets widgets follow suit using instance model if need maintain selection state widgets parts tree open close might little bit harder might actually work using selectionmodel selectionmodel setselectionmodel
i new python pyqt what best way keep qttreewidgets synchronized items well attributes items these widgets appear different dialog boxes different times session for number reasons i need keep much existing code signals layout intact possible the modelview division would obvious first place go i want touch methods used access update tree i planning refactor whole thing months i need something quickly carry since qtreewidget convenience class data the ui maintained qt designer i want keep way when dialog initialized tree appears the application singleton class dialogs use reference variablesattributes in initialization parent dialog i check see locationtree attribute exists singleton if i would need populate initial state tree dialog use copy any time state dialog tree altered ways i trap i like update singleton locationtree mirror change although clone method qtreewidgetitem i see corresponding method entire qtreewidget how i accomplish least amount change existing code base gui layout john
2
save selfshop getqueryset first method called see code baselistview get method so one solution would get variable code also save selfshop baselistview selfobjectlist def getquerysetself selfshop shopobjectsgetnameselfkwargs shopname offer selfshopgetoffersmodel return offerobjectsall then methods use selfshop def gettemplatenamesself return shopsofferlist selfshopgettype
my url keyword shopname variable there also shop model name field in listview class i need make repeating queries shop model get unicode variable shopgettype method depending result proper template directory selected queryset using subclassed django models here code class offerlistlistview def gettemplatenamesself shop shopobjectsgetnameselfkwargs shopname return shopsofferlist shopgettype def getquerysetself shop shopobjectsgetnameselfkwargs shopname offer shopgetoffersmodel return offerobjectsall def getcontextdataself kwargs getting shop instance shop shopobjectsgetnameselfkwargs shopname context superofferlist selfgetcontextdatakwargs context shop shop return context question best way i get var shop case available methods i python guru may basic problem i tried init overriding i get exchangename specified urlspy get right shop instance i would like avoid repeating thanks
1
numpy scipy contain routines let fit expressions data points expression plot range time like answer nonlinear ex regression using scipy python numpy contains example nonlinear regression exponential like question one negative exponent general fitting extrapolating exponentials positive exponents bad idea extrapolation sensitive noise uncertainty quickly becomes meaningless
i need able extrapolate using n data points curved trend line queried in head would look bit like blue line this calories calculator i data points regarding amount calories burned activity based certain weight eg kg burn around calories kg burn calories kg burn calories etc etc one axis would calories weight obviously i wanted find amount calories burned weight i data point i would need trend line query brings second part question would i go in summary how i extrapolate trend line python how i query trend line get estimates based point trend line
2
yes use python threading module cooperative microthreading module like gevent note python threading mechanism carries disclaimer cpython default python implementation boxes due global interpreter lock cpython one thread execute python code even though certain performanceoriented libraries might overcome limitation if want application make better use computational resources multicore machines advised use multiprocessing however threading still appropriate model want run multiple iobound tasks simultaneously depending underlying modules calling operate may find using threading one thread give control often in case using cooperative microthreading might option
i trying run method infinite loop create video display this method called within another loop handles hardware input cannot loop fast video causing lag i use outer loop run video is way start video loop start hardware loop run separately currently i call video loop sits loop returns
1
you use datetimedatetimestrptime converts string date format datetimedatetime object the format fields eg y denotes fourdigit year specified python documentation import datetime format ymd hmsf datedatetimedatetimestrptimes format date datetimedatetime
i string field like i need convert datetime object python i calculate difference two datetime objects
3
yes use python multiprocessing module note multiprocessing fight gil work simultaneously everything give on hand warning multiprocessing module spawn process completely separate python interpreter so os controlled thread it entirely different process this add overhead programs advantage completely dodging gil makes mild issue
i trying run method infinite loop create video display this method called within another loop handles hardware input cannot loop fast video causing lag i use outer loop run video is way start video loop start hardware loop run separately currently i call video loop sits loop returns
1
just enable developer mode get access shell
i would like use samsung chromebook develop app engine using python unfortunately possible i browser there online ide like codule good enough yet so regards i questions is way hack chrome os pull native linux is way install second os chromebook i new samsung chromebook first one is chrome os extension help programming python app engine
3
if list key value key value turn dict thatdict dictthatlist then unpack setdefaults ie parsersetdefaultthatdict
i trying use argumentparsersetdefaults argparse i want keyworded tuple like parsersetdefaultsbar baz badger i item output configparseritems baz badger how i convert keyworded tuple setdefaults expecting
1
after hours researching exact problem i found solution it nothing pythoncom wincom fact apache running service the solution found httpsocialmsdnmicrosoftcomforumseninnovateonofficethreadbacedbbafef the solution consists simply making one folder giving write permissions relevant apache user bit windows create folder cwindowssyswowconfigsystemprofiledesktop bit windows create folder cwindowssystemconfigsystemprofiledesktop
i problem opening excel document web application running apachemodwsgiwindows server problem application running django developer server one thread my code def myviewrequest import pythoncom wincomclient import dispatchex pythoncomcoinitializeexpythoncomcoinitmultithreaded xl wincomclientdynamicdispatch excelapplication xldisplayalerts false xlvisible doc xlworkbooksopencpathtofilexlsx docsaved true wbclosesavechanges xlquit pythoncomcouninitialize error message exception occurred u microsoft office excel umicrosoft office excel cannot access file cpathto filexlsx there several possible reasons the file name path exist the file used another program the workbook trying save name currently open workbook u cprogram files xmicrosoft officeoffice xlmainchm none i know problem localized somewhere threading i using pythoncomcoinitializeexpythoncomcoinitmultithreaded maybe changing server solve problem libs django apache modwsgi wincom latest i hope somebody help thank you regards
2
i problem have looked sentry codebase found place throws line webviewspy it happens else clause checks header httpauthorization to get passed i add wsgipassauthorization on apache conf i think else clause i mention must bug handled
i get following error sentry client tries logging error unable reach sentry log server http error bad request url httplocalhostsentrystore body missing data traceback recent call last file homedeployenvlibpythonsitepackagessentryclientbasepy line send return selfsendremoteurlurl datamessage headersheaders file homedeployenvlibpythonsitepackagessentryclientbasepy line sendremote response urlliburlopenreq dataread file usrlibpythonurllibpy line urlopen return openeropenurl data timeout file usrlibpythonurllibpy line open response methreq response file usrlibpythonurllibpy line httpresponse http request response code msg hdrs file usrlibpythonurllibpy line error return selfcallchainargs file usrlibpythonurllibpy line callchain result funcargs file usrlibpythonurllibpy line httperrordefault raise httperrorreqgetfullurl code msg hdrs fp httperror http error bad request http the error trying log get saved server thank
1
this valid yaml superset json use pyyaml parse orange apple lemon import yaml yamlloads orange lemon apple more since tab space inside string better remove parsing yaml ssreplace otherwise string cannot parsed
i received output likes orange apple lemon i know standard json format still possible parse python dictionary type is must orange apple lemon must quoted thanks
3
you need typecast cleaneddataget quantity int django topython method form base class all forms try convert values python values part validation process i see anything cleanquantity method would make think work although showing stock class see type field stockquantity my advice would write unit test form view method ensure getting correct values httpsdocsdjangoprojectcomentopicstesting if habit writing unit tests great time start they really save lot time
model modelform django project defined like class consumptionmodelsmodel datemodelsdatetimefielddefaultdatetimenow productnamemodelsforeignkeystocktofield productname quantitymodelsintegerfield customermodelscharfieldmaxlengthnulltrueblanktrue def unicodeself return selfproductname class consumptionformmodelform class meta modelconsumption def cleanquantityself cleaneddataselfcleaneddata productcleaneddatagetproductname quantityintcleaneddataget quantity stockstockobjectsgetproductnameproduct quantity stockquantity raise formsvalidationerrornot enough stock return cleaneddata stock class contains product name serves foreign key consumption whose quantity greater consumption quantity now problem i enter submit consumptionform it gives error quantity field field must integer even i providing integer what reason
1
from i understand virtualenv enables separate library installation paths effectively separate virtual python installations java concept systemwide installed library it always searches classpath libraries loaded since classpath needs defined application application pickandchoose libraries versions wants load if go one level deeper single application somehow needs two different versions library time even classpath trickery it get complicated definitely possible osgi one example supported even tomcat two separate webapplications i seens references security virtualenv description java pretty thorough security system built in server applications often turned easier configure way easily configure exactly java application allowed almost extensions extension libraries used lot even easily loaded arbitrary directories
is anything similar python virtualenv java jvm languages
3
you returning whole cleaneddata dictionary cleanquantity method rather value quantity
model modelform django project defined like class consumptionmodelsmodel datemodelsdatetimefielddefaultdatetimenow productnamemodelsforeignkeystocktofield productname quantitymodelsintegerfield customermodelscharfieldmaxlengthnulltrueblanktrue def unicodeself return selfproductname class consumptionformmodelform class meta modelconsumption def cleanquantityself cleaneddataselfcleaneddata productcleaneddatagetproductname quantityintcleaneddataget quantity stockstockobjectsgetproductnameproduct quantity stockquantity raise formsvalidationerrornot enough stock return cleaneddata stock class contains product name serves foreign key consumption whose quantity greater consumption quantity now problem i enter submit consumptionform it gives error quantity field field must integer even i providing integer what reason
2
i solved problem similarly fabriziom suggested one notable difference since menu item presentation time contain html i want mess around html markup directly present methods so i ended implementing menu definitions python presentation jinja mutual recursion bridging gap different types menu items represented different subclasses class menuitemobject def presentself macromap return macromaptypeselfnameself macromap class textlinkmenuitem def initself url text selfurl selftext url text class sectionmenuitem def initself text items selftext selfitems text items class imagelinkmenuitem the macromap referenced dict mapping type menu item macro implementing represenation it defined jinja macro textlinkl macromap classmenuitem hreflurlescape ltextescape endmacro macro sections macromap div classheadingstextdiv ul classitems item sitems li itempresentmacromap li endfor ul endmacro set defaultmap textlink textlink section section the actual menu definitions cleanly expressed trees menuitem subclasses mainmenu sectionmain menu sectionproduct line textlinkproducts a product section to kick presentation template call top level section present method passing macro map specify present menu eg mainmenupresentdefaultmap as best seen section macro menu items ask children present whose present method call yet another jinja macro recursively having explicitly pass around macro map pretty grants valuable benefit one easily render different representations menu data without touching menu definitions for example macro maps may defined render main website menu variant mobile devices case css suffice xml sitemap even plain text version we actually ended using system website menu sitemap cases
i looking way jinja macro calls different implementations depending type object passed basically standard python method polymorphism right i using ugly workaround similar macro menuitemobj set type objclassname type imagemenuitem imagemenuitemobj elif type foobarmenuitem foobarmenuitemobj else textmenuitemobj endif endmacro in pure python one muck around module environment eg globalsx menuitem pretty works well i tried something similar using jinja context latter seem contain macro definitions what better ways achieve i seeking
1
it means methodattribute returned none tried access nodevalue attribute either algorithm wrong need test none accessing attribute sorry i help i never used library
i using ksoap communicate android app python server containing following files posted i trying retrieve values xml file posted but keep getting attributeerror nonetype object attribute nodevalue can anyone tell wrong code i tried debug error still failed portion xml file macfilterlist map node empty profilelist profile profilenamelabprofilename owneradminowner maplabmap visibletruevisible macfilterlist stringbffdastring stringbffdstring stringbffdstring stringbffdstring macfilterlist profile profilelist soapapipy profilexml refers filename xml file def initself selfprofilefile configprofilexml selfprofile xmlprofiledatastore selfprofileloadxmlfileselfprofilefile def getallprofiledataself selfprofilefile configprofilexml selfprofileloadxmlfileselfprofilefile result selfprofilegetallprofiledata return result profiledatapy class xmlprofiledatastore def getallprofiledataself get node list containing nodes name location profilelist selfxmldocgetelementsbytagname profile numargcheck profiles for location node list profilenode profilelist for child nodes location node compare xy coordinates childnode profilenodechildnodes if child node profile name profilename cmpchildnodenodename profilename numargcheck profiles profiles childnodefirstchilddata childnode childnodenextsibling profiles profiles childnodefirstchildnodevalue childnode childnodenextsibling profiles profiles childnodefirstchildnodevalue childnode childnodenextsibling profiles profiles childnodefirstchildnodevalue childnode childnodenextsibling child childnodechildnodes profiles profiles childfirstchildnodevalue profiles profiles return profiles
1
jumping kelketek answer i remember i read basically python garbage collector runs occasionally guarantees given object collected the flush function httpdocspythonorglibrarystdtypeshtmlfileflush what i gathered flush puts data buffer writing os decide probably one problem were reading file soon writing that could cause race condition httpenwikipediaorgwikiracecondition class generally weird possibly randomhardtoreproduce bugs normally expect highlevel language like python
i tried different ways result always seems i get python read end file it stops halfway i tried binary ascii modes result i also checked special characters file cuts none additionally i tried specifying much read still cuts place it goes something like fopenarchivesarchivelog r logtextfread print logtext it happens whether i call bash python whether i normal user root however works fine file directory i fopenarchivelog r logtextfread print logtext this works like dream any idea
1
i new django attempt in modelspy need override flatpage model provide meta class something like djangocontribflatpagesmodels import flatpage class myflatpageflatpage class meta verbosename static page overridden name this sets name model appear admin you register appear admin myappmodels import myflatpage djangocontribflatpagesmodels import flatpage adminsiteunregisterflatpage adminsiteregistermyflatpage adminmodeladmin you set again someone may able chime better answer i still learning
am pretty new django trying make use flatpage module one site going create i able setup everything admin user create page using flatpage module problem i want change flatpages name thats displayed admin dashboard something sensible end user for example name like manage static pages something like from documents i could understand meta class one need use change label sure use use please help thanks
1
an alternative datetimedatetimestrptime would pythondateutil libray dateutil allow thing without explicit formatting step dateutil import parser dateobj parserparse date datetimedatetime it standard library module handy parsing date time strings especially control format come one caveat install library version python version python easyinstall pip default installing version explicitly indicate pythondateutil using python
i string field like i need convert datetime object python i calculate difference two datetime objects
2
from department dirty hacks this process solved problem hardly elegant remove migrations affected app rm mainappmigrations remove modelspy replace empty file mv mainappmodelspy rm mainapppyc touch mainappmodelspy generate initial migration nothing python managepy schemamigration mainapp initial apply python managepy migrate mainapp restore ones models generate migration recreate everything rm mainappmodelspy mv modelspy mainapp python managepy schemamigration mainapp auto before running new migration edit comment changes really new changes alternatively run fail tables actually exist comment everything apply migration put south something like normal state perform changes followed recommended course step python managepy migrate mainapp better cleaner suggestions welcome indications else approach might break
i using south generate apply migrations rather managing unfortunately south refusing actually anything transcript graffiastestingtustincommercialcomoneclickcos python managepy schemamigration mainapp auto you cannot use auto app migrations try initial graffiastestingtustincommercialcomoneclickcos python managepy schemamigration mainapp initial added model mainappcompanyuk added model mainappcompanyname added model mainappindividual added model mainappdirector added model mainappdirectorsindividual added model mainappdirectorscorporate added model mainappsharecapitalclass added model mainappmember added model mainappmembersindividual added model mainappmembergeneric added model mainappcompanymanager added model mainapppendingregistration added model mainapppendingauthorisation created initialpy you apply migration managepy migrate mainapp graffiastestingtustincommercialcomoneclickcos python managepy migrate mainapp running migrations mainapp nothing migrate loading initial data mainapp no fixtures found graffiastestingtustincommercialcomoneclickcos as see south thinks nothing however last three models completely new table database is anything i short zapping database get south working i intention manually writing migrations rest project would help i would write one migration
1
the downloadcache option want pip install downloadcachepthtodownloadedfiles package however i tested main package downloaded saved installed ok dependencies saved full url path name bit annoying targz files the download option downloads main package dependencies install note prior version download option download dependencies pip install package downloadpthtodownloadedfiles the pip documentation outlines using download fast amp local installs
if i want use pip command download package dependencies keep zipped files get downloaded say djangosocialregistrationtargz way i tried various commandline options always seems unpack delete zipfile gets zipfile original package dependencies
3
something may almost exactly want twistedinternettestreactormixinsreactorbuilder you see used testtcp example
i one python module defines set base classes another python module implements the core python module also test cases test base classes correctly implemented in second module test suite i would like automatically generate testcase subclasses first module adding mixin necessary setup specific implementation i see lots answers parametrizing test cases case i want reuse common classes subclass it ok needs code parent test module instantiate long names tests differently runs automatically if matters code using twisted trial standard unittest
2
this referred database migration sqlalchemy support migration box you look using sqlalchemymigrate help kinds situations alter table chosen database command line utility
i made table using sqlalchemy forgot add column i basically want usersaddcolumn userid foreignkey usersuserid what syntax i find docs
3
just general remark i familiar python i would suggest make sure easily exchange slow parts reference implementation optimized parts eg use something like strategy pattern this allow crossvalidate results sophisticated algorithms ensure mess results keep overall structure simulation algorithm clear separation concerns you place optimized algorithms separate source files folders packages document separately much detail necessary apart try avoid usual traps premature optimization check actually worth eg profiler reinvent wheel look available libraries
i writing scientific program python c complex physical simulation algorithms after implementing algorithm i found lot possible optimizations improve performance common ones precalculating values getting calculations cycle replacing simple matrix algorithms complex but arises problem unoptimized algorithm much slower logic connection theory look much clearer readable also harder extend modify optimized algorithm so question techniques i use keep readability improving performance now i trying keep fast clear branches develop parallel maybe better methods
3
yours good question arises almost every piece code however simple complex written programmer wants call pro i try remember keep mind reader newly come code pretty much crude view problem straightforward maybe brute force approach i originally then i get deeper understanding problem paths solution become clearer i try write comments reflect better understanding i sometimes succeed comments help readers especially help i come back code six weeks later my style write plenty comments anyway i sudden insight gets excited i want see run brain fried i almost always greatly regret later it would great i could maintain two parallel code streams naã¯ve way sophisticated optimized way but i never succeeded to bottom line i write clear complete succinct accurate uptodate comments best i just one thing know already optimization usually mean shoehorning ton code onto one source line perhaps calling function whose argument another function whose argument another function whose argument yet another function i know avoid storing function value temporarily but little usually nothing speed code bitch follow no news i know
i writing scientific program python c complex physical simulation algorithms after implementing algorithm i found lot possible optimizations improve performance common ones precalculating values getting calculations cycle replacing simple matrix algorithms complex but arises problem unoptimized algorithm much slower logic connection theory look much clearer readable also harder extend modify optimized algorithm so question techniques i use keep readability improving performance now i trying keep fast clear branches develop parallel maybe better methods
2
listsort sorts list place ie return new list just write newlistsort return newlist
purpose accept file name print unique words alphabetically problem the file runs i able verify finduniquewords result sorted list however return list main method i seem find any ideas thanks lee def finduniquewordsthelist newlist words read line time item thelist remove punctuation line cleaned cleanupitem split line separate words words cleanedsplit evaluate word word words count unique word word newlist newlistappendword answer newlistsort return answer def cleanupphrase item strphrasereplace item stritemreplace item stritemreplace item stritemreplace item stritemreplacen return item def main filename rawinputenter filename list openfilename r finallist finduniquewordslist print finallist main
3
the problem answer newlistsort sort return sorted list rather sorts list place use answer sortednewlist
purpose accept file name print unique words alphabetically problem the file runs i able verify finduniquewords result sorted list however return list main method i seem find any ideas thanks lee def finduniquewordsthelist newlist words read line time item thelist remove punctuation line cleaned cleanupitem split line separate words words cleanedsplit evaluate word word words count unique word word newlist newlistappendword answer newlistsort return answer def cleanupphrase item strphrasereplace item stritemreplace item stritemreplace item stritemreplace item stritemreplacen return item def main filename rawinputenter filename list openfilename r finallist finduniquewordslist print finallist main
3
favourite rawinput joinanimals this take strings list animals join together end lion tiger fish want add question mark space end favourite rawinput joinanimals also line favourite lion your quotes match make sure use either double single quotes one you also need use compare two things assigning value comparing i would probably like animalstring joinanimals favourite rawinputwhich animals favouriten formatanimalstring which first makes animal string formats choices question new line n puts
hi i starting learn python i using book learn python hard way one exercises build simple game i wanted give options user list for example i would make list called animals would include animals lion tiger fish possible offer selected elements list i pretty sure i know i thinking something like obviously wrong i think helps understand i mean animals lion tiger fish print animals favourite favourite rawinputanimals animals favourite lion print nice choice else print bad choice again i stress enough i know really crap essentially i want offer certain items list option rawinput in case item item thanks advance help
2
how favourite rawinputwhich animals favourite joinstrab ab enumerateanimals fav animalsintfavourite print fav nice choice indeed the big bear kill anyway good bye
hi i starting learn python i using book learn python hard way one exercises build simple game i wanted give options user list for example i would make list called animals would include animals lion tiger fish possible offer selected elements list i pretty sure i know i thinking something like obviously wrong i think helps understand i mean animals lion tiger fish print animals favourite favourite rawinputanimals animals favourite lion print nice choice else print bad choice again i stress enough i know really crap essentially i want offer certain items list option rawinput in case item item thanks advance help
1
when binding tkinter automatically adds argument information event you need account either randfunc definition call here one solution import tkinter tk class sampleapptktk def initself args kwargs tktkinitself args kwargs selfframe tkframeself selfframepack selfbutton tkbuttonselfframe textclick commandlambda b c selfrandfunca b c selfbuttonpack selfframebindreturn lambda event b c selfrandfunca b c make sure frame focus binding work selfframefocusset def randfuncself b c print self self b b c c print abc app sampleapp appmainloop that said rare binding frame right thing typically frame keyboard focus unless focus binding never fire if setting global binding either bind binding tag using bindall method toplevel widget
i tkinter frame button attached tkinter import def randfuncabceffects print abc roottk frameframeroot framebindreturnlambda b c randfuncabc framepack buttonbuttonframe textclick commandlambda abceffnonerandfuncabc buttonpack rootmainloop i want function done user presses enter presses button sadly code gives error frame binding does anyone know solution problem
3
i guess got trouble starting managepy converttosouth mainapp maybe correct make south believe perform first migration go zero managepy migrate fake mainapp zero migrate real first migration managepy migrate mainapp but i make question already models database made without south otherwise use initial if probably complain columns already existing you change situation wiping first schemamigration deleting mainappmigrationsinitialpy you need fiddle south database table directly deleteghostmigrations take care managepy syncdb south expects database sync models managepy converttosouth mainapp actually let south handle database migrations managepy migrate deleteghostmigrations mainapp move first migration deleting old first migration deleted migrations database
i using south generate apply migrations rather managing unfortunately south refusing actually anything transcript graffiastestingtustincommercialcomoneclickcos python managepy schemamigration mainapp auto you cannot use auto app migrations try initial graffiastestingtustincommercialcomoneclickcos python managepy schemamigration mainapp initial added model mainappcompanyuk added model mainappcompanyname added model mainappindividual added model mainappdirector added model mainappdirectorsindividual added model mainappdirectorscorporate added model mainappsharecapitalclass added model mainappmember added model mainappmembersindividual added model mainappmembergeneric added model mainappcompanymanager added model mainapppendingregistration added model mainapppendingauthorisation created initialpy you apply migration managepy migrate mainapp graffiastestingtustincommercialcomoneclickcos python managepy migrate mainapp running migrations mainapp nothing migrate loading initial data mainapp no fixtures found graffiastestingtustincommercialcomoneclickcos as see south thinks nothing however last three models completely new table database is anything i short zapping database get south working i intention manually writing migrations rest project would help i would write one migration
3
i would argue create symlinks like especially going distribute python code assume user python python usrbinpython if script requires python use usrbinenv python if script requires python use usrbinenv python this way scripts work fine even updates python it also much clear version script actually needs
so i read httpswikiarchlinuxorgindexphppython and clear wiki i install python via pacman s python is reasonable create symlink python ln python usrbinpython i forsee switching python time soon or better way managing multiple python versions like i usually use debian system updatealternatives config python mac os x system python select clarification what i trying find best practice managing various python versions archlinux system i new archlinux familiar ubuntu debian mac os x
3
python habitually returns none functions methods mutate data listsort listappend randomshuffle idea hints fact mutating if want take iterable return new sorted list items use sorted builtin function
purpose accept file name print unique words alphabetically problem the file runs i able verify finduniquewords result sorted list however return list main method i seem find any ideas thanks lee def finduniquewordsthelist newlist words read line time item thelist remove punctuation line cleaned cleanupitem split line separate words words cleanedsplit evaluate word word words count unique word word newlist newlistappendword answer newlistsort return answer def cleanupphrase item strphrasereplace item stritemreplace item stritemreplace item stritemreplace item stritemreplacen return item def main filename rawinputenter filename list openfilename r finallist finduniquewordslist print finallist main
3
you forgot sorting requirement edit apparently set sorts elements ascending order probably implementation detail if asked write function test maybe required implement whole thing instead delegating set edit for completeness implementation meet requirements def commonelementsa common x x commonappendx commonsort return tuplecommon
write function commonelementsa takes tuples arguments returns sorted tuple containing elements found tuples my task commonelements commonelements p n p p commonelements p n p p i tried like def commonelementsa return tuplesetaintersection seta anyone know mistake requirement i pass
2
using urllib make everything easier import urllib request urllibrequest httpmapsgooglecommapsfeedsmapsdefaultfull requestaddheader authorization googlelogin auths authorizationtoken urlliburlopenrequestread btw google maps data api deprecated httpgooglegeodevelopersblogspotcommapsdataapideprecationannouncementhtml
i trying get list maps created google maps maps api says following retrieving list maps the maps data api provides feed lists maps created particular user feed known metafeed a typical maps data api metafeed get request following form the default feed requests maps associated authenticated user get httpmapsgooglecommapsfeedsmapsdefaultfull authorization googlelogin authauthorizationtoken the standard metafeed requests maps associated associated userid get httpmapsgooglecommapsfeedsmapsuseridfull authorization googlelogin authauthorizationtoken note get requests require authorization http header passing authsub googlelogin token depending authentication scheme implemented the googlelogin token corresponds clientlogin authentication process i idea create http request authorization http headers i already code get authorizationtoken follows coding utf import urllib getpass httpcodegooglecomintlptbrapismapsdocumentationmapsdatadevelopersguideprotocolhtmlclientlogin username heltonbiker senha getpassgetpass senha usuã¡rio username dic accounttype google email username gmailcom passwd senha service local source heltonmapper url httpswwwgooglecomaccountsclientlogin urlliburlencodedic output urlliburlopenurlread authid outputstripsplit n split i also took look httplib docs understand much i professional programmer any clue
3
set ordered so order result may arbitrary i would come something like def commonelementsa l el el lappendel return tuplel please note way solving problem would get output elements ordered tuple so mentioned comments correct way call ordering sorting also complexity onm n lengths lists respectively onlogm achieved case bisect module used access elements second tuple sorted proceeding if sorting common way required i would stick code bit altered def commonelementsa return tuplesortedsetaintersectionseta on average complexity ominmnlogminnm sorting onm worst case intersection if code needs implemented without using set example purposes study code def commonelementsa l el el lappendel lsort return tuplel complexity onm with using bisect code would look way bisect import bisectleft def commonelementsa l asort sort able use binary search internal loop thus changing complexity on onlogn assuming n rather equal alen lena el bisectlefta el alen ai el lappendx lsort uncomment line list sorted order needed ordered first lits possible sort beginning function would slower average since l smaller average since l intersection return tuplel complexity onlogm
write function commonelementsa takes tuples arguments returns sorted tuple containing elements found tuples my task commonelements commonelements p n p p commonelements p n p p i tried like def commonelementsa return tuplesetaintersection seta anyone know mistake requirement i pass
2
def commonelementsa return tuplesortedsetaintersection seta
write function commonelementsa takes tuples arguments returns sorted tuple containing elements found tuples my task commonelements commonelements p n p p commonelements p n p p i tried like def commonelementsa return tuplesetaintersection seta anyone know mistake requirement i pass
2
ok question open i answer unless i missing something br variants replace br amplt br ampgt in python looks like means text resub br amplt text text resub br ampgt text to explain going negative lookahead successfully matches position following text match subexpression contains note lookaheads consume text matched subexpression verify exists similarly negative look behind thing using preceding text however lookbehinds slight different lookaheads regex implementations subexpressions inside lookbehinds must represent fixedwidth limitedwidth matches python one ones requires fixed width whilst expression works always four characters brs would valid regex python represents variable length match however stack multiple lookbehinds could potentially manually iterate assorted options necessary
i able regex i looking syntax exclude something i parsing amp html code replace amplt etc i need exclude br parsing ie htmlbr headtitletitleheadbr bodybr bodybr html i tried sometihng like ie r bbr others work completely i use resub replace
1
fname argv openfname reader csvreaderi firstrow nextreader currow reader outname currow openoutname wb writer csvwritero writerwriterowfirstrow writerwriterowcurrow hope helps
i trying solve following problem using python i table csv i want extract consecutively row row row etc the extracts saved csv file named according first string nd row extracted now question python right tool example code available thanks lot advance help amp hints claude s clarification thanks feedback actually i trying use csv module open read table using code import csv import sys f opensysargv rt try reader csvreaderf row reader print row now i sure select write required rows sorry beginners kind question claude s
1
your program suggests entrybodyfat variables generated fly want the normal approach store entries labels list map tkinter import root tk names weight bodyfat hydration muscle bones entry label name names e entryroot egridstickye entryname e lb labelroot textname lbgridrowi column labelname lb def printallentries name names print entrynameget b buttonroot textprint commandprintallentries bgridstickys mainloop the value bodyfat entry entrybodyfatget
i want create simple gui i enter values a label button start script i using something like w labelmaster textweight wgridstickye w labelroot textbodyfathydrationmusclebones wgridstickye w labelroot texthydration wgridstickye ok want dynamic also would use w entrys could cast wget need data thinking def createwidgetsself lweightbodyfathydrationmusclebones lv index rangelenl printindex printlindex entrylindex entryroot entrylindexgridstickye labellindexlabelroot textlindex labellindexgridrowindex column to call later varweightentryweightget varbodyfatentrybodyfatget make work
2
then create container class named tuple tuple whatever pickle modify original class parts want pickled pickle serialisation standard python mechanism so unless need eg interoperability different languages stick
i python class contains many objects data structures lists dicts etc handlers classes also contain data structures rather using pickle save entire class amp contents i wondering way serialize data several desired objects save only binary file for example suppose i following python objects mylist mydict b c what best way save contents both python objects binary file ideally i like save objects binary file able load data later
3
you write file system changing fakefileallowedmodes flags googleappenginetools import devappserver allowedmodes devappserverfakefileallowedmodes devappserverfakefileallowedmodes frozenset w f open testtxt w fwrite test fclose devappserverfakefileallowedmodes allowedmodes
what easiest way restore original builtin openfile function appengine devappserver i need get working assets manager development environment compiling multiple jscss files
2
i solution yet something interesting python i realized python used convenient tool notation algorithms basically i wrote program similar started transforming program logically leave results unchanged i came def orderxy xy return xy else return yx n numset n range n rangenn b rangenn ab continue numaddorderanbn orderbnan printn lennum obviously brute force even simple loop feasible maybe algorithm one find closed form expression point if set character num would doable maybe one find duplicate point way this could dead end still pretty cool python used notation work algorithms any progress side
i stuck project euler problem here i done far let denote rectangle width height x respectively xy to form new rectangles consider cutting kind stairway diagonal shown problem description steps but form new rectangle following must hold dx either dy dy the new rectangle becomes either xdd ydd xdd ydd obviously new rectangles area old rectangle that enough confirm g g looping relevant adding new rectangles set careful count xy yx the main issue method possible make new rectangle two different ways for example transform either dividing or another example transforms respectively i lucky enough read blog post it removes need check duplicates searching one sides instead def fw h wamp hamp return wh wh hw r x x wh whx xh x continue wwx xxh r x return r def gn w range n h range w fwh return g would require far long solve regardless fast f though i think necessary either use kind sieving algorithm loop x counting many wh satisfy h w xwh x h wxw xhx i think on algorithm must possible i stuck edit i access forum since i unable solve that i asking help i completed questions want tackle question edit i think considering areas prime factors dead end that different areas rectangles prime areas solutions rectangles semiprime areas solution one primes otherwise solutions but counting semiprime solutions alone would take long since need count primes p p feasible edit i stripped code def gn x range n h range n xh continue w rangemaxh xh n whx xwx xxh x range n h range n xh continue w rangemaxh xh n whx wwx x range n h range n xh continue w rangemaxh xh n whx hxh return i think breaking bruteforce code work though remember enough count solutions x w h three subproblems the last summation would constraints x n h n xh maxh x h w n xwh xhh i think start assumption prime p divides x w h even xh see deduce variables if works well maybe consider p k arbitrary k
1
if use dateutil gae in import dateutilparser parser in parserparse sunday st july pm fuzzytrue out datetimedatetime otherwise rely manipulate date string format strptime parse in datetimedatetimestrptimeresubr w dw ofs r sunday st july pm b y ims p out datetimedatetime
i new python i need migrate project php python running gae environment i need move data one database gae one the chellenge write data strings datetime objects dates stored strings created using php pattern l ds f y a so every date looks like sunday st july pm i looked python documentation i see datetimestrptime job it parameter th rd st endings and may issues well what could advise i use regexp remove unneccessary crap way create datetime object string directly thank advance
2
basically sort string first get ackz use regex like ckz match
for example characters match czk string zack matches string zak does match i tried ckz ckz obviously wrong i feel simple task unable find answer
1
it common assume must give readability get performance that necessarily you need find what exactly spending much time notice i say need measuring here example i mean chances good simple changes avoid waste motion fix anything program told fix
i writing scientific program python c complex physical simulation algorithms after implementing algorithm i found lot possible optimizations improve performance common ones precalculating values getting calculations cycle replacing simple matrix algorithms complex but arises problem unoptimized algorithm much slower logic connection theory look much clearer readable also harder extend modify optimized algorithm so question techniques i use keep readability improving performance now i trying keep fast clear branches develop parallel maybe better methods
2
def whatyoushoulddoservings integrationmethodoven make chicken soup comments they important with syntax highlighting comments first thing new programmer look therefore motivate algorithm outline break stages you make it feel as if you are reading text interspersing code amongst text algorithm overview to make chicken soup acquire chicken broth noodles preprocessing ingredients done optimize cooking time then output soup format via stdout begin algorithm preprocessing thaw chicken broth broth chickenstoredeserialize mix noodles noodles cache begintransactionlocalspoulty cachenoodles tbuynoodles get local store noodles cachenoodles perform thorder rungekutta numerical integration import kitchensink import fixme poor form better kitchensink import pan beginning result boilerplaterkbroth semidirectproduct noodles serve hot logdebug attempting serve return result logdebug server successful also see httpenwikipediaorgwikiliterateprogrammingexample i also heard httpenwikipediaorgwikiaspectorientedprogramming attempts help though i really looked it seems fancy way saying put optimizations debugs junk outside function writing
i writing scientific program python c complex physical simulation algorithms after implementing algorithm i found lot possible optimizations improve performance common ones precalculating values getting calculations cycle replacing simple matrix algorithms complex but arises problem unoptimized algorithm much slower logic connection theory look much clearer readable also harder extend modify optimized algorithm so question techniques i use keep readability improving performance now i trying keep fast clear branches develop parallel maybe better methods
1
to modify existing list use list assignment eg l b c e f l b print l b c e f i would usually prefer create new list using comprehension eg key newvalue x key else x x l but first comment already mentioned sounds like trying make list something really using dict instead
i list tuples l b c e f and two parameters key value new value modify for example key newvalue b means modify b value tuples i two options works f lambda tkv k kv newlist ftkeynewvalue l print newlist newlist rangelenl elem lpop elem key newlistappendkeynewvalue else newlistappendelem print newlist but new python know right can help thank
1
to create new list list comprehension would in key b key else val keyval l out b c e f to modify list place l b c e f ielt enumeratel keyvalelt key likey b printl b c e f
i list tuples l b c e f and two parameters key value new value modify for example key newvalue b means modify b value tuples i two options works f lambda tkv k kv newlist ftkeynewvalue l print newlist newlist rangelenl elem lpop elem key newlistappendkeynewvalue else newlistappendelem print newlist but new python know right can help thank
2
here approach i would use l b c e f key newvalue b pos index index k v enumeratel k key lpos key newvalue break else lappendkey newvalue l b c e f this looks awful lot like ordereddict though keyvalue pairs preserved ordering you might want take look see suits needs edit replaced try except stopiteration break else since might look bit less weird
i list tuples l b c e f and two parameters key value new value modify for example key newvalue b means modify b value tuples i two options works f lambda tkv k kv newlist ftkeynewvalue l print newlist newlist rangelenl elem lpop elem key newlistappendkeynewvalue else newlistappendelem print newlist but new python know right can help thank
1
here one solution involving altering items inplace def replacelist key newvalue currentkey currentvalue enumeratelist currentkey key listi key newvalue or append def replaceorappendlist key newvalue currentkey currentvalue enumeratelist currentkey key listi key newvalue break else listappendkey newvalue usage mylist b c replacemylist b mylist b c if want create new list list comprehension easiest mylist b c findkey newvalue b newlist key newvalue key findkey else value key value mylist newlist b c and wanted append lennewlist lenmylist newlistappendfindkey newvalue note also i changed variable name l l easily confused i best avoided thus saith pep i agree
i list tuples l b c e f and two parameters key value new value modify for example key newvalue b means modify b value tuples i two options works f lambda tkv k kv newlist ftkeynewvalue l print newlist newlist rangelenl elem lpop elem key newlistappendkeynewvalue else newlistappendelem print newlist but new python know right can help thank
2
the natural way would probably use sets rather regex like set czk issubsets code often simpler easier maintain without using regex much
for example characters match czk string zack matches string zak does match i tried ckz ckz obviously wrong i feel simple task unable find answer
2
x xchopped intx x intx
x x xintx ok x want round say use later way dont know x time real place start even possible know change int want store ever took store right id write statments figure say doent strike best way
1