text_a
stringlengths
5
12.3k
text_b
stringlengths
36
15.7k
Score
int64
1
3
i would write first function using generators def fiximportstopdir notuikeys walk directory substitute wrong imports itertools import imapifilter gen ifilternoneimapextractdotted notuikeys repl dictdottedaddmodeldotted dotted gen pyfiles pathjoinroot x root dirs files walktopdir x files x py py pyfiles openpy opf res replacetextopfread repl x py faster xendswith py
i dictionary form fromx fromchangedx possibly quite big i substitute text files accordingly dictionary quite big directory structure i find anything might nice solution i end using oswalk iterating dictionary writing everything with something like def fiximportstopdir notuikeys walk directory substitute wrong imports repl n notuikeys interleave model dotted extractdottedn dotted repldotted addmodeldotted root dirs files walktopdir pyfiles pathjoinroot x x files xendswith py py pyfiles res replacetextopenpyread repl def replacetextorigtext replacemap res origtext try grep keys using translate maybe dictionary replacements toreplace replacemap resreplacetoreplace replacemaptoreplace print differences un unifieddiffressplitlines origtextsplitlines printun return res is betternicerfaster way edit clarifying bit problem substitution generated function form xyz xyaddedz xba xbaddeda and yes sure i better use regexps i thought i need time i think help much however i really formalize whole range substitutions one multiple regexps
1
you also set entire script warnonly setting true def local envwarnonly true
when i define task run several remote servers task runs server one exits error fabric stop abort task but i want make fabric ignore error run task next server how i make for example fab siteservicegw siterpt executing task siteservicegw sitefep run echo nm sudo s route sitefep err sitefep err we trust received usual lecture local system sitefep err administrator it usually boils three things sitefep err sitefep err respect privacy others sitefep err think type sitefep err with great power comes great responsibility sitefep err root password sitefep err sudo route command found fatal error run encountered error return code executing echo nm sudo s route aborting
3
this question sort answered fully the issue to header wants emails string sendmail function wants list structure list emails emails banjerexamplecom slingbladeexamplecom dudeexamplecom use string to header msg to join emails use list sendmail function ssendmailfromemail emails msgasstring
i try send mails python multiple emailaddresses imported txt file i tried differend syntaxes nothing would work the code ssendmail sendermailcom recipientmailcom recipientmailcom recipientmailcom msgasstring so i tried import recipientaddresses txt file urlfile openmaillisttxt r maillist urlfileread ssendmail sendermailcom maillist msgasstring the mainlisttxt contains recipientmailcom recipientmailcom recipientmailcom but work i also tried maillist code txt file also effect maillist code txt file also effect does anyone knows thanks lot
3
are sure urlopen call hangs because loop terminate call successful
the function urlliburlopen freezes so question simple why urlopen freeze script ever even though timeout set how i access data url case httpapiowndtvlivechannelfnatictv without possibility python process freezing eternity this part freezes in owndpy try three times make contact true try connect api right it freezes connection urlliburlopenrequest timeout xmlstring connectionread except urlerror e tries tries sysstderrwrite owndstreamsupdater fatal error repeated timeouts exit this stack trace keyboardinterrupt traceback recent call last file line file honsappowndstreamsupdaterpy line updatestreaminfo streaminfo getstreaminfostream file honsappowndpy line getstreaminfo connection urlliburlopenrequest timeout file usrlocallibpythonurllibpy line urlopen return openeropenurl data timeout file usrlocallibpythonurllibpy line open response selfopenreq data file usrlocallibpythonurllibpy line open open req file usrlocallibpythonurllibpy line callchain result funcargs file usrlocallibpythonurllibpy line httpopen return selfdoopenhttplibhttpconnection req file usrlocallibpythonurllibpy line doopen r hgetresponsebufferingtrue file usrlocallibpythonhttplibpy line getresponse responsebegin file usrlocallibpythonhttplibpy line begin version status reason selfreadstatus file usrlocallibpythonhttplibpy line readstatus line selffpreadline file usrlocallibpythonsocketpy line readline data selfsockrecvselfrbufsize keyboardinterrupt edit i let script run night i know exactly long took though five minutes script finally gave gave stacktrace traceback recent call last file honsappowndstreamsupdaterpy line newinfo file honsappowndstreamsupdaterpy line newinfo result updatestreaminfostream file honsappowndstreamsupdaterpy line updatestreaminfo streaminfo getstreaminfostream file rootdropboxprojectshonstreamshonsappowndpy line getstreaminfo connection urlliburlopenrequest timeout file usrlocallibpythonurllibpy line urlopen return openeropenurl data timeout file usrlocallibpythonurllibpy line open response selfopenreq data file usrlocallibpythonurllibpy line open open req file usrlocallibpythonurllibpy line callchain result funcargs file usrlocallibpythonurllibpy line httpopen return selfdoopenhttplibhttpconnection req file usrlocallibpythonurllibpy line doopen r hgetresponsebufferingtrue file usrlocallibpythonhttplibpy line getresponse responsebegin file usrlocallibpythonhttplibpy line begin version status reason selfreadstatus file usrlocallibpythonhttplibpy line readstatus raise badstatuslineline httplibbadstatusline
2
most likely cause error mismatch calling conventions i guessing c dll exports functions cdecl convention use windll implies stdcall create library like use cdecl lpdllcdllcsomepathmydlldll
i trying use dll python source using ctypes i began reading python documentation i new after successfully loading dll python i try pass string function expects char gives valueerror procedure probably called many arguments bytes excess i also tried looking posts resolve problem i tried different approaches pas string using byref pointer change outcome i also tried winfunctype failed the dll i using windll here test program i wrote python ctypes import lpdllwindllcsomepathmydlldll print lpdll ipaddr createstringbuffer ipaddr ipaddr ccharp print ipaddr ipaddrvalue dinitlpdlldinit dinittesterlpdlldinittester dinittesterprototype winfunctypecint ccharp dinittesterparamflags ipaddress none dinittester dinittesterprototypedinittester lpdll dinittesterparamflags try dinit dinittester except valueerror msg print inittester failed print msg here dinittester implemented cpp file available dll exports dapi int dinittesterchar ipaddress int err errok libsinitialized code else err hndlconinitipaddress err err errnoconnection else ntesters instantiateanalysisclasses initializetestersettings ifnull hndlhndlfm fminitialized true else err errnotinitialized return err your help greatly appreciated
1
when submit form multiplechoisefield validates selected items belong choises parameter multiplechoisefield if dynamically later add fields naturally choises set read as solution could think using charfield selectmultiple widget override cleanmethod
i understand happening i form mylist formsmultiplechoicefieldrequiredfalse widgetformsselectmultiple label mylist helptext help i jquery page adds dynamic values i submit form i get formisvalid false object attribute cleaneddata this seems happens dynamically add values select box i select submitting if i select values cleaneddatamylist empty array how i fix basically i want access dynamically added list values django form submission edit requestmethod post form myformrequestpost action requestpost submit action update mylist formcleaneddata mylist else form myform edit def cleanmylistself data selfcleaneddata mylist return data def cleanself cleaneddata selfcleaneddata return cleaneddata
1
selfbitmaphide selfbitmapdestroy the first hide whereas second actually destroy widget you probably want call selflayout make window redraw update layout widgets
i know sounds easy delete image wxpython i using wxstaticbitmap wximage create image way delete image maybe theres something like bmp wximagefilename wxbitmaptypeanyconverttobitmap selfbitmap wxstaticbitmapselfsizer bmp deleteimageselfbitmap deleteimagebmp i tried replacing variable image still shows
3
that article meant show stretch resize image to probably require python imaging library pil then resize grab new size frame use calculate scale image see following link download pil httpwwwpythonwarecomproductspil
wondering put stretched background image sizer wxpython i looking tutorial httpwwwblogpythonlibraryorgwxpythonputtingabackgroundimageonapanel image resize import wx class mainpanelwxpanel def initself parent constructor wxpanelinitself parentparent selfsetbackgroundstylewxbgstylecustom selfframe parent sizer wxboxsizerwxvertical hsizer wxboxsizerwxhorizontal num range label button num btn wxbuttonself labellabel sizeraddbtn wxall hsizeradd wxexpand hsizeraddsizer wxtop hsizeradd wxall selfsetsizerhsizer selfbindwxevterasebackground selfonerasebackground def onerasebackgroundself evt add picture background yanked colourdbpy dc evtgetdc dc dc wxclientdcself rect selfgetupdateregiongetbox dcsetclippingrectrect dcclear bmp wxbitmapuntitledpng dcdrawbitmapbmp class mainframewxframe def initself constructor wxframeinitself none size panel mainpanelself selfcenter class mainwxapp def initself redirectfalse filenamenone constructor wxappinitself redirect filename dlg mainframe dlgshow name main app main appmainloop that code i sure resizing possible wxpython so basically i want able use picture background sizer however image stretched sizer size thanks
1
if want run django native language language file available need set languagecode httpsdocsdjangoprojectcomentopicsindeploymenthowdjangodiscoverslanguagepreference
i website two languages turkish english i already setup django internalization gettext if browser request turkish translates turkish if browser request english translates english but want turkish language show users how set language turkish permanentlyi using django thanks
2
are sure typo like something somthing typo left e traceback recent call last file stdin line module nameerror name somthing defined
i gui created glade i would like populate treeview widget here relevant part code def initself selffillstore selfaddcolumnselfwidget treeviewpreview selfwidget treeviewpreview setpixbufcolumn def fillstoreself selfwidget liststorepreview clear foo gdkpixbufpixbufnewfromfile png da gtkimagenewfrompixbuffoo selfwidget liststorepreview appendda def addcolumnself treeview renderer gtkcellrendererpixbuf column gtktreeviewcolumnpreview renderer pixbuf columnsetsortcolumnid treeviewappendcolumncolumn yet i try run code i get error informs renderer defined the offending line column gtktreeviewcolumnpreview renderer pixbuf can someone point error in case helps traceback traceback recent call last file testpy line module class test file testpy line test column gtktreeviewcolumnpreview r pixbuf nameerror name r defined thanks vz
1
try urlliburlopen instead urlliburlopen i situations urlliburlopen chokes proxy server urlliburlopen opens fine
i trouble script it supposed open website trough proxy i get always error several proxies i trying what could traceback recent call last file cusersshadydesktopptzplace copypy line module h urlliburlopenwebsite proxies http proxy file cpythonliburllibpy line urlopen return openeropenurl file cpythonliburllibpy line open return selfopenunknownproxyproxy fullurl data file cpythonliburllibpy line openunknownproxy raise ioerror url error invalid proxy type proxy ioerror errno url error invalid proxy http xxxxxxxxxxxx the script proxylist proxy proxylist h urlliburlopenwebsite proxies http proxy
3
wow this going complex job regardless that said if i understand needs project correctly something done using data migration south even i lying i said going joke my recommendation mostly parrot assumption question i want make clear one master table base records table added so table a keeps existing records gets additions b b feeds additions a done b deleted i hesitant write sample code actual job much complex i anyway try point right direction consider something like import datetime southdb import db southv import datamigration djangodb import models class migrationdatamigration def forwardsself orm b ormbobjectsall sanity check item get copied a ormaobjectsfilterusernamebusername continue make a record properties b record orma firstnamebfirstname lastnameblastname emailaddressbemailaddress save new a record delete b record asave bdelete def backwardsself orm backwards method write one this would end migrating bs a a leave table bs expected duplicates could check means deleting like i said sample meant complete if decide go route spend time south documentation particularly make sure look data migrations that ⢠hope helps
i two djangoorm managed databases i like merge both similar schema standard authusers table along shared tables reference well authusers i like merge single database automatically understandably could nontrivial depending upon foreignkey relationships constitutes unique record table does anyone know exists tool merge operation if nothing like currently exists i considering writing management command based standard loaddata command essentially use standard dumpdata command export tables source database use modified version loaddata merge destination database for example i databases a b i want merge database b database a i want follow procedure according pseudocode mergedatabasedst a mergedatabasesrc b table sortedmergedatabasedstgetredundanttablesmergedatabasesrc keyacyclicdependency key tablegetuniquecolumnkey srcidtodstid recordsrc mergedatabasesrctableobjectsall srckeyvalue recordsrcgetkeyvaluekey try recorddst mergedatabasedsttableobjectsgetkey dstkeyvalue recorddstgetkeyvaluekey except mergedatabasedsttabledoesnotexist recorddst mergedatabasedsttablekconvertfkv kv recordsrcmetafields recorddstsave dstkeyvalue recorddstgetkeyvaluekey srcidtodstidtablerecordsrcid recorddstid the convertfk function would use srcidtodstid index convert foreign key references source table equivalent ids destination table to summarize algorithm would iterate table merged order dependency parents iterated first so wanted merge tables authusers mycustomprofile dependent authusers iterate authusers mycustomprofile each merged table would need sort indicator documenting combination columns denotes universally unique record ie key for authusers might username andor email column if value key database b already exists a record imported b id existing record a recorded if value key database b exist a record imported b id new record recorded using previously recorded id mapping created explaining map foreignkey references specific record b new mergedpreexisting record a when future records merged a mapping would used convert foreign keys i could still envision cases imported record references table included dumpdata might cause entire import fail therefore sort dryrun option would needed simulate import ensure fk references translated does seem like practical approach is better way edit this exactly i looking i thought others might find interesting the turbion project mechanism copying changes equivalent records different django models within database it works defining translation layer ie mergingmodellayer two django models say update www field user bobbobcom profile automatically update url field user bobbobcom otherprofile the functionality i looking bit different i want merge entire partial database snapshot infrequent intervals sort way loaddata management command
1
as uses libediteditline syntax enable autocompletion little bit different you first force emacs bindings readline i wrong typing readlineparseandbindbind e then add autocompletion linked tab button man editrc readlineparseandbindbind rlcomplete and want support indenting history found internet look like unless i made mistake import readlinerlcompleter indenting class tabcompleterrlcompletercompleter completer supports indenting def completeself text state text return nonestate else return rlcompletercompletercompleteself text state readlinesetcompletertabcompletercomplete add autocompletion libedit readlinedoc readlineparseandbindbind e readlineparseandbindbind rlcomplete else readlineparseandbindtab complete add history import os histfile ospathjoinosenvironhome pyhist try readlinereadhistoryfilehistfile except ioerror pass import atexit atexitregisterreadlinewritehistoryfile histfile del histfile
before upgrading lion i tab complete working python shell via terminal following instructions possible tab complete working since upgrading lion i unable get tab complete working terminal session python i followed instructions letter still work is difference readline module lion hooking tabcomplete option longer seems work i wondering terminal ignoring readline python python version edit by tab complete i mean i could something like following django import mymodel mymodelobjectsatab complete
3
i completely understand algorithm looks like code hangs loop true selection randomrandrangeselfpool selection selfpoolindex index index index break it gets point never get value index index this could either indicate mistake somewhere code situation meets condition you could try putting cap number iterations example iters iters selection randomrandrangeselfpool selection selfpoolindex index iters index index break iters deal able identify couple
i implemented simple genetic algorithm python code import random ings w su su sy sy sy sy sy mutationrate crossoverrate iterations file open dlogfiletxt class ingredient def initself n p mi selfname n selfprice p selfmin mi selfmax selfperc randomrandrangeselfmin selfmax class drink def initself selfing ingredientx x ings selfnormalize selffitness selfevaluate def normalizeself sum x selfing sum xperc sum offset sum offset index randomrandrangelenselfing val selfingindexmax selfingindexperc threshold randomrandrangeval val else threshold threshold threshold offset else offset selfingindexperc threshold offset threshold sum offset sum offset index randomrandrangelenselfing val selfingindexperc selfingindexmin threshold randomrandrangeval val else threshold threshold threshold offset else offset selfingindexperc threshold offset threshold def evaluateself fitness x selfing fitness xperc xprice return fitness class geneticalgorithm def initself selfdrinklist drink x range selfpool def mutateself index ing ing randomrandrange randomrandrange ing ing ing randomrandrange ptr selfdrinklistindexing ingthr ptringmax ptringperc ingthr ptringperc ptringmin ingthr amp ingthr change randomrandrangeingthr ingthr ingthr else ingthr ptringperc change ptringperc change def crossoverself index index ing ing randomrandrange randomrandrange ing ing ing randomrandrange ptr selfdrinklistindexing ptr selfdrinklistindexing resultindex randomrandrangelenselfdrinklist true resultindex randomrandrangelenselfdrinklist resultindex resultindex break bias ptringperc ptringperc else bias maxchange minptringperc ptringmin ptringmax ptringperc ptringmax ptringperc ptringperc ptringmin maxchange change randomrandrangemaxchange ptringperc change ptringperc change ptringperc change ptringperc change selfdrinklistresultindexing ptr selfdrinklistresultindexing ptr bias maxchange minptringmax ptringperc ptringperc ptringmin ptringperc ptringmin ptringmax ptringperc maxchange change randomrandrangemaxchange ptringperc change ptringperc change ptringperc change ptringperc change selfdrinklistresultindexing ptr selfdrinklistresultindexing ptr def rouletteself sum lst x selfdrinklist sum xfitness lstappendsum return lst def selectoneself selection randomrandrangeselfpool index selection selfpoolindex index return index def selectcoupleself selection randomrandrangeselfpool index index selection selfpoolindex index true selection randomrandrangeselfpool selection selfpoolindex index index index break return index index def saveself text filewritetext x selfdrinklist xing filewrite min strymin max strymax value stryperc n filewrite nn filewrite npopulation fitness strselfcalculatepopulationfitness nnnn def runself filewritegenetic algorithmnnattributes valuesn mutation rate strmutationrate ncrossover rate strcrossoverrate niterations striterations ningredientsnn strings selfsave nnfirst populationnn cnt rangeiterations selfupdatefitness selfpool selfroulette randomrandom mutationrate index selfselectone selfshowfitness mutation iteration strcnt selfmutateindex selfupdatefitness selfshowfitness results randomrandom crossoverrate index index selfselectcouple selfshowfitness crossover iteration strcnt selfcrossoverindex index selfupdatefitness selfshowfitness results selfsave final populationnn def calculatepopulationfitnessself sum x selfdrinklist sum xfitness return sum def updatefitnessself x selfdrinklist xfitness xevaluate def showfitnessself text lst xfitness x selfdrinklist sumlst filewritetext n strlst strall n to run i create instance geneticalgorithm launch run method the problem low level iterations program works less fine i set iteration example seems fall infinite loop suspend random iteration logfile updated anymore program stop happenes random iteration what cause ps can suggest changes coding style i quite new python know conventions yet
1
i two methods handle one production one development in development append path apps settingspy in case i main project hgdjangoproject apps hgdjangoapps so i use devel syspathinsert ospathjoinospathdirnamefile apps i also use production method development box this method knock effect letting roll back recent production version simply commenting line path insertion settingspy in production i install apps using distutils i control deployment per server multiple projects running server access you read distutils setup scripts then install simply setuppy install
i starting first large django project realized default directory structure going work well i saw question answer decided implement something similar large django application layout what i need make something like work how i change django looks appsmodules
1
python works automatically deep directory structures that porbably find instructions ithere instructions get classes models work if want module folder yourprojectappsfirstapp add installedapps adding line appsfirstapp you add initpy file directories recognized python packages when import classes simply use yourprojectappsfirstappfilename import yourclass you also make sure template directories listed templatedirs
i starting first large django project realized default directory structure going work well i saw question answer decided implement something similar large django application layout what i need make something like work how i change django looks appsmodules
1
i thinking easiest way go use string method endswith this method works follows blacklisted foocom email xfoocom emailendswith foocom true email xsubdomainfoocom emailendswith foocom true so return true domain email whatever ends foocom as see include subdomains foocom conveniently also pass tuple endswith construct tuple blacklisted domains could something like blacklisted foocom barcom email xbarcom emailendswithblacklisted true this even benefit able blacklist subdomains others blacklisted foocom barcom subbaznet emailbad xsubbaznet emailbadendswithblacklisted true emailgood xgoodbaznet emailgoodendswithblacklisted false edit in response avaris comment in order make sure end situation blacklisted barcom bazcom email xfoobarcom emailendswithblacklisted true you included blacklisted list barcom barcom the result blacklisted barcom barcom bazcom bazcom email xfoobarcom emailendswithblacklisted false this obviously work at point i would say method versus regex matter preference while i try avoid regex costs might way go
i list emails domains i trying filter blacklist for email easy since i simply compare emails directly domains emails subdomains etc need matched well foocom domain i would need filter xfoocom xsubdomainfoocom how typically done via regex splitting email appropriate strings
2
one option add logging top foo indicate called need add lines def foo import traceback print foo called tracebackextractstacklimit previous foo code instead logging may find useful maintain global dictionary keep track count many times foo called different places
i using python hotshot profiler tells one methods foo called n times n larger number i expecting is way get detail foo called ideally listing module names line numbers i use grep my codebase contains lots calls foo i want find ones actually executed particular conditions i set profiler
1
if ready follow longer term approach i would advise go macports package manager software packaged works i followed approach successfully mac os x lion you basically first install macports package manager install programs like explained site sudo port install python pynumpy pyscipy pymatplotlib pyipython one advantage macports approach touch mac os x original software programs stored optlocal along programs applicationsmacports like gimp python idle the install procedure put optlocal front path automatically use macport programs instead installed default mac another advantage macports automatically downloads additional necessary programs dependencies their packages quite uptodate many k time writing so macports route access many additional programs side note i long experience another package manager mac os x fink i find macports simpler robust uptodate so i heartily recommended ps i believe also create new python macports command sudo port select python python ipython sudo port select ipython ipython these commands effect define version python ipython called use python ipython commands shell pps jd long i tried following instructions may possibly versions possibly idiosyncrasies mac i also run sudo port install pytornado pyzmq order get fully functioning ipythonnotebook stack working
what could i done instead order get items working together should i move everything windows i prefer reliable way okay happened i wanted install numpyscipy onto mac runs unfortunately numpy ver supports python i go install python but python work appicon bounces automatically quits this strange retrospect i heard python numpy ships mac i tried using sample code numpy website failed now real bind i eventually found httpstronginferencecomscipysuperpack which somehow installs numpy scipy matplotlib ipython pandas well pymc alpha it seemed like worked numpy work example code provided python but i working practice problems i found matplotlib working anymore the python launcher i think python launcher appicon says python name bounces app tray eventually freezes i worried could i matplotlib installed i followed instructions clean uninstall matplotlib followed installation scipysuperpack still fails way now i done clean install matplotlib hopes works and i import pylab throws ton error messages any advice would greatly appreciated
3
the number seconds datetimetimedelta x given timedeltatotalseconds xtotalseconds this function introduced python for older versions python compute totalseconds xdays xseconds xmicrosecondse
how i find number seconds since beginning day utc timezone python i looked docs understand get using datetimetimedelta
3
here one way datetime import datetime time utcnow datetimeutcnow midnightutc datetimecombineutcnowdate time delta utcnow midnightutc print deltaseconds careful edit as suggested want microsecond precision potentially crossing hour period ie deltadays use totalseconds formula given unutbu print deltatotalseconds print deltadays deltaseconds deltamicroseconds e
how i find number seconds since beginning day utc timezone python i looked docs understand get using datetimetimedelta
3
this would simplest way i think f foosubdomainbarcom joinfsplit barcom it use regex one line readable pull domain name added benefit caring domain com net whatever then check extracted domain blacklisted table edit ok couk domains et al import def getaddremailaddr parts resplitr emailaddr return joinparts parts co else getaddr foosubdomainbarcom barcom getaddr foosubdomainbarcouk barcouk getaddr foobarcom barcom edit wilduck pointed may use cases want filter specific subdoamins others ie communityebaycouk i figured may want blacklist specific email addresses without needing separate table ie exgirlfriendgmailcom here solution def isinblacklistaddr check addr list db table return true false def addrisblacklistedaddr addr return false isinblacklistaddr return true sliced joinaddrsplit addr else return addrisblacklistedsliced so deconstructing email address beginning end checking part blacklist obviously get answer single query filter single email addresses subdomains domains way top level domains inclined you queries per email average kill huge blacklist
i list emails domains i trying filter blacklist for email easy since i simply compare emails directly domains emails subdomains etc need matched well foocom domain i would need filter xfoocom xsubdomainfoocom how typically done via regex splitting email appropriate strings
1
what i keep sublists match items match list def matchallthelist tomatch return sublist sublist thelist allitem sublist item tomatch you speed using set def matchallthelist tomatch matches settomatchissubset return sublist sublist thelist matchessublist
given twodimensional list i would like find everything contains sublist i realize i something like psuedopython kosher def matchallthelisttomatch resultlistthelist nmatch tomatch nresult result nmatch nresult resultremovenresult return result but seems kinds bad it seems unlike python code i seen dealt far besides i making changes list iterating i read good thing also seems horribly inefficient tomatch length greater three purposes length thelist unknown could quite large any help greatly appreciated thanks advance
2
another option would epd epd free either install numpy scipy matplotlib ipython traits chaco window osx linux epd kitchensinkincluded version libraries science analysis available subscription basis free academics epd free free commercial use redistribution etc
what could i done instead order get items working together should i move everything windows i prefer reliable way okay happened i wanted install numpyscipy onto mac runs unfortunately numpy ver supports python i go install python but python work appicon bounces automatically quits this strange retrospect i heard python numpy ships mac i tried using sample code numpy website failed now real bind i eventually found httpstronginferencecomscipysuperpack which somehow installs numpy scipy matplotlib ipython pandas well pymc alpha it seemed like worked numpy work example code provided python but i working practice problems i found matplotlib working anymore the python launcher i think python launcher appicon says python name bounces app tray eventually freezes i worried could i matplotlib installed i followed instructions clean uninstall matplotlib followed installation scipysuperpack still fails way now i done clean install matplotlib hopes works and i import pylab throws ton error messages any advice would greatly appreciated
3
access methods different inheritance chain you call raw function method instance fix inheritance chain instead
hi trouble passing variablesdoing functions classes right i something like class def hi print class class def hi print class class def hi print class lets say class i would like execute function class how i go i googling awhile much success except finding images snakes any help problem would greatly appreciated
2
venuessearch supports querying rectangles addition circles specify sw ne params instead request you also specify intentbrowse get back best results area weighted proximity region center httpsdeveloperfoursquarecomdocsvenuessearchhtml this still support arbitrary polygons exhaustive retrieval venues return best region step closer looking
i want retrieve sq venues specific area now i get venues like thishttpsapifoursquarecomvvenuessearchll geopoint i pass radius argument area shape for backend i use django
1
what run cakephp app standard lamp web host access gae data store rest rpc web service this bad idea already cakephp frontend deals rpcs backend cake app stores models mysql could take considerable effort adapt itcakephp models abstract storage method using datasource class you might able find datasource class uses rest rpc however considerable investment cakephp controllers templates i would suggest simply building app entirely gae
i thinking create webapplication cakephp consuming python appengine webservice but install cakephp etc i need configure database appengine uses another kind datastorage different mysql etc i thinking store data appengine using python webservices cakephp application comunicating webservice insert retrieve data is good resource unpossible obs also opened possibility developing webapplicaiton completely python running appengine if anyone good resource thanks
1
it seems png file really value stored white pixel instead i assume something fact photoshop reality works bits bit mode small inaccuracy saving bit greyscale images
i writing script check image normalized i using python png module analyze image to test i created bit image consisting pixels line black white pixel photoshop my script correctly identifies black pixel gives different value i expecting white pixel i understand happens is something wrong script related way photoshop saves image minimalistic test png image httpiimgurcomdfpng script usrbinpython import sys import png httpspypipythonorgpypipypng lensysargv print invalid number arguments lensysargvnusage python getminmaxcolorpy pngfile sysexit pngfilepath sysargv f openpngfilepath rb r pngreaderfilef k rread bitdepth k bitdepth none bitdepth k bitdepth absmaxcolor bitdepth maxcolor mincolor absmaxcolor print content line k color line print color color maxcolor maxcolor color color mincolor mincolor color fclose print n print min color mincolor print max color maxcolor max absmaxcolor mincolor maxcolor absmaxcolor print image normalized else print image normalized
1
i think closer want fin readfiledb categorydict defaultdictdict automatically create subdict line fin itemdict new innermost dict every item iteminstance setiteminstancesline itemdictiteminstanceproductid iteminstance categorydictiteminstancecategoryid itemdict
how i create nested dictionary python so i want data form categoryid productid productinstanceprodid instance basically something like lets say i want check whether productid category i dicthaskey true false my bad code fin readfiledb categorydict defaultdictlist itemdict line fin iteminstance setiteminstancesline itemdictiteminstanceproductid iteminstance categorydictiteminstancecategoryidappenditemdict edit example dict pid pinstance pid pins pinthiscatid isntance thanks
3
dicts python basically always collection items item key value separated colon item separated next comma an item cannot one key value collections keys values looking second example dict pid pinstance pid pins pinthiscatid isntance outer dict needs another comma end first item key second key additionally quite clear instance meant mean often case methods objects passed object first parameter convention called self given name sometimes done reduce confusion metaclasses finally bare words pid forth rarely valid unless variable name assigned earlier attribute another object possibly selfpid i know problem
how i create nested dictionary python so i want data form categoryid productid productinstanceprodid instance basically something like lets say i want check whether productid category i dicthaskey true false my bad code fin readfiledb categorydict defaultdictlist itemdict line fin iteminstance setiteminstancesline itemdictiteminstanceproductid iteminstance categorydictiteminstancecategoryidappenditemdict edit example dict pid pinstance pid pins pinthiscatid isntance thanks
1
well bug report bug tracker exactly documentation though ah one even better okay possibly best one yet
the code x def f execx printx f runs python python prints different results is change documented anywhere a pointer mailing list discussion would also fine i ask purely curiosity
1
with ubuntu unity desktop environment ie ubuntu need whitelist application there different ways using gsettings application command line i get programs like skype showing system tray custom apps use wxpython
there tray unity ubuntu how i make icon appear somewhere unity wxtaskbaricon appear anywhere thanks
3
add import os projectroot ospathabspathospathdirnamefile settings py following managepy syspathinsert joinsettingsprojectroot apps syspathinsert joinsettingsprojectroot lib include installed apps would project root installedapps local apps myapp local libs pistondev allows bit freedom move apps around without redeclare imports
i starting first large django project realized default directory structure going work well i saw question answer decided implement something similar large django application layout what i need make something like work how i change django looks appsmodules
1
class needs functions class class could double inheritance class one def functself print i defined class one selfdata one class two def functself print i defined class two selfdata two class threeone two def functself print i defined class three selfdata three object created class three able call funct funct funct also object version selfdata selfdata selfdata ob three obdata prints one obfunct prints i defined class one now hand want function subclass call method superclass done class one def functself print class one class twoone def functself onefunctself ob two obfunct prints class one hope helps
hi trouble passing variablesdoing functions classes right i something like class def hi print class class def hi print class class def hi print class lets say class i would like execute function class how i go i googling awhile much success except finding images snakes any help problem would greatly appreciated
2
a fast solution query catalog like client xmlrpclibserverproxy httpuserpasswordblahcomplone completepath joinclientgetphysicalpath sitesngpathtofolder lenclientportalcatalogsearchresultspathcompletepath return true another solution could traverse folders structure like client xmlrpclibserverproxy httpuserpasswordblahcomplone path sitesngpathtofolder subdirs pathsplit dir client subdir subdirs subdir dirobjectids dir dirsubdir else return false return true edit i ammend answer i tried interact portalcatalog via xmlrpc actually easy my two options good use via xmlrpc so taking example transmogrifyploneremote simple option different implementation checking remote folder exists try path httpuserpasswordblahcomplonesitesngpathtofolder xmlrpclibserverproxypathgetphysicalpath return true except xmlrpclibfault e return false
i use xmlrpclib wsapiplone connect plone client xmlrpclibserverproxy httpuserpasswordblahcomplone method check folder plone exists url something like clientexists sitesngpathtofolder what i bit cheating try clientgettypes sitesngpathtofolder except exception means folder create clientpostobjectfolder i dont admin rights look methods list i told somewhere plone site i need admin i want keep ask question method available plone methods list anywhere web
1
this i make executable script it take eggs anything like account it simple script i want able execute i assuming using linux usrbinenv python import sys def main do something whatever processing need make happen don shove everything main break testable functions whatever function returns exit code interpreter ie script because main called sysexit behave differently depending return so return none returned if return integer return code used anything else printed console error returned anerroroccurred return i returning string printed returned otherwise success returned return this true script run interpreter imported another module name main main return success something else usually error sysexitmain now permissions set correctly execute script one thing realize script processed line executed interpreter this true regardless processor gets that importing script module executing script essentially work execute line module once realize script simply executing runs realize order functions matter a function declaration function declaration it call function matters so general layout script looks like def func pass def func pass def main return name main sysexitmain you create functions want use first use hope helps
i python script i wondering i make executable words i run using shell like bash i know first thing stick first line usrbinenv python i need example functions specific order ie main one top bottom what i need keep extension py python file i call function dosomething to short could provide simple guide important points someone take account make python file executable
1
found solution chatting automatedtester irc currently python webdriver implementation ignores selfbaseurl value get url need use full url bug report filed likely updated near future webdriver version
just title says i copy selenium installed svn repo when i import run things console everything works i try run unittest even one exported directly selenium ide open browser hang without trying open url additional details os ubuntu python browser firefox tried httpunit though i kept getting illegal character errors code import unittest import time import selenium import webdriver seleniumwebdrivercommonby import by seleniumcommonexceptions import nosuchelementexception localconfig import baseurl basefolder driver baseurl httplocalhost basefolder dirtosite driver firefox class checksitemapunittesttestcase def setupself global baseurl global driver driver firefox selfdriver webdriverfirefox elif driver httpunit selfdriver webdriverremotedesiredcapabilitieswebdriverdesiredcapabilitieshtmlunit else raise exception driver set selfdriverimplicitlywait selfbaseurl baseurl print selfbaseurl selfverificationerrors def getsitemapself global basefolder global driver print basefolder driver selfdriver op ssitemapxml basefolder driver httpunit op ss selfbaseurl oplenop print op drivergetopreplace print hello world urls print driverpagesource r recompiler href match rfinditerdriverpagesource urlsappendmatchgroup lenurls r recompiler locloc redotall match rfinditerdriverpagesource urlsappendmatchgroupstrip return urls def testchecksitemapself global driver driver selfdriver urls selfgetsitemap print urls url urls driver httpunit drivergeturl else drivergeturlreplaceselfbaseurl researchrphp line driverpagesource selfverificationerrorsappend php error url def iselementpresentself try selfdriverfindelementbyhow valuewhat except nosuchelementexception return false return true def teardownself selfdriverquit print selfverificationerrors selfassertequal selfverificationerrors name main unittestmain ideas
1
because called supergoblin selfinitself power maxhp magic maxmp speed name without difficulty you probably also want inherit like class enemyobject make sure enemy newstyle class x i guess must considering old way used super here simpler example class animalobject def initself talk print init animal talk class catanimal def initself talk meow print init cat supercat selfinittalk name main tom cat outputs init cat init animal meow edit well following work perhaps old class definitions cached interpreter try running fresh interpreter class enemyobject def initself difficulty power maxhp magic maxmp speed name selfpower power difficulty selfhp selfmaxhp maxhp difficulty selfmagic magic difficulty selfmp selfmaxmp maxmp difficulty print raaarghh i formidable formatname class goblinenemy def initself difficulty power maxhp magic maxmp speed namegoblin supergoblin selfinitdifficulty power maxhp magic maxmp speed name name main g goblinname user goblin
i trying make class generic init values defaults subclasses class enemy def initself difficulty power maxhp magic maxmp speed name selfpower power difficulty selfhp selfmaxhp maxhp difficulty selfmagic magic difficulty selfmp selfmaxmp maxmp difficulty class goblinenemy def initself difficulty power maxhp magic maxmp speed name goblin supergoblin selfinitself power maxhp magic maxmp speed name however i try make goblin object without full number default values like i put value difficulty tells i need full arguments even though rest given default values is reason i i something wrong
2
do chance recreate database it seems might something wrong as side note you call datetimenow createdat already set default field datetimenow
i basic model django class casemodelsmodel name modelscharfieldmaxlength createdat modelsdatetimefielddefaultdatetimenow updatedat modelsdatetimefielddefaultdatetimenow def saveself selfcreatedat none selfcreatedat datetimenow selfupdatedat datetimenow supercase selfsave class meta dbtable u cases because i specify pk django took care i see field database called id marked primary key autoincrement i find odd getting warning since everything cool db model end the error mysqlexceptionswarning warning field id default value my work around saving set id it kills warning id gets set properly anyway since mysql handles case case caseid ugly workaround warning field id default value casename requestpostu casename casesave the issue solution it ugly the new pk inaccessible saving makes impossible serialize properly does anyone know fix i running python djangoversion final mysql ver distrib appledarwin using readline mysqlpythonpymacosxxegg and create table looks like create table cases id int not null autoincrement name varchar not null createdat datetime not null updatedat datetime not null primary key id enginemyisam autoincrement default charsetlatin
3
your save method really necessary use arguments datefieldautonow datefieldautonowadd those arguments handle createdat updatedat attributes datefieldautonow automatically set field every time object saved useful lastmodified timestamps datefieldautonowadd automatically set field object first created useful creation timestamps try using default save method hope helps more info autonow autonowadd httpsdocsdjangoprojectcomendevrefmodelsfieldsdatefield
i basic model django class casemodelsmodel name modelscharfieldmaxlength createdat modelsdatetimefielddefaultdatetimenow updatedat modelsdatetimefielddefaultdatetimenow def saveself selfcreatedat none selfcreatedat datetimenow selfupdatedat datetimenow supercase selfsave class meta dbtable u cases because i specify pk django took care i see field database called id marked primary key autoincrement i find odd getting warning since everything cool db model end the error mysqlexceptionswarning warning field id default value my work around saving set id it kills warning id gets set properly anyway since mysql handles case case caseid ugly workaround warning field id default value casename requestpostu casename casesave the issue solution it ugly the new pk inaccessible saving makes impossible serialize properly does anyone know fix i running python djangoversion final mysql ver distrib appledarwin using readline mysqlpythonpymacosxxegg and create table looks like create table cases id int not null autoincrement name varchar not null createdat datetime not null updatedat datetime not null primary key id enginemyisam autoincrement default charsetlatin
1
save method sometimes uses additional arguments keywors arguments dont handle i sure may fix problem def saveself args kwargs selfcreatedat none selfcreatedat datetimenow selfupdatedat datetimenow supercase selfsaveargs kwargs
i basic model django class casemodelsmodel name modelscharfieldmaxlength createdat modelsdatetimefielddefaultdatetimenow updatedat modelsdatetimefielddefaultdatetimenow def saveself selfcreatedat none selfcreatedat datetimenow selfupdatedat datetimenow supercase selfsave class meta dbtable u cases because i specify pk django took care i see field database called id marked primary key autoincrement i find odd getting warning since everything cool db model end the error mysqlexceptionswarning warning field id default value my work around saving set id it kills warning id gets set properly anyway since mysql handles case case caseid ugly workaround warning field id default value casename requestpostu casename casesave the issue solution it ugly the new pk inaccessible saving makes impossible serialize properly does anyone know fix i running python djangoversion final mysql ver distrib appledarwin using readline mysqlpythonpymacosxxegg and create table looks like create table cases id int not null autoincrement name varchar not null createdat datetime not null updatedat datetime not null primary key id enginemyisam autoincrement default charsetlatin
1
django uses wsgi designed synchronous processing want easy that said one guy seems done implementation asynchronous responses that probably efficient reliable least possible
say i want ajax get request goes django view instead returning response client could i store request dictionary list forget leaving ajaxclient waiting response then say something happens server i use another view function retrieve request create response send client this kind like ajax push approach is possible done django efficient
1
no cons implementation detail lisplike languages exist meaningful sense python
is equivalent cons python version if built or i need easyinstall get module
1
you quite trivially define class behaves much like cons class consobject def initself car cdr selfcar car selfcdr cdr however heavyweight way build basic data structures python optimised i would expect results much cpumemory intensive something similar lisp
is equivalent cons python version if built or i need easyinstall get module
1
note python lists implemented vectors linked lists you could lstinsert val operation on if want data structure behaves like linked list try using deque
is equivalent cons python version if built or i need easyinstall get module
2
in python typical use arraybased list class lispstyle linked lists but hard convert def consseq result none item reversedseq result item result return result def iterconsseq seq none car cdr seq yield car seq cdr cons none itercons generator object uncons xd list
is equivalent cons python version if built or i need easyinstall get module
3
that standard precision floats python for arbitrary precision use bigfloat package
how i print digits float python right print sqrnewton sqrnewton newton algorithm square roots returns float gives many digits decimal place i get
3
they encrypted use smtp tls ssl
when i send credentials using login method python smtp library go wire encrypted plaintext
2
i fixed filtering warning import warnings warningsfilterwarningsignore field id default value now saving serialization looks good
i basic model django class casemodelsmodel name modelscharfieldmaxlength createdat modelsdatetimefielddefaultdatetimenow updatedat modelsdatetimefielddefaultdatetimenow def saveself selfcreatedat none selfcreatedat datetimenow selfupdatedat datetimenow supercase selfsave class meta dbtable u cases because i specify pk django took care i see field database called id marked primary key autoincrement i find odd getting warning since everything cool db model end the error mysqlexceptionswarning warning field id default value my work around saving set id it kills warning id gets set properly anyway since mysql handles case case caseid ugly workaround warning field id default value casename requestpostu casename casesave the issue solution it ugly the new pk inaccessible saving makes impossible serialize properly does anyone know fix i running python djangoversion final mysql ver distrib appledarwin using readline mysqlpythonpymacosxxegg and create table looks like create table cases id int not null autoincrement name varchar not null createdat datetime not null updatedat datetime not null primary key id enginemyisam autoincrement default charsetlatin
1
here resources relied troubleshoot getting scientific python rig snow leopard lion hyperjeff blog first used reference snow leopard lion it excellent thorough stepbystep guide installing bit numpy scipy matplotlib mac os x though seemed equally helpful this survival guide couple things going stepbystep guide makes assumptions instance first step configuring bashprofile appropriate environmental variables deployment target package config paths cflags actually supplies code individual shell commands retrievedownload configure build install three packages dependencies addition blog post supplies diffs config files author recommends edit prior installation vetted community perhaps comments original post nearly author responded cases revised text original guide addition comments cover quite edge cases washington university astrology department this began panther actually date bothered revise document cases revision trivial change eg this resource useful discussed detail always seems problem menumpy scipy ok matplotlib fails fails libpng libjpeg et al some empirically likely causes failed install numpyscipymatplotlib unfortunately based personal experience libpng freetype zlib matplotlib dependencies one possible source problems source caused matplotlib versions compile default libpng version yet version developer likely mac version included x shipped versions xcode version this issue aside good idea use xquartz rather xll supplied xcode likewise past applesupplied x included broken version freetype v particular matplotlib default config straightforward way opt defaults edit makeosx setupcfgtemplate files included matplotlib source toplevel directory the posts hyperjeff blog supine sublime blog helpful set issues applesupplied fast fourier transform library various issues believe one persistent lack fortran bindings fft library version supplied mac developer tools in event difficult get latest version gold standard fft libraries fftw install source
what could i done instead order get items working together should i move everything windows i prefer reliable way okay happened i wanted install numpyscipy onto mac runs unfortunately numpy ver supports python i go install python but python work appicon bounces automatically quits this strange retrospect i heard python numpy ships mac i tried using sample code numpy website failed now real bind i eventually found httpstronginferencecomscipysuperpack which somehow installs numpy scipy matplotlib ipython pandas well pymc alpha it seemed like worked numpy work example code provided python but i working practice problems i found matplotlib working anymore the python launcher i think python launcher appicon says python name bounces app tray eventually freezes i worried could i matplotlib installed i followed instructions clean uninstall matplotlib followed installation scipysuperpack still fails way now i done clean install matplotlib hopes works and i import pylab throws ton error messages any advice would greatly appreciated
1
i know mechanism perform screen recording python however may able use python control one many existing screen recording programs recorditnow recordmydesktop byzanz istanbul vncswf pyvncswf
is library making screen recorder application python think would fun make somthing like library work linux im using ubuntu thanks
1
i sure operating system using bigfloat requires mpfr gmp libraries already exist computer it may easy use windows there two multiple precision libraries available support windows mpmath written pure python stable well documented gmpy currently active development the next release stable api famous last words if bigfloat works great it welldesigned documented package disclaimer i maintain gmpy helped mpmath
how i print digits float python right print sqrnewton sqrnewton newton algorithm square roots returns float gives many digits decimal place i get
2
to honest i skipped helloworld bit went straight lazy pirate pattern clientserver that one bugs python version client retry loops least something i added print statements got proper clientserver communication going after i wrote memcache kind server using json objects message bodies eg cmd get key albert jones a couple months later i needed persistent keyvalue server work multiprocessing system i turned existing code sqlite keyvalue server by keyvalue i mean entire schema server one table kvstore two columns key val i server accessed client processes time hitches i also tried hand writing server uses actual memcache protocol using asynchat far complex using zeromq so advice move if hello world example work try different one ps if want portable python distro runs fedora distro look httpsgithubcomwavetossedpybuild currently build ubuntu system resulting tarball includes shared library dependencies runs redhatrpm style distros suserpm style distros it plenty examples building rd party libraries problems adding favourite modules python distro
i trying get zeromq working python fedora as needed python i installed activepython i installed pyzmq using easyinstall installed fine when i run hello world example httpzguidezeromqorgpyhwclient it blocks socketrecv i read issues send messages faster client receive cause client miss first message so i sure whether expected behaviour least possible behaviour i would thought simple hello world example would worked box what i trying figure whether code installation causing problem anyone come across something similar
1
contacted author boto learned getcanonicaluserid sconnection class this give canonical user id credentials associated connection the connection used operation eg listing buckets very awkward possible
does canonical user id exist federated user created using sts when using boto i need canonical user id grant permissions bucket here quick tour code i successfully created temporary credentials using boto sts module using master account gives back federateduserarn federateduserid packedpolicysize accesskey secretkey sessiontoken expiration then i create bucket using boto bucket selfsconnectioncreatebucket sstore appid now i want grant permissions i left two choices boto addemailgrantpermission emailaddress recursivefalse headersnone addusergrantpermission userid recursivefalse headersnone displaynamenone the first method option since email attached federated user i look second here second parameter userid the canonical user id associated aws account granting permission but i seem find way come federated user do canonical user ids even exist federated users am i overlooking easier way grant permissions federated users
1
solution explicitly invoke python using python filepy described httpwwwvelocityreviewscomforumstproblemsrunningvirtualenvunderwindowshtml reason python registered py windows invoke virtualenv
i virtualenv installed windows in cmd run python look syspath see virtualenv path included run managepy django i see virtualenv path virtualenv working django server why
1
my money misspelled name i notice error message omnicloudappaccounts omnicloudappuser second table uses singular there second table like chance omnicloudappusers also using mixed case identifiers postgresql great source reputation so it bite sooner later victims folly regulars any table name maybe forgot double quotes omnicloudappuser somewhere omnicloudappuser it either transaction saving user committed yet can create user accounts yet check ends right database table right id edit tools diagnose problem if know users created question foreign key constraint useridrefsidfbceced look right place same database same schema same table to find tables exists database try following query necessary privileges select nnspname as schemaname crelname as tablename crelhastriggers creltuples from pgcatalogpgclass c left join pgcatalogpgnamespace n on noid crelnamespace where crelname user and crelkind r and nspname pgcatalog shows tables schemas user name case insensitive plus table triggers could cause problem many rows estimate updated analyze might give lead you also use metacommand standard command line client interactive terminal psql i would run test case postgres server log everything gets set parameter purpose set logstatement the manual loggingparameters logstatement enum controls sql statements logged valid values none ddl mod statements the manual set parameters
go edit calling following adduser function viewspy i save user first id automatically created django upon insert primaryforeign key accounts passwords adding user seems working fine gets accountsuseru following error throws integrityerror adduser insert update table omnicloudappaccounts violates foreign key constraint useridrefsidfbceced detail key userid present table omnicloudappuser but key since saved user db def adduserrequest username requestpost username password requestpost password u userobjectscreateuserusername requestpost email password usave accountsuseru p passwordsuseru asave psave user authenticateusernameusername passwordpassword user none userisactive authloginrequest user return httpresponseredirects uid else return httpresponseredirectaccountinvalid edit here beginning initialization accounts djangodb import models djangocontribauthmodels import user class accountsmodelsmodel user modelsforeignkeyuser edit i realized going admin page it complains database adding rd user adding th user throws error user id duh i see anything code would cause search userid ideas to war chest
2
i use sessions store last ping datetime session parameter don worry database hits certain point would feel getting many switch session storage cache make application robust cacheflushing one friends used host relatively popular djangobased social networking game pretty much standard virtual private server took forced switch cachebased sessions
the closest example case django ajax chat application the rooms need keep list active users aside displaying list users within chat given room might maximum number active users new users need blocked entering room currently i chat client page calling poll view every second via ajax the poll view returns text room i figure poll also type pinging adding users activeuser mm field room object i place far what i need next something drops users activeuser list kind timeout i imagine two ways i wondering would efficient app needs accurate second tenfifteen seconds using cookies sessions middleware la thread however seems method work momenttomoment info another model explicit usersrooms table datetime field time updated upon creation every ping following write function cleans old ones that i think i trying figure whether hitting mysql every second every user every room good idea wondering second indeed best option task thanks
2
mygroup groupobjectsgetnamemygroup mykeyword mykeywordsobjectscreatenamemykeyword mylistassoc mylistassocgroupmygroup mylistassocsave mylistassockeywordaddmykeyword if want remove association use removemykeyword instead addmykeyword however need intermediary model set relation groups keywords
how i create association mylistassoc how would i delete class groupmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname class mykeywordsmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname class mylistassocmodelsmodel group modelsforeignkeygroup keyword modelsmanytomanyfieldmykeywords mygroup groupobjectsgetnamemygroup mykeyword mykeywordsobjectscreatenamemykeyword
1
you use generator expression instead list comprehension elem item item mylist item do something
is possible basically following python elem mylist elem do something elem note i want specifically avoid using map lambdas filter create second list gives boolean condition i want following elem item item mylist item do something the latter method requires construction boolean list in code mylist large basically simplest way would write elem mylist elem do stuff i specifically want one line if allinoneline make code actually different last example i gave fine i go
3
check ifilter function itertools
is possible basically following python elem mylist elem do something elem note i want specifically avoid using map lambdas filter create second list gives boolean condition i want following elem item item mylist item do something the latter method requires construction boolean list in code mylist large basically simplest way would write elem mylist elem do stuff i specifically want one line if allinoneline make code actually different last example i gave fine i go
1
you need many many relation something like class groupmodelsmodel name modelscharfieldmaxlength uniquetrue keywords modelsmanytomanyfieldmykeywords def unicodeself return selfname class mykeywordsmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname then use mm relation group groupobjectsgetname something keyw mykeywordsobjectsgetname somethingelse groupkeywordsaddkeyw groupkeywordsall groupkeywordsremovekeyw note it recommended name class singular mykeyword instead mykeywords
how i create association mylistassoc how would i delete class groupmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname class mykeywordsmodelsmodel name modelscharfieldmaxlength uniquetrue def unicodeself return selfname class mylistassocmodelsmodel group modelsforeignkeygroup keyword modelsmanytomanyfieldmykeywords mygroup groupobjectsgetnamemygroup mykeyword mykeywordsobjectscreatenamemykeyword
2
this looks like bug macports port python for sample works current macports python fails current macports python way reported macports automatically builds includes gdbm database manager python ports python includes berkeley db gdbm it looks like macports using db works fails using gdbm presumably macports port similar this investigated update if using uptodate macports installation likely problem reported httpbugspythonorgissue it looks like fix support latest gdbm beyond current macports version that fix applied python released macports folks backport python ports
i running python macports i attempting use shelve module i use successfully another dev machine different os etc i sure i may incorrectly any thoughts suggestions would greatly appreciated here error dbmerror db type could determined i searched error message found info i even tried force protocl see might help here interactive session python default oct gcc apple inc build darwin import shelve locker shelveopen myshelf protocol locker lockerclose exit python default oct gcc apple inc build darwin import shelve locker shelveopen myshelf protocol traceback recent call last file stdin line module file optlocallibraryframeworkspythonframeworkversionslibpythonshelvepy line open return dbfilenameshelffilename flag protocol writeback file optlocallibraryframeworkspythonframeworkversionslibpythonshelvepy line init shelfinitself dbmopenfilename flag protocol writeback file optlocallibraryframeworkspythonframeworkversionslibpythondbminitpy line open raise errordb type could determined dbmerror db type could determined
1
the second method fine fact use time the reason i putting answer infact something like work project years back turned although logging anything debug level production file cost creating debug message quite expensive impacting performance ie in production debug level message created boolean check instead in production debug messages created propagated logged file well fact setup logging the project pretty big calculation farm every ounce performance mattered case ever since might case hey thought would mention
in django settingspy defines debug whole project now my debug level independently configured settingspy how i use loggingdebug way settingsdebug loggingdebugdebug message way without checking settingsdebug loggingdebugdebug message what good practice i think use way since logging level already decides message logged but say way standard practice
1
here try ints except valueerror verr pass job handle contain anything convertible int except exception ex pass job handle exception occurred converting int
so i pretty stumped convert string int using tryexcept function does anyone know simple function i feel like i still little hazy string ints i pretty confident ints related numbers stringsnot much
3
it important specific exception trying catch using tryexcept block string abcd try intstring print except valueerror handle exception print please enter integer tryexcepts powerful something fail number different ways specify want program react fail case
so i pretty stumped convert string int using tryexcept function does anyone know simple function i feel like i still little hazy string ints i pretty confident ints related numbers stringsnot much
3
in typical wordcount example file name map file processing ignored since job output contains consolidated word count input files file level but get word count file level input file name used mappers using python get file name using osenvironmapinputfile command the list task execution environment variables the mapper instead emitting keyvalue pair hello also contain input file name processed the following emitted map inputtxt hello inputtxt key hello value now word counts particular file processed single reducer the reducer must aggregate word count particular file as usual combiner would help decrease network chatter mapper reducer also complete job faster check dataintensive text processing mapreduce algorithms text processing
i learning elastic mapreduce started word splitter example provided amazon tutorial sectioncode shown the example produces word count words input documents provided but i want get output word counts file names ie count word one particular document since python code word count takes input stdin i tell input line came document thanks usrbinpython import sys import def mainargv line sysstdinreadline pattern recompileazazazaz try line word patternfindallline print longvaluesum wordlower line sysstdinreadline except end file return none name main mainsysargv
3
the trunk version webdriversetwindowposition webdriversetwindowsize methods usrbinenv python import time contextlib import closing seleniumwebdriver import firefox pip install selenium closingfirefox browser browsersetwindowposition note might fail systems browsersetwindowsize timesleep
i wanted know maximize browser window using python bindings selenium webdriver
2
i exact problem last night i came across question mdash i also arch i guess problem could number different things solution i python version pythondisribute package installed therefore easyinstall easyinstall i believe case wrong version pythondistribute installed attempt previously install sphinx pacman installs version uninstalling sphinx subsequently unneeded dependencies pacman rsu pythonsphinx installing pythondistribute got right version easyinstall reinstalling sphinx easyinstall sphinx installation works expected if things depend pythondistribute process may little different but start trying remove pythondistribute work scrap last part it early morning i thinking straight pythondistribute pythondistribute seperate packages i believe coexist so problem need check pythondistribute install ensure use easyinstall install sphinx hope helps
i try create documentation project written python x sphinx tool i want use according official site last version compatible python my os archlinux linux distribution uses python default python package the installation configuration straight forward easyinstall u sphinx sphinxquickinstall i never asked choose x x python interpreter but i ask sphinx create documentation project code analyzed i wrote python x is sphinx ready python x did i make mistake
3
no matter point python interpreter going reading unobfuscated python bytecode from dead easy get back source code minus comments nonobvious layout this everybody says pretty much impossible obfuscate python the fact pretty much impossible obfuscate python implies good tools i afraid wishful thinking say i know done effectively tools probably best encrypt code standard encryption tools write little wrapper program language decrypts python runs program deletes unencrypted code done if want put way much effort could probably something c api embedding python interpreter c program feed unencrypted python interpreter memory rather files disk note schemes still relatively easy get around work want provide importable python modules rather whole programs which i expect find anyone already written tool
is existing python code obfuscating tool python please try teach python right choice i want hideobfuscate code or correct licenses protect code instead obfuscation update this question duplicate issue how i protect python code i simply ask tool obfuscate python nothing nothing less if none i wonder i get much feedback
3
there perl netepp package cpan implements lowlevel highlevel epp clients
do epp clientside implementations languages java exist i mostly interested c tcl client implementation also python perl
2
looking documentation syslastvalue friends their intended use allow interactive user import debugger module engage postmortem debugging without reexecute command caused error so interpreter debugging i suggest using syslastvalue script i suggest use sysexcinfo
should i prefer sysexcinfo syslastvalue friends syslasttype syslasttraceback
2
instead letting excelmicrosoft dictate store datetime would less trouble work rely standardobvious way things process objects according standards domain python way datetime objects inside pythonsqlalchemy sql way inside sqlite native datetime type instead float use apis necessary translation domains python talks sqlite via sqlalchemy python talks excel via xlrdxlwt python talks systems python glue using standard datetime types sqlite allows write sql without python involve standard readable way where date between and makes much sense where date between and it allows easily port another dbms without rewriting adhoc functions applicationdatabse needs grow using native datetime objects python allows use lot freely available well tested noneee embrace extend extinguish apis sqlalchemy one and i hope aware slight dangerous difference excel datetime floats mac windows who knows one clients would future submit excel file mac crash application actually worse suddenly earned million dollars error so suggestion use xlrdxlwt dealing excel python another package reading excel let sqlalchemy database use standard datetime types however insist continuing store datetime excel float could save lot time reuse code xlrdxlwt it functions converting python objects excel data viceversa edit clarity you issues reading database python class converts float python datetime you issues writing database sqlalchemy using native python functionsmodulesextensions trying force nonstandard type expecting standard python datetime exceldatetime type point view python float datetime although python uses dynamicduck typing still strongly typed it allow nonsensesilliness like adding integers string forcing float datetime at least two ways address declare custom type seems path wanted take unfortunately hard way it quite difficult create type float also pretend datetime possible yes requires lot study type instrumentation sorry grok documentation create utility functions should easier way imho you need functions floattodatetime converting data database return python datetime b datetimetofloat converting python datetime excel float about solution i saying could simplify life reusing xldatefromdatetimetuple xlrdxlwt that function convert datetime tuple year month day hour minute second excel date value install xlrd go pathtopythonlibsitepackagesxlrd the function xldatepy source well documented understanding
we sqlite databases datetimes actually stored excel format decent reason system standard representation choice sqlite databases may accessed multiple languagessystems have introducing python mix great success recent months sqlalchemy part the ability sqlite dbapi layer swiftly bind custom python functions sqlite lacks given sql function particularly appreciated i wrote exceldatetime type decorator works fine retrieving result sets sqlite databases python gets proper datetimes back however i real problem binding custom python functions expect input params python datetimes i thought bindparam i obviously missing something i cannot get scenario work unfortunately modifying functions convert excel datetimes python datetimes option neither changing representation datetimes database one systemlanguage may access the code selfcontained example run asis representative issue the custom function getmonth created fails receives raw data typeconverted data born column at end see i tried far errors spits is i trying impossible or different way ensuring bound function receives appropriate python type it problem i unable overcome far would great find solution import sqlalchemytypes types sqlalchemy import createengine table column integer string metadata sqlalchemysqlexpression import bindparam sqlalchemysql import select text sqlalchemyinterfaces import poollistener import datetime setup type decorator excelpython date conversions class exceldatetime typestypedecorator impl typesfloat def processresultvalue self value dialect lxdays int value lxsecs int roundvaluelxdays lxsecs lxsecs lxdays return datetimedatetimefromordinallxdays datetimetimedeltasecondslxsecs def processbindparam self value dialect value already excel float return value elif isinstancevaluedatetimedate return valuetoordinal elif isinstancevaluedatetimedatetime datepart valuetoordinal timepart valuehour valueminute valuesecond return datepart timepart time part day fraction create sqlite memory db via sqlalchemy def getmonth dt return dtmonth class connectionfactory poollistener def connect self dbapicon conrecord dbapiconcreatefunction getmonth getmonth eng createengine sqlitememory listenersconnectionfactory engdialectdbapienablecallbacktracebacks show better errors user functions meta metadata birthdays table birthdays meta column name stringprimarykeytrue column born exceldatetime column birthmonth integer metacreatealleng dbconn engconnect dbconnexecute insert into birthdays values jimi hendrix null demonstrate type decorator works get proper datetimes res dbconnexecute selectbirthdays tupleres u jimi hendrix datetimedatetime simple attempt blows attributeerror float object attribute month dbconnexecute textupdate birthdays set birthmonth getmonthborn involved attempt blows interfaceerror interfaceerror error binding parameter probably unsupported type dbconnexecute text update birthdays set birthmonth getmonthborn bindparamsbindparam born exceldatetime typemap born exceldatetime bornbirthdayscborn many thanks
1
does ossystem work import os ossystempathtoscriptsh
i trying run scripts python mac os i unable run scripts run bashsh scripts one idea i run bashsh from python mac os thanks help this scripts called runscriptsh i need run python script
2
get database group fairly easy piece code obviously adapt actual model schools schoolobjectsorderby name schooldict school schools firstletter schoolnamelower firstletter schooldict schooldictfirstletterappendschool else schooldictfirstletter school
i currently data model set school object name on primary page website i outputting school objects sorted alphabetically name i hoping would way django create index titles objects by i mean categorize school object first letter name this would prove useful i provide section titles potentially long list schools ideally instead returning school objects template i want manipulate sort objects way categorized dictionary arrays keys main dictionary letters alphabet excluding school names starting letter values arrays schools whose name starts first letter corresponding key this would make easy loop django templating system accomplish want section headers any help would greatly appreciated is native django or i going employ python logic
1
mainsysargv calls main content list sysargv respective arguments main method case equivalent mainsysargv mainsysargv sysargv depending length sysargv so call asterisk passes name first element list sysargv if call without asterisk passes name whole list sysargv
what star operator input argument list example def mainname datadir print name typename name main mainsysargv concretely i run program star operator prints name type str run without star mainsysargv prints name type list
1
the operator unpacks argument list it allows call function list items individual arguments for instance sysargv foo bar quux mainsysargv equivalent mainfoo bar quux
what star operator input argument list example def mainname datadir print name typename name main mainsysargv concretely i run program star operator prints name type str run without star mainsysargv prints name type list
3
this questions stale reference using ipython zeromq enabled take look vimipython older version shipped using plugin send lines whole files ipython execute also get back object introspection word completions vim like get objectenter objecttab ipython take look two screencasts plugin action post
i found ipython i report i deep love and affection immediate i think affair turn something lasting like one i screen ipython screen happen best friends triangular drama purely platonic mind the reason ipython hits soft spots much i generally like command prompts especially nixinspired prompts inspiration ksh csh yes chs monster prompt sport lots really good features bash zsh and ipython sure feel like home nix prompt rider mixing system shell python also really good idea plus course ipython helps lot solving python challenge riddles invaluable even now i love vim since i learnt vi back days turning back and i mac i choice now i like glue together ipython macvim workflow what i done far i start ipython using ipython e open macvim thus i edit ipython starts macvim filemodule loaded could look bit like in run foo this also imports foo anew hello world in edit foo editing done executing edited code this happens immediately hello world in run foo hello so world ok i think improved maybe way tie ipython macvim please share experiences of course use textmate fav editor i interested maybe lessons general
3
i go obfuscating approach i rather investigate alternative ways ship executable binary files instead bytecode tools known probably others httpwwwohlohnetppyc converts python c code compile httpwwwpyinstallerorg httpcxfreezesourceforgenet httpwwwpyexeorg windows httpsvnpythonmacorgpyapppyapptrunkdocindexhtml mac i know hackproof tools i think worth taking look edit damnit missed python part it little hard help write anything product os gui etc if also python code written code python already i suggest
is existing python code obfuscating tool python please try teach python right choice i want hideobfuscate code or correct licenses protect code instead obfuscation update this question duplicate issue how i protect python code i simply ask tool obfuscate python nothing nothing less if none i wonder i get much feedback
1
you tried use local variables class attributes try following changes class dobject def createself selffoo selfbar squirrels baz i insane head selffoo selfbar return baz class cd def createself superc selfcreate print selffoo selfbaz i cute yard selffoo selfbar ccreate
how i overload class methods i failed class dobject def createself foo bar squirrels baz i insane head foo bar return baz class cd def createself superc selfcreate baz i cute yard selffoo selfbar ccreate traceback attributeerror c object attribute foo
2
strin b script b compiler b cds b algo b timing arr strinstrip split res partstripb part arr res script compiler cds algo timing
i variable data data b script b compiler b cds b algo b timing i need convert remove occurrence b list how
1
not sure whether would help works sample initlist b script b compiler b cds b algo b timing resultlist strx x initlist or p resultlist xdecodeutf x initlist utf encoding used check decode function also may want take look following related so thread
i variable data data b script b compiler b cds b algo b timing i need convert remove occurrence b list how
2
b script b compiler b cds b algo b timing mapstr script compiler cds algo timing
i variable data data b script b compiler b cds b algo b timing i need convert remove occurrence b list how
2
here one way arguably pythonic if want parse byte string use struct module provided exact purpose import struct collections import namedtuple details namedtuple details name phone def lazyparsedata extract name phone data buffer if buffer could parsed parseerror raised try name structunpackfromdp lendata data phone structunpackfromdp lendatalenname data lenname except structerror raise parseerror return detailsname phone what i still find unpythonic throwing away useful structerror traceback replace parseerror whatever original tells wrong string latter tells something wrong
here quote httpstackoverflowcomusersgreghewgill answer good primer python slice notation python kind programmer fewer items ask for example ask contains one element get empty list instead error sometimes would prefer error aware may happen so error prefered pythonic way proceed is pythonic way rewrite example class parseerrorexception pass def safeslicedata start end start end assumed r datastartend lenr end start raise indexerror return r def lazyparsedata extract name phone data buffer if buffer could parsed parseerror raised try namelength orddata extractedname safeslicedata namelength phonelength orddata namelength extractedphone safeslicedata namelength namelength phonelength except indexerror raise parseerror return extractedname extractedphone name main print lazyparsexjackxa ok print lazyparsexjackxa raise parseerror edit example simpler write using byte strings real code using lists
3
the backdoor looking following get width widest label since every label need shift amount align right shift maxtgetwindowextentwidth legendgettexts legendgettexts tsetha right ha alias horizontalalignment tsetpositionshift
i trying rightalign entries matplotlib axes legend default leftaligned seem find way the setup i i added data labels myfig axes using axplot command ax myfiggetaxes legendfont fontpropertiessize axlegendproplegendfont numpoints markerscale there list legend keyword arguments docs matplotlib axes seem straighforward way set alignment legend entries anybody know backdoor way thanks edit to clarify i trying achieve right legend looks like maneuver oct utc bias oct utc i want look like maneuver oct utc bias oct utc
3
the problem xlrdnamedstyle different xlwtxfstyle the question seems duplicate preserving styles using pythons xlrdxlwt xlutilscopy
specifically i trying open existing workbook write data however whenever i write data obliterates borders cells so i wondering way copy style cell writing reapply i think i might right track code xlrd import openworkbook xlwt import easyxf xlutilscopy import copy xlutilsstyles import styles rbopenworkbook sourcexls formattinginfotrue styles stylesrb rsrbsheetbyindex wbcopyrb wswbgetsheet icell enumeraterscol continue cellstyle stylesrscelli wswriteicellvaluecellstyle wbsave outputxls but i getting error attributeerror namedstyle instance attribute font
2
unfortunately support bit python windows relatively poor bit version it fault python community relative difficulty getting free compilers bit windows if installed bit version python also need use packages built bit some simple python packages written pure python requiring externalc libraries install normal using setuptoolseasyinstallvirtualenv a lot bit packages however might break installed virtualenv require installer fortunately find bit precompiled installers popular packages try package first the installer target globalmain installation python thus isolated virtualenv note however unofficial builds provided free convenience please sue provider things fail expect help
i wonder right way install virtualenv bit python pywin module operating system windows bit i found exe installer sourceforge when run easyinstaller command line first everything goes fine soon see strange behavior pywinwinamdpy installs runs pywinpywinegg fails error no local packages download links found pywin best match none and full log sandboxvirtenv dtestpyexetesteasyinstall httpsourceforgenetprojectspywinfilespywinbuildpywinwinamdpyexe downloading httpsourceforgenetprojectspywinfilespywinbuildpywinwinamdpyexe processing pywinwinamdpyexe pywintypes module references file winevtlogutil module references file winserviceutil module references file wintimezone module references file demoswinrcparserdemo module references file demossecuritysspivalidatepassword module references file isapiinstall module references file isapisamplesadvanced module references file isapisamplestest module references file isapitestsetup module references file pywinframeworkscriptutils module references file pywinframeworkstartup module references path pywinscintillaconfig module references path pywinscintillacontrol module references file pywinscintillaidleenvironment module references file scriptsregsetup module references file scriptssetupd module references file testtestall module references file testtestclipboard module references file testtestwinapi module references file testtestwinrcparser module references file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandbdisteggpy unicodewarning unicode equal comparison failed convert arguments unicode interpreting unequal symbols dictfromkeysitersymbolscode testtestwintrace module references file wincominit module references path wincomserverregister module references file wincomserverregister module references path wincomtestgentestscripts module references path wincomtestpipposerver module references file wincomtesttestall module references file wincomtesttestaxscript module references path wincomtesttestdictionary module references file wincomtesttestpippo module references file wincomtesttestpycomtest module references file wincomtesttestservers module references file wincomtestutil module references file wincomextadsiinit module references path wincomextauthorizationinit module references path wincomextaxcontrolinit module references path wincomextaxdebugcodecontainer module references file wincomextaxdebugdebugger module references file wincomextaxdebuginit module references path wincomextaxscriptinit module references path wincomextbitsinit module references path wincomextdirectsoundinit module references path wincomextdirectsoundtestdstest module references file wincomextinternetinit module references path wincomextmapiinit module references path wincomextshellinit module references path wincomextshelldemosserversemptyvolumecache module references file wincomextshelldemosserversfolderview module references file wincomexttaskschedulerinit module references path creating cusersantpkyiappdatalocaltempeasyinstallkclmxkpywinpywinegg adding cusersantpkyiappdatalocaltempeasyinstallkclmxkpywinpywineggtmp creating dtestsandboxvirtenvlibsitepackagespywinpywinegg extracting pywinpywinegg dtestsandboxvirtenvlibsitepackages adding pywin easyinstallpth file installing pywinpostinstallpy script dtestsandboxvirtenvscripts installing pywinpostinstallpyc script dtestsandboxvirtenvscripts installing pywintestallpy script dtestsandboxvirtenvscripts installing pywintestallpyc script dtestsandboxvirtenvscripts installed dtestsandboxvirtenvlibsitepackagespywinpywinegg processing dependencies pywin searching pywin reading httppypipythonorgsimplepywin reading httpsfnetprojectspywin reading httpssourceforgenetprojectspywinfilespywin reading httpsourceforgenetprojectshowfilesphpgroupid no local packages download links found pywin best match none traceback recent call last file dtestsandboxvirtenvscriptseasyinstallscriptpy line module loadentrypoint setuptoolsc consolescripts easyinstall file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line main witheiusagelambda file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line witheiusage return f file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line lambda distclassdistributionwithouthelpcommands kw file cpythonlibdistutilscorepy line setup distruncommands file cpythonlibdistutilsdistpy line runcommands selfruncommandcmd file cpythonlibdistutilsdistpy line runcommand cmdobjrun file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line run selfeasyinstallspec selfnodeps file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line easyinstall return selfinstallitemnone download tmpdir deps true file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line installitem selfprocessdistributionspec dist deps file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line processdistribution requirement selflocalindex selfeasyinstall file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggpkgresourcespy line resolve dist bestreqkey envbestmatchreq self installer file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggpkgresourcespy line bestmatch return selfobtainreq installer try downloadinstall file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggpkgresourcespy line obtain return installerrequirement file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolscommandeasyinstallpy line easyinstall selflocalindex file dtestsandboxvirtenvlibsitepackagessetuptoolscpyeggsetuptoolspackageindexpy line fetchdistribution return distclonelocationselfdownloaddistlocation tmpdir attributeerror nonetype object attribute clone sandboxvirtenv dtestpyexetest now import python winapi quite confusing sandboxvirtenv dtestpyexetestpython python default jun msc v bit amd win type help copyright credits license information import winapi if find something unclear ask thanks advices
1
do want something like import csv open largecsv w f writercsvwriterf delimiter lineterminator n range row j j rangei writerwriterowrow also rowcolumn headers import csv open largecsv w f writercsvwriterf delimiter lineterminator n writerwriterow range range row j j rangei writerwriterowrow the latter returns following file i replaced
import csv open largecsv w f writercsvwriterf delimiter lineterminator n range j rangei aappendij print ija want write csv file like i done avoid caculation twice list grow large i initialize againafter one iteration outer loop so i want listbefore get initialized written csv file manner i able soplease help
3
you use plain dom httpdocspythonorglibraryxmldomminidomhtml parse source xmldomminidom import parse datasource open ctempmydataxml doc parsedatasource find nodes remove node docgetelementsbytagname div attr nodeattributes attrname id found targeted nodes replace new comment node parent nodeparentnode parentreplacechilddoccreatecommentpage break node docs httpdocspythonorglibraryxmldomhtml
what good way replace html tag like old div idpgbrk page breakdiv new page break div id might many values hence regex good idea hence i need lxml kind things basically problem replace html tag string
1
as long div parent tag could import lxmlhtml lh import lxmletree et content rootdiv idpgbrk page breakdivroot doclhfromstringcontent printlhtostringdoc div docxpath dividpgbrk parentdivgetparent parentreplacedivetcommentpage break printlhtostringdoc yields rootpage breakroot
what good way replace html tag like old div idpgbrk page breakdiv new page break div id might many values hence regex good idea hence i need lxml kind things basically problem replace html tag string
2
just came across issue way i solved remove sender function arguments check inside callback function djangodbmodels import signals features import models features def createfeaturesapp createdmodels verbosity kwargs print creating features app features work compares models module instances return do stuff signalspostsyncdbconnectcreatefeatures that way keep management module like django docs suggest i agree work like suggested you could probably dig implementation signal class djangodispatch
i myappmanagementinitpy registering postsyncdb handler like djangodbmodels import signals features import models features def createfeaturesapp createdmodels verbosity kwargs print creating features do stuff signalspostsyncdbconnectcreatefeatures senderfeatures i verified following both features myapp settingsinstalledapps myappmanagement getting loaded prior syncdb running verified via print statement module level the features app getting processed syncdb emitting postsyncdb signal verified examining syncdb output verbosity i using exact idiom another pair apps handler called correctly i compared two modules found relevant differences invocations however myappmanagementcreatefeatures never called what i missing
1
using function like safeslice would faster creating object perform slice speed bottleneck looking nicer interface could define class getitem perform checks returning slice this allows use nice slice notation instead pass start stop arguments safeslice class safesliceobject slice rules httpdocspythonorglibrarystdtypeshtmlsequencetypesstrunicodelisttuplebytearraybufferxrange def initselfseq selfseqseq def getitemselfkey seqselfseq isinstancekeyslice startstopstepkeystartkeystopkeystep start seqstart stop stop stoplenseqstop seqstop return seqkey seq printseq printsafesliceseq printsafesliceseq indexerror list index range if speed issue i suggest testing end points instead arithmetic item access python lists o the version safeslice also allows pass arguments with arguments second interpreted stop value similar range def safesliceseq start stopnone step stop none stopstart start else seqstart stop stoplenseqstop seqstop return seqstartstopstep
here quote httpstackoverflowcomusersgreghewgill answer good primer python slice notation python kind programmer fewer items ask for example ask contains one element get empty list instead error sometimes would prefer error aware may happen so error prefered pythonic way proceed is pythonic way rewrite example class parseerrorexception pass def safeslicedata start end start end assumed r datastartend lenr end start raise indexerror return r def lazyparsedata extract name phone data buffer if buffer could parsed parseerror raised try namelength orddata extractedname safeslicedata namelength phonelength orddata namelength extractedphone safeslicedata namelength namelength phonelength except indexerror raise parseerror return extractedname extractedphone name main print lazyparsexjackxa ok print lazyparsexjackxa raise parseerror edit example simpler write using byte strings real code using lists
1
according python documentation subprocesscall runs command waits complete equivalent subprocesspopen followed popenwait however popenwait method documentation explicitly warns problem buffer overflow recommends use popencommunicate instead hence solution looking something like import subprocess process subprocesspopencmd stdoutsubprocesspipe stdinsubprocesspipe shelltrue stdout stderr processcommunicate print show something subprocess
i problem using subprocesspopen subprocesscall i use execute command lines generates lot output python scripts hangs weird waiting script hanging state i find job commanded cmd line done script hung subprocesscallcmd shell true or subprocesspopencmd stdout subprocesspipe stdin subprocesspipe shell true hangs here print show something subprocess note last print never executed actually cmd executed note also cmd related serial port i plug serial cable everything become fine last print statetement get executed but i use terminal everything fine even serial plugged occurs python script thanks lot
3
you use httpceleryprojectorg works like charm nice django integration well documented used many
i fairly complex report generating work needs generated spaning multiple tables final report created excel sheetthe process takes anything minutes we provided django web app client only issue client requests report generating url takes time issue far ui go i would like task running behind mail client link report what right strategy libraries used
2
i accept comment answer question python worked clojure using last vector linear operation prevented cumulative sum computed way i intended updating function use transient vector like defn cumulativesum loop x amp xs ss acc transient x let ssx ss x recur xs ssx conj acc ssx persistent acc results clojure version run twice long python consistently i kind hoped clojure would faster python operations wonder i still miss something i using way thanks
i recently started learn clojure decided practice euler problems get hang available data structures practice recursion looping i tried various approaches problem matter i finding solution never finished after i looked others i guessed i take forever either i typed equivalent algorithm python see problem lies lack understanding clojure thing java setting python finished seconds for primes python version finished sec clojure i posting clojure version created specifically match python code can help understand difference performance should i use uncheckedadd type hints primitives so clojure defn prime n let r int mathsqrt n loop cond n false r true zero rem n false recur inc defn primes filter prime iterate inc defn cumulativesum reduce fn v x conj v last v x first rest defn longestsequnder n longest prime seq sum n let ps vec takewhile n primes prime numbers n primeset set ps set testing inclusion cs cumulativesum ps cnt count ps maxlen count takewhile n cs cannot longer sequences subsum fn j sum primes ith jth cs j get cs dec seqwithlen fn try length prime sequences return first sum prime loop try lowest sum cnt elements length sequence nil could find let j dec fix length subsum j n overshoot nil primeset sum prime inc j looked first recur inc shift window loop maxlen try longest sequence zero let j seqwithlen j subvec ps j recur dec assert longestsequnder let longestsequnder assert count assert reduce time reduce longestsequnder elapsed time msecs and python math import sqrt itertools import takewhile def isprimen xrange intsqrtn n return false return true def nextprimen isprimen n return n def primes true nextprimei yield def cumulativesums cs css si css si csappend css return cs def longestsequndern ps listtakewhile lambda p p n primes pss setps cs cumulativesumps cnt lenps maxlen lenlisttakewhilelambda n cs def subsumi j return csj csi else def intervalwithlengthm xrange cntm j sij subsumij sij n return none none sij pss prime return j return none none xrangemaxlen f intervalwithlengthm return psft assert longestsequnder assert sumlongestsequnder import timeit timeittimersumlongestsequnder main import longestsequndertimeit thanks
2
using code phone send file using chunked encoding because pybottle support chunked enconding solution rewrite android send file body post request
on android phone i used setentity put fileentity post request httppost post new httpposturi fileentity reqentity new fileentityf applicationxgzip reqentitysetcontenttypebinaryoctetstream reqentitysetchunkedtrue postaddheaderxaethersnotebookcustom configurationgetcustomheader postsetentityreqentity when using bottle tried working f requestbody gzipper gzipgzipfile fileobj f content gzipperread the content empty string so i tried look requestforms requestfiles both key value requestfileskeys requestformskeys when searching i read entity request may transfer entity entity entityheader entityvalue so may something like filecontent egetentityheader
1
almost numpy functions operate whole arrays andor told operate particular axis row column as long define function terms numpy functions acting numpy arrays array slices function automatically operate whole arrays rows columns it may helpful ask implement particular function get concrete advice numpy provides npvectorize npfrompyfunc turn python functions operate numbers functions operate numpy arrays for example def myfuncab ab return else return b vecfunc npvectorizemyfunc resultvecfunc printresult the elements first array get replaced corresponding element second array second bigger but get excited npvectorize npfrompyfunc syntactic sugar they actually make code faster if underlying python function operating one value time npvectorize feed one item time whole operation going pretty slow compared using numpy function calls underlying c fortran implementation to count many elements column x smaller number could use expression array x ysum for example import numpy np arraynparangeview x npint npint printarray printarray x printarray x true true false printarray x sum
i using numpy store data matrices coming r background extremely simple way apply function rowcolumns matrix is something similar pythonnumpy combination it problem write little implementation seems versions i come significantly less efficientmore memory intensive existing implementation i would like avoid copying numpy matrix local variable etc possible the functions i trying implement mainly simple comparisons eg many elements certain column smaller number x many absolute value larger
3
right i think yet ready however still manual introspection looking gtkgir file system located usrsharegirgtkgir the gir file xml file supposed used exactly explore exposed interface regardless programming language using for example label class found looking class namelabel inside class tag doc tag extensive information widget supposed also many method tags one one interested example method namesettext inside method tag doc tag describes method also parameters tag turn contains parameter tag used describe parameter terms name description type parameters parameter namestr transferownershipnone doc xmlwhitespacepreservethe text want setdoc type nameutf ctypegchar parameter parameters so information already
one great things python ability introspection methods functions as example get function signature mathlog ipython run in mathlog type builtinfunctionormethod base class type builtinfunctionormethod string form builtin function log namespace interactive docstring logx base return logarithm x given base if base specified returns natural logarithm base e x and see x optionally base parameters function with new gtk automaticall generated pygobject bindings i examples i tried ever get args kwargs parameters every gtk method example labelsettext requires string in girepository import gtk in mylabel gtklabelhello in mylabelsettext type instancemethod base class type instancemethod string form bound method labelsettext label object xb gtklabel xcd namespace interactive file usrlibpythondistpackagesgitypespy definition lsettextargs kwargs docstring docstring now the question loss method introspection python bindings something change documentation effort gone pygobjects something stay due way pygobjects works
2
def stepsdself ns return scrandomrandomintegers sizens def walkdself nsnone ns none ns selfns return sccumsumselfstepsdns
code class randomwalk ns number stepsd np number particles dimension choose d d def initselfnsnpdimensionnone selfnsns selfnpnp selfdimensiondimension def stepsdselfns return scrandomrandomintegerssizeselfns the position particles nth stepsd given sum n first stepsd def walkdselfns return sccumsumrandomwalkstepsdselfselfns when ns np dimension rwrandomwalknsnp rw creates instance class randomwalkswhich ns nowif example want print walkd rwwalkd give size array telling right created instance ns so want apply statement order give size array solutions exists
1
an alternate way dynamic sys scriptengineimportmodulesys syspathappendsomepath
i complete noob comes ironpython i need call py script aspnet website following code var ipy ironpythonhostingpythoncreateruntime dynamic test ipyusefileservermappathpythontestpy testdowork the version ironpython i using the rd party python file i need call following import directives import sys array import subprocess import i receiving error no module named subprocess i copied subprocesspy file ironpython installation lib directory i assume i need link c code thanks edit i found solution scriptengine scriptengine pythoncreateengine var sp scriptenginegetsearchpaths spaddservermappathpythonlib scriptenginesetsearchpathssp var scope scriptengineruntimeexecutefileservermappathpythontestpy if anyone commentsimprovements please feel free elaborate seeing i new ground pythonironpython malarky
1
this script freeze brilliant example code tired the loop supposed try connect api three times continue ever i forgot put break this question stupid i blame removing fixed code try three times make contact true try connect api connection urlliburlopenrequest timeout xmlstring connectionread break except urlerror e tries tries sysstderrwrite owndstreamsupdater fatal error repeated timeouts exit
the function urlliburlopen freezes so question simple why urlopen freeze script ever even though timeout set how i access data url case httpapiowndtvlivechannelfnatictv without possibility python process freezing eternity this part freezes in owndpy try three times make contact true try connect api right it freezes connection urlliburlopenrequest timeout xmlstring connectionread except urlerror e tries tries sysstderrwrite owndstreamsupdater fatal error repeated timeouts exit this stack trace keyboardinterrupt traceback recent call last file line file honsappowndstreamsupdaterpy line updatestreaminfo streaminfo getstreaminfostream file honsappowndpy line getstreaminfo connection urlliburlopenrequest timeout file usrlocallibpythonurllibpy line urlopen return openeropenurl data timeout file usrlocallibpythonurllibpy line open response selfopenreq data file usrlocallibpythonurllibpy line open open req file usrlocallibpythonurllibpy line callchain result funcargs file usrlocallibpythonurllibpy line httpopen return selfdoopenhttplibhttpconnection req file usrlocallibpythonurllibpy line doopen r hgetresponsebufferingtrue file usrlocallibpythonhttplibpy line getresponse responsebegin file usrlocallibpythonhttplibpy line begin version status reason selfreadstatus file usrlocallibpythonhttplibpy line readstatus line selffpreadline file usrlocallibpythonsocketpy line readline data selfsockrecvselfrbufsize keyboardinterrupt edit i let script run night i know exactly long took though five minutes script finally gave gave stacktrace traceback recent call last file honsappowndstreamsupdaterpy line newinfo file honsappowndstreamsupdaterpy line newinfo result updatestreaminfostream file honsappowndstreamsupdaterpy line updatestreaminfo streaminfo getstreaminfostream file rootdropboxprojectshonstreamshonsappowndpy line getstreaminfo connection urlliburlopenrequest timeout file usrlocallibpythonurllibpy line urlopen return openeropenurl data timeout file usrlocallibpythonurllibpy line open response selfopenreq data file usrlocallibpythonurllibpy line open open req file usrlocallibpythonurllibpy line callchain result funcargs file usrlocallibpythonurllibpy line httpopen return selfdoopenhttplibhttpconnection req file usrlocallibpythonurllibpy line doopen r hgetresponsebufferingtrue file usrlocallibpythonhttplibpy line getresponse responsebegin file usrlocallibpythonhttplibpy line begin version status reason selfreadstatus file usrlocallibpythonhttplibpy line readstatus raise badstatuslineline httplibbadstatusline
2