text_a
stringlengths
5
12.3k
text_b
stringlengths
36
15.7k
Score
int64
1
3
another option addition casey already provided set remote mysql database somewhere user access levels allowing remote connections your python program could simply access database insert data trying store centrally eg mysqldb package pyodbc package your users could either read data client supports mysql could write simple frontend python php displays data database
i program i wrote python collects data i want able store data internet somewhere allow another user access another computer somewhere else anywhere world internet connection my original idea use email client gmail store data sending pickled strings address this would allow anyone access address simply read newest email get data it worked perfectly program requires new email sent every seconds so method fell limit gmail emails among reasons i unable completely delete old emails now i want try different idea i know much network programming python i want setup webpage essentially nothing the master program program actually collecting data send pickled string webpage then remote programs able read string i also need master program delete old strings updates webpage it would preferred able store multiple string chance master updating remote reading i know feasible task python ideas welcome also ideas different way i ears well eyes case
1
xizor use link instead button redirect edition form becasue button probably sending post view ps please forgive english edit answer think right make useful
i modelform i created view template add instance database i trying extend editable user clicks button formtemplate page appears i get this field required message fields empty instead prepopulated instance i passed i edit values something different originally database correct instance updated so passing primary key none values showing if anyone tell i wrong i would appreciate oh i using post django edit form based add form basis please send here files modelform class creditcardformformsmodelform class meta model creditcard fields nameoncard cardnumber contactnumberoncard view def editrequest idnone templatename articleedittemplatehtml id print edit mode card getobjectorcreditcard pkid cardcardowner requestuser raise httpresponseforbidden else print create mode card creditcardcardownerrequestuser requestpost print requestpost form creditcardformrequestpost instancecard formisvalid print isvalid formsave if save successful redirect another page redirecturl reversearticlesavesuccess return httpresponseredirect cards else print else form creditcardforminstancecard return rendertoresponse createcredithtml form form contextinstancerequestcontextrequest template include basehtml form action methodpost csrftoken fieldset legendrequiredlegend div classfieldwrapper formnameoncarderrors label foridtopicname appears cardlabel formnameoncard div div classfieldwrapper formcardnumbererrors label foridtopiclast digits card numberlabel formcardnumber div fieldset fieldset legendoptionallegend this credit card only div classfieldwrapper formcontactnumberoncarderrors label foridtopicinstitution contact number label formcontactnumberoncard div fieldset pinput typesubmit valuesavep form urls urlr newcredit viewsedit crdsnewcredit urlr editcreditpidd viewsedit crdseditcredit
2
one way accomplish matplotlib suggested tags to i would use numpy create nxn array represent imagegradient create figure square shape size inches correlated radius circle imagecircleradius need keep mind figure dotsperinch figdpi create axes margins frame ticks figaddaxesframeonfalse xticks yticks use imshow plot array image create circle center radius units dpi use setclippath method clip axesimage created imshow call this approach inspired matplotlib example here attempt prescribe import numpy np import matplotlibpyplot plt import matplotlibpath path import matplotlibpatches patches pi nppi sqrt npsqrt exp npexp def makenodeimagemeasuredvalue stddev coverageimageid dpi todpi minsize dpi maxsize dpi maxamplitude make radiusstddev values grid units meancircleradius intsqrtmeasuredvaluepitodpi imagecircleradius intsqrtmeasuredvalue stddevpitodpi imagecircleradius minsize raise exceptionimagecircleradius small imagecircleradius maxsize raise exceptionimagecircleradius large gridstddev stddevtodpi gradientamplitude stddevsqrtpimaxamplitude gradientfade npzerosimagecircleradius imagecircleradius ix rangeimagecircleradius iy rangeimagecircleradius r sqrtiximagecircleradius iyimagecircleradius gradientfadeixiy exp rmeancircleradius gridstddev imagegradient gradientamplitudegradientfade fig pltfigurefigsizeimagecircleradiusdpi imagecircleradiusdpidpidpi ax figaddaxesframeontrue xticks yticks generateimagefromgradient im aximshowimagegradientvminvmax patch patchescircleimagecircleradiusimagecircleradius radiusimagecircleradiusfc white scaleandclipimagetoimagecircleradius imsetclippathpatch name circimagedpng imageid figsavefigname return name makenodeimagepi this results the circle seems clipped edges the almost certainly vectorized approach build gradientfade though hand i know this feels kludgy i really hope someone provides elegant answer obviously code starting point someone definitely improve upon
i producing simple pythonbased program produces graphviz graphs output i would like use custom nodes depict data program using custom nodes simple enough image i trouble figuring convenient method producing images i want specifically i would like nodes circles whose area represents measured value gradient represents uncertainty value it seems reasonable use contour map produced math program eg sagemath tend make square images scaled alternatively gradient functions image manipulation programs seem difficult relate rigorous gaussian function ideally i would like write function along lines pseudocode def makenodeimagemeasuredvalue stddev meancircleradius sqrtmeasuredvaluepi imagecircleradius sqrtmeasuredvalue stddevpi gradientamplitude stddevsqrtpi gradientfade ermeancircleradiusstddev imagegradient gradientamplitudegradientfade generateimagefromgradient scaleandclipimagetoimagecircleradius return image the two starred bits i need help i appreciate suggestions thanks
1
this might dangerous reason done one line project modelspy file usermetaorderingusername
i application makes use django userprofile extend builtin django user model looks bit like class userprofilemodelsmodel user modelsforeignkeyuser uniquetrue local stuff imageurls modelscharfieldmaxlength blanktrue imageurlm modelscharfieldmaxlength blanktrue admin class admin pass i added new class model class teammodelsmodel name modelscharfieldmaxlength manager modelsforeignkeyuser relatedname manager members modelsmanytomanyfielduser blanktrue and registered admin class teamadminadminmodeladmin listdisplay name manager adminsiteregisterteam teamadmin alas admin inteface i go select manager dropdown box set team members via multiselect field ordered user numeric id for life i figure get sorted i similar class class meta ordering name that works great but i user class i try trick useradmin class meta ordering username i get djangocoremanagementbasecommanderror one models validate eventsuserprofile ordering refers username field exist userusername work either i could specify like imageurls i wanted i tell admin sort lists users username thanks
2
the superior solution building python pythonbrew automates process also allows install several different versions also easily select in pyenv pyrun viable solutions
ubuntu comes python preinstalled i also downloaded python dev packages because another issue i explained extreme depth how i replaceupdate version expat library used apache graham dumpleton told distro explicitly built python way use external pyexpat implementation causing issue he also said i could build python source code resolve issue how would i ubuntu keep mind i new linux
1
it appears best method use nginx multiple tornado instances i alluded original question cole mentions nginx reload configuration file fly so process looks like update pythontornado web application code start new instance application different port update configuration file nginx point new instance testing syntax configuration file first reload nginx configuration file kill hup command stop old instance pythontornado web server a couple useful resources nginx regarding hotswapping configuration file httpscalomelorgnginxhtml explaining directives nginxconf section httpwikinginxorgcommandline loading new configuration using signals section
i recently started experiment python tornado web serverframework web development previously i used php framework lamp stack with php deploying updated codenew code easy uploading server way modphp apache interact when i add new code update code pythontornado i need restart tornado server i could see problematic number active users do i restart server anotherbetter way b if i avoid users disconnectedgetting errorsetc restarting could take seconds one possible thought use page flipping paradigm nginx pointing server launch new server instance updated code redirect nginx take original server
3
there variety approaches ipythonparallel includes two implementations zeromq one simple purezmq another elaborate controller implemented python we split controller two actors hub outoftheway process sees traffic keeps track state cluster pushing results database etc notifying clients engine connectdisconnect etc scheduler core simple routerdealer device forwards requests clients engines replies back looking taskfarming part topology scheduler mq queue device router dealer socket bind clients dealer sockets connected scheduler router engines router sockets connected scheduler dealer which makes use two properties dealers lru loadbalance requests across peers routers use identity prefixes send replies back peer made particular request a toy loadbalanced task farm pyzmq routes replies back requesting client httpsgistgithubcom an alternative results go somewhere back requesting client ventilatorsink pattern mq guide
i using zeromq solve problem involves several hundred potentially thousands clients request tasks carried each client would request specific task carried results completed whould returned back client issued request these actors i identified far pattern i come client actor requests unit work job carried controller actor loadbalances jobs accross available engines engine actor receives job request controller publishes result back client i still yet worked engine gets mesage back client i guessing one way implemented using zeromq would client push job messages one socket controller subscribe completed results published engine another socket controller pull job messages client one socket publish job messages engines another socket clearly forwarding device engine subscribe job messages one socket publish result another socket it would helpful someone provide skeletonsnippet show outline pattern may implemented using zeromq framework the code snippet c c php python c edit after reading task farms suggested akappa i think problem indeed modelled task farm i modified original actors accordingly changed title it would still useful someone familiar zeromq sketch skeleton would show i use core components build framework
3
it default behaviour comparing lists x xsortreverse true printx
i need sort list lists entry outer list list three integers like the trick i need sort entry tie sort entry also tie sort entry list i keep overthinking loops sort statements i able get way check entries order without rearranging lists values instead keeping hierarchy any suggestions
3
i see article linked tuples one types python maintains free lists they could well according article specific culprits int float dict list although article things could changed since in python later free lists everything int float cleared gccollect i guess help gae i thought i mention
according article i read looks like immutable type may become immortal httpeffbotorgpyfaqwhydoesntpythonreleasethememorywhenideletealargeobjecthtm i currently working solve memory usage problem web service running google app engine does use much tuple could potential reason cause problem thanks reply i running code google app engine backend instance memory usage upper bounds mb it said i use memory allowed stopped instance as comments mentioned it could memory usage remain large instead memory leaks
1
the immutable type become immortal the memory occupied still owned python available use objects circular dependencies possibility memory leak class parentobject def initself selfoffspring childself def delself matter goes gc able auto collect freed parents childs class childobject def initself parent selfparent parent johndoe parent at point child link parent parent link child python may trouble releasing
according article i read looks like immutable type may become immortal httpeffbotorgpyfaqwhydoesntpythonreleasethememorywhenideletealargeobjecthtm i currently working solve memory usage problem web service running google app engine does use much tuple could potential reason cause problem thanks reply i running code google app engine backend instance memory usage upper bounds mb it said i use memory allowed stopped instance as comments mentioned it could memory usage remain large instead memory leaks
1
this article specify immutable types specifies another possible cause excessive memory usage python uses socalled “free lists” certain object types including integers floats i know information get gae process try experiment system first start python interpreter find process then run command manytuples x range replace xrange x then take look memory usage you created list million tuples now type del manytuples on system python win memory usage shot k dropped amount i del ed variable if get information processes cpu memory usage try maybe several times row give spikes higher memory usage
according article i read looks like immutable type may become immortal httpeffbotorgpyfaqwhydoesntpythonreleasethememorywhenideletealargeobjecthtm i currently working solve memory usage problem web service running google app engine does use much tuple could potential reason cause problem thanks reply i running code google app engine backend instance memory usage upper bounds mb it said i use memory allowed stopped instance as comments mentioned it could memory usage remain large instead memory leaks
3
linker error fix yum install pythondevel
i using python pygments version rhel always get error message i try create new project gitlabhq gem list reveals pygmentsrb rubypython among others after running rails e production i see following error stdout this error happens first completed internal server error ms actionviewtemplateerror could open library libso libso cannot open shared object file no file directory bashlexer pygmentslexerbash div class div classgitempty hgit global setuph appviewsprojectsemptyhtmlerbin appviewsprojectsemptyhtmlerb appcontrollersprojectscontrollerrbin show i see actionviewtemplateerror undefined method highlight nilnilclass git config global useremail currentuseremail eos raw bashlexerhighlightsetupstr br br hnext stepsh appviewsprojectsemptyhtmlerbin appviewsprojectsemptyhtmlerb appcontrollersprojectscontrollerrbin show
1
use strjoin waypoints joinformatplatitude plongitude p points
i set points latitude longitude values i trying create string following format order work gmaps api latitudexlongitudexlatitudeylongitudey the final string built using unknown number lat long pairs my previous experience php whilst i managed get something working however seems bit clumsy i wondering pythonic way achieve result here i far waypoints point points waypoints waypointsss pointlatitude pointlongitude waypoints waypoints any advice appreciated thanks
3
have considered python audio tools it ability load mp play using player class the player class initializer accepts audiooutput object lets specify number playback channels the project seems well supported last git commit october th two weeks prior posting it also around appear flybynight library
im coding music player python using pyqt i wanted feature mono playback mp files i accomplished using pygame mixer specific parameter channels i set get mono playback however pygame mp support limited i searching library able handle mp files and mono playback currently i using pyaudiere playback site example processing song playing maybe i could turn song mono i really idea accomplish i like help code feature using pyaudiere library handle mp files edit i would also accept solution c i always build python wrapper using boostpython
1
the source xmlrpclib contains comment might find applicable outside original context note call remote object nonstandard name use result getattrserver strangepythonnameargs it general python idiom
how using python i dynamically generate call xmlrpc server using xmlrpc lib something like def callmethodmethodname server serverselfurl transportproxiedtransport servermethodnameparams the resolution takes methodname instead example methodnamegettime servergettimeparams
1
setupclass new unittest framework if want use older version need use nose test runner instead unittest
i trying get started unittest i problem getting setupclass work here test code import unittest class testrepgenunittesttestcase contains methods training data testing testvar none classmethod def setupclasscls clstestvar def testmethodself ensure data selected selfassertisnotnoneselftestvarselftestvar none run tests name main unittestmain the assert error message displayed indicating selftestvar none changed setupclass is something wrong code i get result i run code within ide wing directly command line for record i using python windows
3
there database must purchased called pdnickname i found via question database common name aliases nicknames people searched google nickname database second result in addition transformations pointed hunter simple you implement transformations minutes less the one pointed william bill still quite simple although need list names nicknames hence link database from sample text name variation gender abigail abbey f abigail abbie f abigail abby f abigail gail f abigail abaegayle f abigail abagael f may bit overkill williams like called bill p edit there also alternative google code csv names common nicknamesdiminuntives
i looking apidictionary resource help return variants names i give eg if pass william defoe return wdefoe billd williamd etc i found adequate resource online my implementation either python java
1
look tornadoescapeurlescapevalue tornadoescapeurlunescapevalue encoding utf something like coding utf dont know show import tornadoioloop import tornadoweb class abdoutornadowebrequesthandler def getself selfwritehi miaw tornadowebapplication tornadoescapeurlescapeu ã©ã©ã© abdou name main miawlisten tornadoioloopioloop you probably also want able get urls user inputs i think like class pagetornadowebrequesthandler def getselftitle title tornadoescapeurlunescapetitle encoding utf selfwritetitle miaw tornadowebapplication tornadoescapeurlescapeu ã©ã©ã© page get ã©ã©ã©pagename pagename unicode name main miawlisten tornadoioloopioloop
tornado accept unicode adress coding utf dont know show import tornadoioloop import tornadoweb class abdoutornadowebrequesthandler def getself selfwritehi miaw tornadowebapplication u ã©ã©ã© abdou name main miawlisten tornadoioloopioloop flask worked flask import flask miaw flaskname miawrouteu ã©ã©ã© def abdou return hi name main miawrun nb problem using escape like hello world flask works nb thank wisty edit appears professional code p
1
everything tried far creates shallow copy outer list to create deep copy use either copiedlist x x mylist using list comprehension copiedlist copydeepcopymylist using copydeepcopy function
i need able duplicate list lists python example right i function returns list always lists within list example mylist i need create two copies list mylist mylist separately mutable example i edit mylist mylist edited i tried everything simple mylist mylist mylist mylist complicated mylist ch mylist mylistappendch mylist ch mylist mylistappendch nothing works if i change value one list mylist lists become any idea
3
use copydeepcopy mylist copydeepcopymylist see working online ideone
i need able duplicate list lists python example right i function returns list always lists within list example mylist i need create two copies list mylist mylist separately mutable example i edit mylist mylist edited i tried everything simple mylist mylist mylist mylist complicated mylist ch mylist mylistappendch mylist ch mylist mylistappendch nothing works if i change value one list mylist lists become any idea
2
the mysqldb developer recommends building application specific api db access stuff worry mysql query strings application code it make code bit extendable link as cursors understanding best thing create cursor per operationtransaction so check value update value read value type transaction could use cursor next one would create new one this pointing direction building internal api db access instead generic executesql method also remember close cursors commit changes connection queries done your getdatabaseresult function need connect every separate query though you share connection queries long act responsible cursors
i writing python cgi script query mysql database i using mysqldb module since database queryed repeatedly i wrote function def getdatabaseresultsqlqueryconnectioninfohere connect database vdatabase mysqldbconnectconnectioninfohere create cursor execute sql statement get result tuple cursor vdatabasecursor try cursorexecutesqlquery except cursorclose return none result cursorfetchall cursorclose return result my question is best practice of i reuse cursor within functions for example which better def callsanewcursorandconnectioneachtime result getdatabaseresultsomequery result getdatabaseresultsomequery result getdatabaseresultsomequery result getdatabaseresultsomequery away getdatabaseeresult function together something like def reusesthesamecursor vdatabase mysqldbconnectconnectioninfohere cursor vdatabasecursor cursorexecutesomequery result cursorfetchall cursorexecutesomequery result cursorfetchall cursorexecutesomequery result cursorfetchall cursorexecutesomequery result cursorfetchall
3
if find another ideal solution one method i ended using ocr preprocessing past convert source images ppm use unpaper ubuntu you attempt deskew image based whichever sides specify clearlydefined edges option bypass filters would normally applied black white text you probably want images example images skewed degrees using bottom right edges detect rotation unpaper n dn bottomright dr inputppm outputppm unpaper written c source help
i process lot scanned ids i need extract photos processing here fictional example the problem scans perfectly aligned rotated degrees so i need find position rotate cut photo this turned lot harder i originally thought i checked opencv thing i found rectangle detection give good results rectangle always matches good enough samples also image matching algorithm works notrotated image since brute force comparison so i though using artoolkit augmented reality lib i know able precisely locate given marker image but seems markers simple i use constant part document purpose please correct i wrong also i found superhard compile ubuntu ocr tried one yet i start research i thankful suggestions look i look cpreferablec solution python option
1
import datetime os def mtimefilename return datetimedatetimefromtimestamposstatfilenamestmtime timediff mtimefilepatha mtimefilepathb … format resulting datetimetimedelta object desired way
is handy functions retrieve timestamp given files even compare my ideal usage would like timediff datefilepatha datefilepathb timediff would formatted string days hrs mins i know builtin datetime module python i found anything similar usage and i know i achieve similar effect issuing osstatfilepath get timestamp transform format i want just wondering handy function
3
you use timectime ospathgetctime getmtime functions if prefer format time string use timestrftime formatting timectimeospathgetctime filea ospathgetctime fileb
is handy functions retrieve timestamp given files even compare my ideal usage would like timediff datefilepatha datefilepathb timediff would formatted string days hrs mins i know builtin datetime module python i found anything similar usage and i know i achieve similar effect issuing osstatfilepath get timestamp transform format i want just wondering handy function
2
here pseudocode php script start transaction insert into table anything want sleep update table set field foo commit script start transaction update table set field foo sleep insert into table anything want commit execute script immediately execute script another terminal you get deadlock database table already data in words starts deadlocking second time try note mysql honor sleep command use python equivalent application
i want make python library working mysqldb able detect deadlocks try i believe i coded good solution i want test any ideas simplest queries i could run using mysqldb create deadlock condition would system info mysql client windows xp python mysqldb p
1
gstreamer python bindings here simple music player import gobject import gst pipeline gstparselaunch filesrc locationstereomp mad audioconvert audioxrawintchannels autoaudiosink pipelinesetstategststateplaying gobjectthreadsinit gobjectmainlooprun i really suggest look gstreamer become defacto multimedia solution open source platforms supports wide variety audio files sample apps using rhythmbox banshee totem etc
im coding music player python using pyqt i wanted feature mono playback mp files i accomplished using pygame mixer specific parameter channels i set get mono playback however pygame mp support limited i searching library able handle mp files and mono playback currently i using pyaudiere playback site example processing song playing maybe i could turn song mono i really idea accomplish i like help code feature using pyaudiere library handle mp files edit i would also accept solution c i always build python wrapper using boostpython
1
use one libraries python application talk sshd daemon server httpwikipythonorgmoinsecureshell you want look something help set sshd secure manner like httpwwwlinuxjournalcomarticle you also need ensure update sshd daemon regularly make use keys strong rotating passwords all standard telnet application due lack transport level encryption really using telnet anything
i write python telnet client communicate server telnet however many people tell secure how i convert ssh should i need totally rewrite program
1
adding alternative pan answer need use many different proxies time in case need create opener like http proxy there code available github httpsgistgithubcom opener urllibbuildopenersocksipyhandlersocksproxytypesocks localhost print openeropen httpwwwwhatismyipcomautomationnasp read
how i use socks proxy urllib download web page
3
just create tcp tunnel via ssh relay data need reinvent wheel you find examples ssh docs tcp tunneling man ssh instance but really want rewrite check paramiko project
i write python telnet client communicate server telnet however many people tell secure how i convert ssh should i need totally rewrite program
1
indeed deprecated more importantly gdkpixmap serverside resource contents pixmap live x server memory when getfromdrawable asking contents transferred application expensive instead create cairo image suface drawing this clientside resource get performance penalty image surfaces scaled drawing another surface suitable transformation
i created instance gtkgdkpixmap painted something for example pixmap gtkgdkpixmapwidgetwindow pixmapdrawrectanglegc true pixmapdrawlinegc how i resize pixmap one way i see copy pixmap pixbuf using gtkgdkpixbufgetfromdrawable resize pixbuf copy pixbuf pixmap is way without copying
1
bnc e f g h j knl n p q r resplitr ss b c e f g h j k l n p q r resplitr ss maxsplit b c e f g h j k l n p q r resplitr ss flagsredotall b c e f g h j k l n p q r the problem passing redotall positionally sets maxsplit argument flags argument redotall happens constant
i mac running lion python i noticing something strange module if i run following line print resplitr ss bnc e f g h j knl n p q r i get result b c e f g h j k l n p q r but i run redotall flag like print resplitr ss bnc e f g h j knl n p q r redotall then i get result b c e f g h j k l n p q r note q r counted one match instead two why happening i see redotall flag would make difference i using dots pattern am i something wrong sort bug
3
nice easy solution lol it turns page args useful cause fact creating problem overwriting myargs none one pages keyword variables accessed directly files without using page args
goal to access myargs base child templates currently i access one call childrendermyargs b base excerpt page argsmyargsnone kwargs myargs myargs endif selfbodymyargsmyargs child excerpt version page argsmyargsnone kwargs inherit filebasehtml myargs b b myargs b endif child excerpt version page argsmyargsnone kwargs inherit filebasehtml def namebody myargs b b myargs b endif def using child version child throws error myargs undefined base works using child version base throws error myargs undefined child works these exact examples essence dilemma if someone explain pass variables inheritance chain would lovely unfortunately documentation mako seems skip section
2
that particular error commonly caused trying decode using utf string actually encoded latin see unicodedecodeerror invalid continuation byte info i suspect despite header server returning utf encoded content a solution might worth pursuing use chardet guess encoding used despite chardet awesomeness consider last resort however
okay i coding utf python file snippet opener urllibbuildopener openeraddheaders useragent mozilla openeraddheaders acceptcharset utf f openeropenurl doc freaddecode utf the server response via finfo contenttype texthtml charsetutf get error unicodedecodeerror utf codec decode byte invalid continuation byte what wrong
1
this variation paul mcguire docstringinheritor metaclass it inherits parent member docstring child member docstring empty it inherits parent class docstring child class docstring empty it inherit docstring class base classes mros like regular attribute inheritance unlike class decorator metaclass inherited need set metaclass toplevel base class docstring inheritance occur throughout oop hierarchy import unittest import sys class docstringinheritortype a variation httpgroupsgooglecomgroupcomplangpythonmsgfbfcbdc paul mcguire def newmeta name bases clsdict doc clsdict clsdict doc mrocls mrocls base bases mrocls basemro docmroclsdoc doc clsdict doc doc break attr attribute clsdictitems attributedoc mrocls mrocls base bases mrocls basemro hasattrmrocls attr docgetattrgetattrmroclsattr doc doc isinstanceattribute property clsdictattr propertyattributefget attributefset attributefdel doc else attributedoc doc break return typenewmeta name bases clsdict class testunittesttestcase def testnullself class fooobject def frobnicateself pass class barfoo metaclassdocstringinheritor pass selfassertequalbardoc objectdoc selfassertequalbardoc objectdoc selfassertequalbarfrobnicatedoc none def testinheritfromparentself class fooobject foo def frobnicateself frobnicate gonk class barfoo metaclassdocstringinheritor pass selfassertequalfoodoc foo selfassertequalfoodoc foo selfassertequalbardoc foo selfassertequalbardoc foo selfassertequalbarfrobnicatedoc frobnicate gonk def testinheritfrommroself class fooobject foo def frobnicateself frobnicate gonk class barfoo pass class bazbar metaclassdocstringinheritor pass selfassertequalbazdoc foo selfassertequalbazdoc foo selfassertequalbazfrobnicatedoc frobnicate gonk def testinheritmetaclassself class fooobject foo def frobnicateself frobnicate gonk class barfoo metaclassdocstringinheritor pass class bazbar pass selfassertequalbazdoc foo selfassertequalbazdoc foo selfassertequalbazfrobnicatedoc frobnicate gonk def testpropertyself class fooobject property def frobnicateself frobnicate gonk class barfoo metaclassdocstringinheritor property def frobnicateself pass selfassertequalbarfrobnicatedoc frobnicate gonk name main sysargvinsert verbose unittestmainargvsysargv
i oo hierarchy docstrings take much maintenance code eg class swallowobject def airspeedself returns airspeed unladen raise notimplementederror class africanswallowswallow def airspeedself whatever now problem africanswallowairspeed inherit superclass method docstring i know i keep docstring using template method pattern ie class swallowobject def airspeedself returns airspeed unladen return selfaskarthur implementing askarthur subclass however i wondering whether another way docstrings inherited perhaps decorator i discovered yet
3
try decoding data using latin see looks like what seeing indicates utf decode error see unicodedecodeerror invalid continuation byte it would helpful posted result listfread see data fyi putting coding utf unrelated issue that encoding refers encoding python script data handling
okay i coding utf python file snippet opener urllibbuildopener openeraddheaders useragent mozilla openeraddheaders acceptcharset utf f openeropenurl doc freaddecode utf the server response via finfo contenttype texthtml charsetutf get error unicodedecodeerror utf codec decode byte invalid continuation byte what wrong
2
gdrating deprecated httpcodegooglecomapisyoutubereferencehtmlyoutubedataapitaggdrating anyway check raiting exists entryrating print entryratingaverage print entryratingnumraters else print entry rating
this works perfectly finding average rating number raters youtube video usrbinpython import sys gdatayoutubeservice import youtubeservice yt youtubeservice entry ytgetyoutubevideoentryvideoidsysargv direntryrating findextensions tostring addmemberstoelementtree becomechildelement convertelementattributetomember convertelementtreetomember harvestelementtree toelementtree class delattr dict doc format getattribute hash init module new reduce reduceex repr setattr sizeof str subclasshook weakref attributes children namespace tag average extensionattributes extensionelements max min numraters text print entryratingaverage print entryratingnumraters video rating throws error attributeerror nonetype object attribute average any suggestions thanks
1
no possible when python process launched gets copy environment copied parent shell the python process modify private copy changes propagated back parent process if want something like best get print shell commands needed desired environment variable changes eg print export pythonpathpythonpath run script using eval python myscriptpy
for following python script import os ossystem pythonpathuser ossystem export pythonpath is anyway export pythonpath variable shell executing script
2
class repeatinggroupedsequence needs overwrite extractpadding method def extractpaddingself return by default sub packet treats everything belonging layer ie def extractpaddingself return none and used grouping purposes can someone elaborate difference padding layer separation
i trying specify new packet format using scapy in packet list items items consist grouped fields by grouped fields i mean subsequence fields different types the way making grouped fields i know scapy using packet class using fieldlenfield packetlistfield reference length sequence type list members is way go something looks like scapypacket import packet scapyfields import class repeatinggroupedsequencepacket name simple group two fields fieldsdesc intfield field intfield field class toplayerpacket name storage repeating sequence fieldsdesc fieldlenfieldlength none countof repseq packetlistfield repseq none repeatinggroupedsequence countfrom lambda pkt pktlength now problem i assembling packetlistfield craft toplayer packet p toplayer add two repeated sequences prepseq repeatinggroupedsequence repeatinggroupedsequence sequences observed pshow underlying structure repeated sequence raw stage pshow length print prepseq length lenprepseq cloned packet one repeated sequence rest raw clone toplayerstrp cloneshow length print clonerepseq length lenclonerepseq the problem approach structure grouping preserved packet reassembled on assembly second instance repeatedsequence treated raw body even though count field how add repeatingsequences like structure preserved reassembly is way group fields without resorting packet storage type lists
2
write function classdecorator style copying in python apply directly class created in later versions apply decorator notation here first cut import types def fixdocscls name func varsclsitems isinstancefunc typesfunctiontype funcdoc print func needs doc parent clsbases parfunc getattrparent name none parfunc getattrparfunc doc none funcdoc parfuncdoc break return cls class animalobject def walkself walk like duck class doganimal def walkself pass dog fixdocsdog print dogwalkdoc in newer python versions last part even simple beautiful fixdocs class doganimal def walkself pass this pythonic technique exactly matches design existing tools standard library for example functoolstotalordering class decorator add missing rich comparison methods classes and another example functoolswraps decorator copies metadata one function another
i oo hierarchy docstrings take much maintenance code eg class swallowobject def airspeedself returns airspeed unladen raise notimplementederror class africanswallowswallow def airspeedself whatever now problem africanswallowairspeed inherit superclass method docstring i know i keep docstring using template method pattern ie class swallowobject def airspeedself returns airspeed unladen return selfaskarthur implementing askarthur subclass however i wondering whether another way docstrings inherited perhaps decorator i discovered yet
3
minx x mylist x
i question algorithm point view i list numbers floats and i want find smallest number greater lets say so answer but besides obvious solution iterating thru list keeping track smallest number greater k pythonic way thanks
3
i idea python algorithmic point view maybe i add something in example list monotonically increasing sorted if always true list small optimization might stop iterating reached number larger if list always numbers lower great optimization number items target number random improvement reliable in case might want search list partitioning test middle element larger if larger throw away upper half otherwise throw away lower half do thing new halflength list you need deal even odd numbers case items left listsegment for large list reduce number tests significantly
i question algorithm point view i list numbers floats and i want find smallest number greater lets say so answer but besides obvious solution iterating thru list keeping track smallest number greater k pythonic way thanks
1
binary search would standard way deal list sorted previous answer pointed see python binary searchlike function find first number sorted list greater specific value in python find index first value greater threshold sorted list discussion module httpdocspythonorglibrarybisecthtml
i question algorithm point view i list numbers floats and i want find smallest number greater lets say so answer but besides obvious solution iterating thru list keeping track smallest number greater k pythonic way thanks
3
i would make use xml attributes envvar namemake typecommandwhich makeenvvar envvar nameqtdir typestringhomeqtlibsqtqtenvvar pseudocode depending xml library nodeattributes type command value ospopennodefirstchildtextread elif nodeattributes type string value nodefirstchildtext osenvironnodeattributes name value
i xml contains information environment variable set shell python script here snippet xml envvar name qtdir homeqtlibsqtqtenvvar envvar name make makeenvvar this part snippet tells python script set environment variables qtdir make my concern difference set variables i know use osenviron set environment variables something like osenviron qtdir homeqtlibsqtqt but use set make variable execute command make get path make executable my goal use methodfunction set every variables so thought something like popenqtdirhomeqtlibsqtqt export qtdir shelltrue stdoutpipe stderrpipe popenmakewhich make export make shelltrue stdoutpipe stderrpipe but variable set subprocess current shell so question way want i don t want analyse xml something like pseudocode qtdir normal value osenviron qtdir homeqtlibsqtqt make value executed p popenwhich make shelltrue stdoutpipe stderrpipe stdout stderr pcommunicate osenviron make stdout
2
no significant digits big deal get little support computer languages people real computations need error bars far precision — real measurements say exact things like “this Ⱡmm“ instead saying either less exact statements “this mm” “this mm” makes choose power ten even inexactness actually fall power ten
is way python count significant figures doublefloatetc i seeing easy way i expect library thanks advance
2
the bad news root problem python datetime implementation the good news django open ticket problem the bad news ticket opened the good news recent proposal useful reading seems development the thread containing proposal long informative the bad news proposal boils real mess still development going i found postgres backend directs django create columns use time zones no django design decision postgresql stores utc store timezone store offset the timezone conceptually like environmental variable gets applied timestamps inserted selected retrieval from django developer mail archive in absence actual time zone support database action taken django going inconvenience somebody likely compatible nondjango use database that big problema fix might make database incompatible languages frameworks that absolute showstopper i work many programming languages frameworks access database sqlite microsoft access mysql datetime data type timestamp cited thread lacking timezone support database
i thought django created datetime columns time zone agnostic i looked postgres table i saw values recorded time zone information going i found postgres backend directs django create columns use time zones from djangodbbackendspostgresqlcreationpy datatypes datetimefield timestamp time zone the schema shows created column specified timestamp time zone create table notificationnotice created timestamp time zone not null the postgres log shows update statement sent django constructed sql statement used utc time zone directed django settings file update notificationnotice set senderid groupid null noticetypeid contenttypeid objectid created e where notificationnoticeid this table looks like the created column timestame time zone postgres must inspecting time zone system clock find time zone mydb select notificationnotice limit id senderid groupid noticetypeid contenttypeid objectid created lastinteractiontime row questions doesn django hands policy time zones why postgres backend use time zones modelsdatetimefield is required postgres is way force django create timestamp columns postgres use time zone
3
you giving facecolors boolean the parameter defined facecolor facecolors matplotlib color arg sequence rgba tuples just make facecolor none work you probably dont want get color two plots if eliminate parameter get automatic colors if still need custom colors easiest way indicate matplotlib colors yellow red etc
i learning draw scatter using matplotlib however bug seems related color argument could anyone explain mistake i googled answer found thanks advance xacta range yacta nprandomrandn xactq range yactq nprandomrandn xra nprandomrandn yra nprandomrandn f figure scatterxacta yacta c b marker facecolors true label answers scatterxactq yactq c r marker facecolors true label questions xscale log yscale log title user activity xlabel number posts ylabel number users legend fshow fsavefig figuretestpng
1
if mycnt string integer read directly sysargv loop never end
i script walk system directory get files sizes directory sorts file sizedescending takes two arguments the first arg system path second arg integer limit output integer count i using loop limit print output getting stuck infinite loop obviously something wrong cant see usrbinpython import sys import os grab arguments mydir sysargv mycnt sysargv print mydir print mycnt set base dir rootpath mydir filesize rootdir mydir filedict dict count root dirs files oswalkrootdir file files filepath ospathjoinrootfile filesize filesize ospathgetsizefilepath filedictfilepath filesize key value sortedfiledictiteritems keylambda keyval valkey reversetrue count mycnt print value key count else sysexit
2
you instead you want exit program count mycnt
i script walk system directory get files sizes directory sorts file sizedescending takes two arguments the first arg system path second arg integer limit output integer count i using loop limit print output getting stuck infinite loop obviously something wrong cant see usrbinpython import sys import os grab arguments mydir sysargv mycnt sysargv print mydir print mycnt set base dir rootpath mydir filesize rootdir mydir filedict dict count root dirs files oswalkrootdir file files filepath ospathjoinrootfile filesize filesize ospathgetsizefilepath filedictfilepath filesize key value sortedfiledictiteritems keylambda keyval valkey reversetrue count mycnt print value key count else sysexit
1
you added else clause loop it execute loop never executes your loop terminates count increases past mycnt anoter iteration loop executed mabe notice â­â€” loop may take long
i script walk system directory get files sizes directory sorts file sizedescending takes two arguments the first arg system path second arg integer limit output integer count i using loop limit print output getting stuck infinite loop obviously something wrong cant see usrbinpython import sys import os grab arguments mydir sysargv mycnt sysargv print mydir print mycnt set base dir rootpath mydir filesize rootdir mydir filedict dict count root dirs files oswalkrootdir file files filepath ospathjoinrootfile filesize filesize ospathgetsizefilepath filedictfilepath filesize key value sortedfiledictiteritems keylambda keyval valkey reversetrue count mycnt print value key count else sysexit
1
fwiw repr module tools display list limiting number lines output
i script walk system directory get files sizes directory sorts file sizedescending takes two arguments the first arg system path second arg integer limit output integer count i using loop limit print output getting stuck infinite loop obviously something wrong cant see usrbinpython import sys import os grab arguments mydir sysargv mycnt sysargv print mydir print mycnt set base dir rootpath mydir filesize rootdir mydir filedict dict count root dirs files oswalkrootdir file files filepath ospathjoinrootfile filesize filesize ospathgetsizefilepath filedictfilepath filesize key value sortedfiledictiteritems keylambda keyval valkey reversetrue count mycnt print value key count else sysexit
2
there assignment python primitive types assignment pointers if want create copy need special copy function
i exporting c class python i noticed compilation swig issued following warning warning operator ignored i sure operator overloaded says swig documentation swig capable handling operators assignment operator there nothing special class declared like class foo public foo fooamp operator const fooamp etc why swig failing generate wrapper code assignment operator may i fix
3
larry lustig already hit nail head regarding mycnt check see hit limit also wrong hamish points rather count mycnt could use slice like maximum removing need count variable speaking variables i suggest would benefit betternamed variables viz usrbinenv python import sys import os rootdir sysargv maximum intsysargv print printing biggest maximum files rootdir filedict root files oswalkrootdir filename files filepath ospathjoinroot filename filesize ospathgetsizefilepath filedictfilepath filesize sortedbysize sortedfiledictiteritems keylambdapath size size path reversetrue path size sortedbysizemaximum print size path
i script walk system directory get files sizes directory sorts file sizedescending takes two arguments the first arg system path second arg integer limit output integer count i using loop limit print output getting stuck infinite loop obviously something wrong cant see usrbinpython import sys import os grab arguments mydir sysargv mycnt sysargv print mydir print mycnt set base dir rootpath mydir filesize rootdir mydir filedict dict count root dirs files oswalkrootdir file files filepath ospathjoinrootfile filesize filesize ospathgetsizefilepath filedictfilepath filesize key value sortedfiledictiteritems keylambda keyval valkey reversetrue count mycnt print value key count else sysexit
1
the built command finding current screen sessions screen ls to get functionality python subprocess import checkoutput def screenpresentname var checkoutputscreen ls trueshelltrue namet var print name running else print name running screenpresentserver a couple comments code i use true shelltrue screen returns exit code play well checkoutput function also i added make sure matching screen name another part printout
how check python whether screen given name ex server running thanks
2
usrbinpython import os import sys print ospathrealpathsysargv
if i execute python script actually symbolic link linked real script somewhere else anyway print location real script
1
the answer appears search engine query away you also use direct link time complexity page pythonorg quick summary average ominlens lent worst case olens lent edit as raymond points worst case scenario likely occur i included originally thorough i leaving provide context discussion i think raymond right
in python get intersection two sets amp set sintersections set anybody knows complexity intersection amp algorithm edit in addition anyone know data structure behind python set
3
alternatively want use argv usrbinpython import os print ospathrealpathfile
if i execute python script actually symbolic link linked real script somewhere else anyway print location real script
2
the intersection algorithm always runs ominlens lens in pure python looks like def intersectionself lenself lenother little big self else little big self result set elem little elem big resultaddelem return result answer question additional edit the data structure behind sets hash table
in python get intersection two sets amp set sintersections set anybody knows complexity intersection amp algorithm edit in addition anyone know data structure behind python set
3
call base class method outerclassamethodsomeclassbobject
when i call method outer class ends calling derived class method instead how i force call base class method is best inner class init call parent init class outerclassa init method def methodself class innerclassbouterclassa def methodself
1
python double underscores name mangling designed help issue for details workedout example see httpdocspythonorgtutorialclasseshtmlprivatevariables httpdocspythonorgreferenceexpressionshtmlatomidentifiers class outerclassa def initself selfmethod call class private copy def methodself method method make private class local copy class innerclassbouterclassa def methodself
when i call method outer class ends calling derived class method instead how i force call base class method is best inner class init call parent init class outerclassa init method def methodself class innerclassbouterclassa def methodself
2
configure error acceptable c compiler found path this error selfexplanatory get c compiler xcode work
i trying install django project onto osx machine requires pycrypto i getting following error running install running build running buildpy running buildext running buildconfigure checking gcc checking cc checking clexe configure error usershomedocumentstmpdlitzpycryptoda configure error acceptable c compiler found path see configlog details traceback recent call last file setuppy line module coresetupkw file systemlibraryframeworkspythonframeworkversionslibpythondistutilscorepy line setup file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommands file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommand file systemlibraryframeworkspythonframeworkversionslibpythondistutilscommandinstallpy line run file systemlibraryframeworkspythonframeworkversionslibpythondistutilscmdpy line runcommand file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommand file systemlibraryframeworkspythonframeworkversionslibpythondistutilscommandbuildpy line run file systemlibraryframeworkspythonframeworkversionslibpythondistutilscmdpy line runcommand file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommand file setuppy line run selfruncommandcmdname file systemlibraryframeworkspythonframeworkversionslibpythondistutilscmdpy line runcommand file systemlibraryframeworkspythonframeworkversionslibpythondistutilsdistpy line runcommand file setuppy line run raise runtimeerrorautoconf error runtimeerror autoconf error
3
why use a lot existing python code compatible python yet if need use django example forced use python x my second question one i use python pyqt recommendations
i used python years ago version now was reason continued upgrade split two different pythons like one uses python they use whatever why use obviously reason i unable find googling my second question one i use i assuming only based higher number i wonder still around if major bugs i going use i reckon much matters either one would probably work py qt
3
python significantly different python x breaks numerous libraries likely lot dependent code python x likely around quite libraries ported fieldtested
i used python years ago version now was reason continued upgrade split two different pythons like one uses python they use whatever why use obviously reason i unable find googling my second question one i use i assuming only based higher number i wonder still around if major bugs i going use i reckon much matters either one would probably work py qt
2
costs lot upgrade python x python project still uses python
i used python years ago version now was reason continued upgrade split two different pythons like one uses python they use whatever why use obviously reason i unable find googling my second question one i use i assuming only based higher number i wonder still around if major bugs i going use i reckon much matters either one would probably work py qt
1
the latest ubuntu ship python yet openbsd package python either some people may python platform care compile
i used python years ago version now was reason continued upgrade split two different pythons like one uses python they use whatever why use obviously reason i unable find googling my second question one i use i assuming only based higher number i wonder still around if major bugs i going use i reckon much matters either one would probably work py qt
1
prefix command pythonpath replace directory app without telling python find modules know look current directory part path default
my app needs backup system remote administration i disabled federated login easier remoteapi access now i log i import module montao python remoteapishellpy montaoprojectappspotcom email niklasro password app engine remoteapi shell python r apr gcc the db users urlfetch memcache modules imported smontaoproject import traceback recent call last file console line module importerror no module named smontaoproject could tell run simple remote api commands i could run backup system connect via ahremoteapi python setup seems correct i might need clearer understanding use remoteapi update this works seems use django ubuntuubuntumedialexarmontao pythonpathmontaoproject python remoteapishellpy montaoprojectappspotcom app engine remoteapi shell python r apr gcc the db users urlfetch memcache modules imported smontaoproject import warningrootyou using default django version the default django version change app engine release near future please call uselibrary explicitly select django version for information see httpcodegooglecomappenginedocspythontoolslibrarieshtmldjango smontaoproject
2
your class demonstrates new python i try clean point things without completely rewriting other solutions cleaner hopefully help understand concepts class chemistry because class method automatically receive reference instance call method you account declaring method standard name self def readamuself infil openatomamutxt r line infilreadline atoms list as frã©dã©ric said tuples immutable means changed this means empty tuple never added later program therefore leave next line element line line linerstripn parts linesplit element parts amu parts the next several lines indicate got right idea got method calls reversed if work would want reverse object append method getting called original elementappendelement amuappendelement elementappendatoms correct element element amu atomsappendelement if make sure atoms part self work disappear end method able anything later selfatoms atoms now want load atomic numbers instantiate chemistry class call readamu method c chemistry creadamu print catoms remember atoms part c instance last line selfatoms atoms
i working chemistry program requires list elements corresponding atomic mass units something along lines elements hhec elements amu read file line written like c i need read information file append line tuple append tuple list here code i tried without success class chemistry def readamu infil openatomamutxt r line infilreadline atoms list element line line linerstripn parts linesplit element parts amu parts elementappendelement amuappendelement elementappendatoms am i right track if would i append two values tuple assign value index append list
1
this quite simple arrange numpy the function nproll returns copy array rolled specified direction for example given array x xnparangereshape array roll columns right nprollxshiftaxis array using nproll boundaries wrapped like torus if want wrapped boundaries could pad array edge zeros reset edge zero every iteration import numpy np def diffusionarr true arrnprollarrshiftaxis right arrnprollarrshiftaxis left arrnprollarrshiftaxis arrnprollarrshiftaxis yield arr n initialnprandomrandomnn state diffusioninitial printstate rawinput
i pretty new python i project part includes diffusion across map i implementing going making current tile equal sum neighbors nwse if i c i double loop loops array arriwidth j arr j j ii neighbors several different arrays i thing different qualities map i changing however i sure really fastest way python some people i asked suggest stuff like numpy width probably k elements max i sure overhead worth i really know builtin functions i want any advice edit this dense ie every spot going nontrivial calculation
2
the easiest way make sure state object saved local scopes attributes object consider import cpickle class testobjet def initself filenamemystatepickle selfindex selffilename filename def saveself f openselffilename w cpickledumpself f fclose def dosomeworkself selfindex print selfindex selfindex selfsavecondition suppose condition become true index value selfsavecondition false selfsave might saved file restoreclassobject getsavedobject get object file of course dosomework makes sense sake example imagine method thread could still interact object setting restoreclassobjectsavecondition true save next iteration step
i want save object state reuse time i got example how save object pickle module i able find resume classmethod save state proceed like game save game latter continue i know game save data game read data build game i want save complete object i restore start working saved state for example class testobjet def dosomeworkself index index print index index savecondition suppose condition become true index value savecondition none savetheobjecttofile might saved file restoreclassobject getsavedobject get object file now start printing i want resume object state saved
1
instead saving temporary value val save list return list def encryptkey temp list char inkey tempappendordchar return temp
i trying save output loop iterationfor example code def encryptkey char key val ordchar example someone entered lol interpreter program outputs encryptlol in example i need store memory use another function anyone help
1
there number different methods could use python probably nicest way use list comprehension like def encryptkey return ordchar char key see httpdocspythonorgtutorialdatastructureshtmllistcomprehensions encrypt lol would return list
i trying save output loop iterationfor example code def encryptkey char key val ordchar example someone entered lol interpreter program outputs encryptlol in example i need store memory use another function anyone help
1
computers simply work way least unless programmed the assumption number give exact if create number operations treat exactly that error least significant digit may end propagating larger errors later computations something good code deal using algorithms minimize issues possible as i said however computers told so packages written use called interval arithmetic a number may described interval might create interval we operate intervals adding subtracting multiplying etc those operations often see interval widths expand operate the fact however even use interval arithmetic tools you must know beginning number significant digits numbers if create number storing double computer actually try store number assume digits exactly correct in fact course floating point arithmetic employed number actually stored internally binary number so probably effectively stored number decimal fractional numbers representable exactly binary form again care must employed software also always person using tools understand numbers really mean this last point important many people treat numbers generated computer truth handed computer god stone tablet if computer prints believe every digit see in fact common sense must applied know perhaps number generated data significant digits may choose rely first significant digits number and course taught concept school know trust trust remember however computers generally infinitely trusting it must apply filter
is way python count significant figures doublefloatetc i seeing easy way i expect library thanks advance
1
how threadingevents import threading import time import logging loggerlogginggetloggername def fresumeiswaitingname true resumeisset iswaitingset loggerdebug n pausing formatnname resumewait iswaitingclear loggerinfoname timesleep def hresumewaiters true loggerdebug halt resumeclear iw enumeratewaiters loggerdebug wait worker pause formatii wwait loggerinfo h begin timesleep loggerinfo h end loggerdebug resume resumeset timesleep loggingbasicconfiglevelloggingdebug format asctimes threadnames messages datefmt hms set means resume clear means halt resume threadingevent resumeset waiters name fg iswaitingthreadingevent waitersappendiswaiting threadingthreadtargetfargsresumeiswaitingnamestart threadingthreadtargethargsresumewaitersstart yields thread f thread g thread halt thread wait worker pause thread f pausing thread g pausing thread wait worker pause thread h begin thread h end thread resume thread f thread g thread f thread g thread f thread g thread f thread g thread f thread g thread halt in response question comments this code tries measure long takes h thread acquire lock worker threads it seems show even h waiting acquire lock worker thread may fairly high probability release reacquire lock there priority given h waiting longer david beazley presented pycon problems related threading gil here pdf slides it fascinating read may help explain well import threading import time import logging loggerlogginggetloggername def flockn true lock loggerinfon timesleep def hlocks true ttimetime nlock enumeratelocks lockacquire ttimetime loggerinfo h acquired n formatnndtt tt ttimetime loggerinfo h formatdtt tt lock locks lockrelease timesleep loggingbasicconfiglevelloggingdebug format asctimes threadnames messages datefmt hms locks n n rangen lockthreadinglock locksappendlock tthreadingthreadtargetfargslockn tstart threadingthreadtargethargslocksstart
i new concurrent programming i like execute three tasks repeatedly the first two run time third run every hour the first two tasks run parallel i always want pause third task running here skeleton i tried import threading import time flock threadinglock glock threadinglock def f true flock print f timesleep def g true glock print g timesleep def h true flock glock print h timesleep threadingthreadtargetfstart threadingthreadtargetgstart threadingthreadtargethstart i would expect code print f g every second h every five seconds however i run takes around f g i start seeing h it looks like first two threads constantly release reacquire locks third thread left loop why when third thread tries acquire currently held lock released acquisition immediately succeed instead firstsecond thread immediately acquiring i probably misunderstanding something what would good way achieve i want note moving timesleep calls flockglock block works simple example apparently real application threads spend time actual operations when first two threads sleep second execution loop body lock released third task still never gets executed
3
count one people get pretty expensive have found gut feeling i rather benchmark also whether web servers carry load assume beforehand indexing properly selecting storage engine might help lot furthermore lot userfriendly let people register enter account data registering event because seem favor people type real quick use decent browser
i looking system people rsvp free web conference web conferences get really busy lot interest limited places way ensure get oversubscribed so need countdown time book seat time order completed confirmed this way first x amount people actually click attending get seats conference if user complete booking allocated seat put back pool someone else grab an overview happens i see best working user clicks rsvp event makes ajax request rsvpeventid this goes stores unique id refered token rest question along timestamp it stores token session the user notified x amount time let say mins complete rest details nameemaildob etc however anything put database checks amount pending orders less total seats available seats left conference returns saying sorry seats available keep checking bookings completed seats become available if user fills time stores details database attending if however fail fill form time cron job running every second go delete tokens timestamp minutes ago loose chance attend seat conference put back pool they notified unsuccessful taken back first step all easy enough write simply putting records database count from pendingbookings where conferenceid x working many seats either confirmed orders pending subtracting total seats available conference but i feel using mysql would scalable i sure excess k people trying grab around seats count one people get pretty expensive decent caching needs checking real time many people process i looked using amazon simpledb deployandgo scalability i used seen count necessarily accurate nature scalability i guess obvious reasons count needs accurate i need able add records along timestamp able delete records older five minutes
2
using communication synchronization usrbinenv python import threading import time queue import empty queue def fq c true try qgetnowait qget get pause signal except empty pass signal thing else qget block resume signal print c timesleep def hqueues true q queues qputnowait qput block pause received print h q queues qput put resume timesleep queues queue range threadingthreadtargetf argsqueues f start threadingthreadtargetf argsqueues g start threadingthreadtargeth argsqueuesstart it might notoptimal performance point i find much easier follow output f g f g h f g f g g f f g g f g f f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h f g f g f g f g f g f g f g h
i new concurrent programming i like execute three tasks repeatedly the first two run time third run every hour the first two tasks run parallel i always want pause third task running here skeleton i tried import threading import time flock threadinglock glock threadinglock def f true flock print f timesleep def g true glock print g timesleep def h true flock glock print h timesleep threadingthreadtargetfstart threadingthreadtargetgstart threadingthreadtargethstart i would expect code print f g every second h every five seconds however i run takes around f g i start seeing h it looks like first two threads constantly release reacquire locks third thread left loop why when third thread tries acquire currently held lock released acquisition immediately succeed instead firstsecond thread immediately acquiring i probably misunderstanding something what would good way achieve i want note moving timesleep calls flockglock block works simple example apparently real application threads spend time actual operations when first two threads sleep second execution loop body lock released third task still never gets executed
1
pymongo
want log information mongodb using python found libraries mongodblog logmongo python idea one better library better
3
read last line documentation link section also aware certain operators map cleanly python for instance overloaded assignment operators map python semantics ignored
i exporting c class python i noticed compilation swig issued following warning warning operator ignored i sure operator overloaded says swig documentation swig capable handling operators assignment operator there nothing special class declared like class foo public foo fooamp operator const fooamp etc why swig failing generate wrapper code assignment operator may i fix
3
i executable i want change permissions write nowhere reading executing that chmod works sets permissions file restrict executable write
i change file permissions executable file using oschmod i executable i want change permissions write nowhere reading executing how i thanks rubik
1
the permissions set file chmod affect read fromwrite toexecute file privileges process created running file on unix could get form protection playing file owner sticky bit appropriate permissions filesystem easy get right work windows sticky bit
i change file permissions executable file using oschmod i executable i want change permissions write nowhere reading executing how i thanks rubik
1
a workaround used linux unixes forbid executable write something make executable setuid user permission nearly exist nobody user eg debian ubuntu be careful read seteuid amp setreuid amp capabilities amp credentials i know precisely syscalls pythonic interface
i change file permissions executable file using oschmod i executable i want change permissions write nowhere reading executing how i thanks rubik
1
the basic form query person example typepeopleperson namenone commontopicalias limit ​ there documentation available httpwikifreebasecomwikimqlmanual using freebasemqlreaditer python library httpcodegooglecompfreebasepython easiest way cycle in case limit clause determines chunk size used querying get result individually api level btw plan disambiguate jack kennedy president hurler football player book etc etc httpwwwfreebasecomsearchlimitampstartampqueryjackkennedy you may want consider capturing additional information freebase birth amp death dates book authors types assigned etc enough context able use disambiguate past certain point may easier andor efficient work bulk data dumps rather api httpwikifreebasecomwikidatadumps edit working python program assumes got list type ids file called typestxt import freebase f file typestxt f ttstrip q type mid none name none commontopicalias limit r freebasemqlreaditerq print jointr mid r name r commontopicalias fclose if make query much complex probably want lower limit keep running timeouts simple query like boosting limit default make efficient querying bigger chunks
vocabulary i using nounphrase a short phrase refers specific person place idea examples different nounphrases include barack obama obama water bottle yellowstone national park google chrome web browser etc category the semantic concept defining nounphrases belong ones examples categories include politician household items food people sports teams etc so would barack obama belongs politician people belong food sports teams i lage unlabeled nlp dataset consisting millions nounphrases i would like use freebase label nounphrases i mapping freebase types categories what i need download every single examples every single freebase type i the problem i face need figure structure type query at high level query ask freebase examples topic xx freebase respond list examples topic xx i would grateful someone could give syntax query if done python would awesome
2
the pythonic way something like bestofall maxpbest p selfplayers bestplayers p p selfplayers pbest bestofall lenbestplayers bestplayer bestplayers bestplayerwins print winner bestplayername nresult bestplayerbest elif lenbestplayers more one player best score resolve tie the first line generates list best properties selfplayers finds maximum the next line generates list players whose scores match best score the rest program prints results there really reason mess list indices
i begin written player selfplayers playershot selfplayersbest selfplayersbest selfplayersbest selfplayerswins print winner selfplayersname nresult selfplayersbest elif selfplayersbest selfplayersbest selfplayersbest selfplayerswins printwinner selfplayersname nresult selfplayersbest i know create loop dont know use comparing object values this works know many players players code would useless how write loop returns highest selfbest values
2
if k dictionary k xv xv kiteritems x for for anything older k dictxv xv kiteritems x
i want iterate dictionary examine value delete items matches certain values example del but know dangerous since list updated iterated what clean way python
3
this hardly useful question go yes webhelpers module frameworks make life much easier
i starting web project python likely using django pyramid i done work aspnet mvc i wondering python templating engines concept like web helpers for know callable piece serverside code generate bit even lot html for example module i call serverside python fill data set properties like number pages example generate pageable sortable table html aspnet mvc webgrid purpose also sometimes called datagrid listview httpblogbekijkhetcommvcwebgridhtmlhelperpaginghtml i wondering python templating engines something similar i would write
1
this behaviour controlled qabstractitemviewautoscroll property set like treewidgetsetautoscrollfalse however property mainly used automatically scrolling tree widget dragging items edge widget viewport so behaviour still needed might better override tree widget mousepress event instead def mousepresseventself event selfsetautoscrollfalse qtguiqtreewidgetmousepresseventself event selfsetautoscrolltrue
i qtreewidget bunch qtreewidgetitems each item couple columns when one columns wider width widget scroll bar bottom when i click qtreewidgetitem inside column wider widget qtreewidget automatically scroll try get much column within widget possible i want happen how i turn
3
you could use eval class name config file exactly matches class names python code classes scope eval evil coincidence one letter difference i think a safer way would add extra dictionary maps configuration class name python class name i configuration files know code names change config files without changing code vice versa avoids eval so look something like mappingdict classname mypythonclass classname mypythonclass keys strings values classes then perform lookup using value config file myclassname types extension myclass mappingdictmyclassname
i configcfg i parse using pythonmodule configparser in one section i want configure assignments form fileextension classname parsing results following dictionary types extension classname extension classname edit i know i class evaltypesextension foo class but i given understand eval evil used do know nicer way dynamically configure fileextension results class
2
something like tupleab b x
i know multiply elements single tuple tup tuptup my question multiply elements several tuples using loop example how i get x x
2
i would recommend use builtin filter function since clear done list also filter works iterable sequence container iterator here example work function in in filterlambda x x out instead lambda pass name function used filter data list documentation filter available httpdocspythonorglibraryfunctionshtmlfilter also note filter wellknown world functional programming utilizes powerful concepts find many languages even different paradigm
i want iterate dictionary examine value delete items matches certain values example del but know dangerous since list updated iterated what clean way python
1
x def multiplytheelementsofseveraltuplesusingaforloopx tupleofproducts x x product element x product element tupleofproductsappendproduct return tupletupleofproducts printmultiplytheelementsofseveraltuplesusingaforloopx printmultiplytheelementsofseveraltuplesusingaforloopy output
i know multiply elements single tuple tup tuptup my question multiply elements several tuples using loop example how i get x x
1
the issue linestyle the directive marker linestyle replace linestyle marker first two lines code you see complete list markers scatter
i using matplotlibpyplotscatter draw simple scatter plot however something wrong appears i cannot find solution here code drawing scatter plot xacta yacta xactq yactq lists dimensions ax scatterxacta yacta color blue label answers linestyle ax scatterxactq yactq color black label questions linestyle axsetlabel answers axsetlabel questions xscale log yscale log title user activity xlabel number posts ylabel number users legend fshow fsavefig figuretestpng and error plot contain dots here data xacta lenxacta yacta lenyacta xactq lenxactq yactq lenyactq and second error raised using another data set i checking datasorry previous unclear description
2
compares python objects objects database query returns new python objects c c different see try changing properties c c only one change seen docs c c equivalent cid cid
using django example foreignkey implicit example coconutsmodels import coconut swallow c coconutobjectsgetid swallowobjectsgetid c scoconutscarriedfilterid c c true c c false my understanding tests identity tests equality in case c c exact object why thing
2
they objects talk database objects python objects b true b python object instance identity the operator overloaded works python objects to understand whats going check idc idc interactive python shell you notice different identities b true b considered equal the operator overloaded different objects behaves differently compared when comparing django model objects considered equal type primary keys equal
using django example foreignkey implicit example coconutsmodels import coconut swallow c coconutobjectsgetid swallowobjectsgetid c scoconutscarriedfilterid c c true c c false my understanding tests identity tests equality in case c c exact object why thing
1
you need init every python class optional called present the actual constructor newstyle python classes new inherited object class fooobject pass foo mainfoo object xf foo traceback recent call last file stdin line module typeerror objectnew takes parameters if class inherits class provide init function inherited along like method this different say c constructors treated special inherited
in code following op created class inheriting template class class batchrenametemplate bottom code instantiating class batchrenamefmt albeit construction method def init as i understand inheritance python might something wrong code i new python i might missing something could anyone explain little code explaining the op shows use custom delimiters templates batch renaming files example he creating custom class inherits template change delimeter namefieldpropertyattribute use inner functionality time import time ospath photofiles imgjpg imgjpg imgjpg class batchrenametemplate delimiter fmt rawinput enter rename style ddate nseqnum fformat enter rename style ddate nseqnum fformat ashleynf batchrenamefmt date timestrftime dby filename enumeratephotofiles base ext ospathsplitextfilename newname tsubstituteddate ni fext print formatfilename newname imgjpg ashleyjpg imgjpg ashleyjpg imgjpg ashleyjpg i took code httpdocspythonorgtutorialstdlibhtmltemplating
2
the class batchrename need init inheriting super class template example class a def initself selfage class ba pass does nothing aage bage calling init super class a
in code following op created class inheriting template class class batchrenametemplate bottom code instantiating class batchrenamefmt albeit construction method def init as i understand inheritance python might something wrong code i new python i might missing something could anyone explain little code explaining the op shows use custom delimiters templates batch renaming files example he creating custom class inherits template change delimeter namefieldpropertyattribute use inner functionality time import time ospath photofiles imgjpg imgjpg imgjpg class batchrenametemplate delimiter fmt rawinput enter rename style ddate nseqnum fformat enter rename style ddate nseqnum fformat ashleynf batchrenamefmt date timestrftime dby filename enumeratephotofiles base ext ospathsplitextfilename newname tsubstituteddate ni fext print formatfilename newname imgjpg ashleyjpg imgjpg ashleyjpg imgjpg ashleyjpg i took code httpdocspythonorgtutorialstdlibhtmltemplating
1
the reason observation aes block cipher encrypt data blocks bits bytes to normally used mode operation allow encrypting larger pieces data padding mode it looks like python decrypting function decrypting undo padding giving result you using pkcs padding appends number bytes least one value number final length multiple block length for bytes string one needs append bytes value ascii backspace character terminal moves cursor one left times resulting xxx overprinting abc for bytes string one needs append bytes value this horizontal tabulator making xxx appear quite right either find supply right padding mode decryption function option remove padding check last byte decryptstring convert number using ascii value take many bytes end decryptstring you also check value you first interpreting output string ie applying encoding like utf ascii
i input string i encrypting mysql aesencrypt decrypting python mysql aesdecrypt i printed tests decrypted string print decryptstring print sxxx decryptstring print lendecryptstring print selftohexdecryptstring when input string length ie abcdefgh tests output abcdefgh xxxdefgh xxxxxxxxxxxxxxxx if input string length ie abcdefg abcdefg abcdefg xxx xxxxxxxxxxxxxxxx i found ending char progressively decreases length input string increases why difference if i use php aes encrypt instead mysql aesencrypt ending char x i using use third party python aes lib
1
if want use tuples length tupleproductmytuple mytuple def productcont base e cont base e return base
i know multiply elements single tuple tup tuptup my question multiply elements several tuples using loop example how i get x x
1
tuples length one line script tpl tuplereducelambda x xy tp tp tpl
i know multiply elements single tuple tup tuptup my question multiply elements several tuples using loop example how i get x x
1
i answer part question getting message something build process invoking gcc c source file option wstrictprototypes for c objectivec causes compiler warn oldstyle function declarations declare types arguments for c option make sense declarations even allowed language prototypes mandatory i know message mentions ada wstrictprototypes makes even less sense ada c it huge deal i submitted bug report marked resolvedfixed the solution remove wstrictprototypes option invocation gcc but since invoking gcc directly difficult know i able reproduce warning using setuppy manually creating dummy examplewrapcxx file python setuppy buildext running buildext building foolib extension gcc pthread fnostrictaliasing dndebug g fwrapv o wall wstrictprototypes fpic iusrincludepython c examplewrapcxx buildtemplinuxiexamplewrapo ccplus warning command line option wstrictprototypes valid adacobjc c so probably minor bug python buildext but since warning fatal error i say safely ignore gcc warns meaningless option ignores edit looking python sources section configurein might culprit case gcc yes test cc g strictprotowstrictprototypes fi i assuming invoked using buildext it turns wstrictprototypes option compiler invoked g case using gcc command compile c source code and libdistutilscommandbuildextpy buildextension pay attention source file language invoking selfcompilercompile invoking selfcompilerlinksharedobject which seems odd compilers gcc necessarily able use command compile c c makes sense use g command anyway even linking update a python bug report submitted httpsbugspythonorgissue closed duplicate one httpsbugspythonorgissue still open i write but i said warning probably safely ignore perhaps python maintainers use information fix problem future release
i building c extension use python i seeing warning generated compilation process type python setuppy buildext what causing i fix btw copy setup file usrbinenv python setuppy file swig example distutilscore import setup extension examplemodule extension foolib sources examplewrapcxx wrappersrcfoocpp librariesfoopp setup name foolib version author me myself i description example extmodules examplemodule pymodules example i using gcc ubuntu
3
i structure class using init new different accepts arbitrary arguments besides default first argument only rarely worry new usually define init let default new pass constructor arguments self keyword terms name changed something else but i wondering cls terms name subject change something else parameter name both parameter names special meaning language but use strong convention python community pythonistas never change names self cls contexts confused someone else note use def newtuple rebinds name tuple inside constructor function when actually implementing new want def newcls args kwargs allocation get object say obj return obj albeit i said i want return tuple code works fine returned myclass value new returns there implicit type checking python responsibility programmer return correct type consenting adults being able return different type requested useful implementing factories return subclass type requested this also explains issubclass isinstance behavior observe subclass relationship follows use class myclasstuple isinstance reflects return wrong type new for reference check requirements new python language reference edit ok example potentially useful use new the class eel keeps track many eels alive process refuses allocate exceeds maximum class eelobject maxeels neels def newcls args kwargs clsneels clsmaxeels raise hovercraftfull obj supereel clsnewcls clsneels return obj def initself voltage selfvoltage voltage def delself typeselfneels def electricself is electric eel return selfvoltage mind smarter ways accomplish behavior
i learning python far i tell things new init new object creation init object initialization new invoked init new returns new instance init invoked afterwards initialize inner state new good immutable object cannot changed assigned so return new instance new state we use new init mutable object inner state changed but i another questions when i create new instance myclasshelloworld arguments passed i mean i structure class using init new different accepts arbitrary arguments besides default first argument self keyword terms name changed something else but i wondering cls terms name subject change something else parameter name i made little experiments class myclasstuple def newtuple return i myclass albeit i said i want return tuple code works fine returned i knew passing first parameters type wanted receive new function invoked we talking new function right i know languages return type bound type and i anther things well issubclassmyclasslist false issubclassmyclasstuple true isinstanceamyclass false isinstanceatuple false isinstancealist true i experiment bright i decided stop decided ask stackoverflow the so posts i read python object creation pythons use new init
3
pygame support two displays single pygame processyet see question developer answer immediately says once sdl finished pygame get support using multiple windows process so options use multiple processes two pygame instances maximized screen communicating back forth could use cool python multiprocessing module local tcp pipes writingreading files etc set resolution displays create large wide window spans information one half user display then manually place window user side screen laptop screen it hacky might better use time engineering better solution if studpid works stupid use pyglet similar pygame supports full screen windows pygletwindowwindowfullscreentrue screens good luck
i using pygame program simple behavioral test i running macbook pro almost functionality working however testing i second external monitor subject sees laptop monitor i like game fullscreen external monitor laptop monitor i monitor performance currently start file looks something like usrbinenv python import pygame import sys stdscr cursesinitscr pygameinit screen pygamedisplaysetmode pygameresizable i thinking starting game resizable screen os x problems resizing window
3
each app engine instance max parallel http queries could potentially make times faster createrpc amp makefetchcall there scenarios work either need split job several tasks let run parallel
i working facebook application it written python running google app engine gae i know get relationship status users network way i running way slow there time limit gae order reduce cpu usage seconds using following code i get relationship status persons time frame getting deadlineexceedederror of course good enough since manymost people higher amount friends facebook what i get friend list user making api call one asking name relationship status the code i use f friends friendsinfof facebookapi f u fields namerelationshipstatus u accesstoken facebookaccesstoken and i get data relstatus friendsinfofu relationshipstatus what i need suggestions optimization ways extract relationship status entire network thanks advance edit the answers seems good ways solve problem though i find good tutorials batch request python i ended using fql call by using following takes seconds get data q select uid sex relationshipstatus user uid select targetid connection sourceid and actual data retrieved data fqlqueryqfacebookaccesstoken call function def queryselfqaccesstoken endpoint httpsapifacebookcommethod params dictqueryq accesstokenaccesstoken format json url endpoint fqlquery return selffetchurl paramsparams def fetchself url paramsnone conn urlliburlopenurl dataurlencodeparams try return jsonloadsconnread finally connclose hope someone make use well
1