text_a
stringlengths
5
12.3k
text_b
stringlengths
36
15.7k
Score
int64
1
3
use beautifulsoup parse returned html search image links you might also need recursively fetch frames iframes
i trying retrieve source webpage including images at moment i import urllib page urlliburlretrieve httpmyurlphp urlgotphp print urlgotphp retrieves source fine i also need download linked images i thinking i could create regular expression searched img src similar downloaded source however i wondering urllib function would retrieve images well similar wget command wget r noparent httpmyurlphp i want use os module run wget i want script run systems for reason i use third party modules either any help much appreciated thanks
2
you want embed python another application use pyrunanyfile run
i python dll already shipped installed end user guaranteed known version number how i use dll execute python scripts without shipping python interpreter
1
its documented fb sdk loginbutton page reason add autologoutlinktrue attribute tag show logout button logged rather making button invisible fbloginbutton autologoutlinktruefbloginbutton warning ignore tag using custom text login button like this always display button whether logged fbloginbutton autologoutlinktruelogin to my servicefbloginbutton
i apologize ahead time clearly documented somewhere fb developer site i find please link appropriate i implemented fb login button website using gae python here html fbloginbuttonfbloginbutton div idfbrootdiv script srchttpconnectfacebooknetenusalljsscript script fbinitappid adafcbefdebe status true cookie true xfbml true fbeventsubscribe authsessionchange functionresponse responsesession a user logged new cookie saved else the user logged cookie cleared script currently behavior i click login button i asked allow application access fb which i choose ok but login button still showing login logout how i implement on server client side
3
use mylist zipmylist original transposed ziporiginal transposed original transposed how works ziporiginal equal ziporiginal original original turn equal zip
i writing code parse tilemap map config file the map format numbers represent tiles i make integer array inttile tile rowsplit row nnlstripnsplitn this produces array format rowcolumn i would prefer columnrow xy i address backwards ie yx but i think concise ways attacking problem i considered reworking format using xml syntax tiled appears difficult beginner thanks advance responses
3
the webtest library helpful test cases httpwebtestpythonpasteorgenlatestindexhtmlformsubmissions
using webapp i create unit tests form checkboxes votes multiple values posted vote field retrieved via requestpostgetall vote input typecheckbox namevote valuebetter input typecheckbox namevote valuefaster input typecheckbox namevote valuestronger in unit test i tried passing list response appgetresponse vote post vote u better u faster u stronger headers contenttype applicationxwwwformurlencoded charsetutf but looks like simply converted string votes selfrequestpostgetall vote uu better u faster u stronger how i pass multiple values vote retrieved list via requestpostgetall
1
this could become heated discussion date logic usually much harder first looks everyone idea make things happen i would probably sacrifice db space models dumb possible eg define anomalies series the repeat condition could either simple terms would parsed depending requirements kiss interval next event occurs from generate next event copy repeat condition generate much events future practically necessary define max time window future generate events generate somebody fact looks time intervall question the events could pointer back parent event whole series identifiable like linked list the model indicator whether single event cancelled the event remains db able copy event future cancelling whole series deletes list events edit answers mentioned dateutil package interval building parsing really looks nice
i building calendar system ground requirement i working special type calendar alongside gregorian i need help logic i writing application django python essentially logical issues i running persist objects possible smartly possible without running tab cpu cycles i feeling polymorphism would solution i exactly sure express i two basic subsets events repeating events oneshot events repeating events subscribers people notified changes if example class canceled moved different address time people subscribed need know some events simply happen every day end time edited happen the problem i one object stores event info repeating policy canceling modifying one event series really screws things i account somehow keeping subscribers aware change keeping series together logical group paradox generating unique event objects normal event series end time repeats indefinitely make sense going store information however change happens single event series i almost create different object database represent cancellation can someone help logic it really twisting mind i really think straight anymore i really like input solve issue repeating events exactly easiest logical thing either repeat every day every mwf st m month every months year date week date month date tuesdays thursdays etc i like help understanding best route logic repeating events well here thought class eventseriesmodelsmodel seriesname modelstextfield seriesdescription modelstextfield seriesrepeatpolicy modelsihavenoideaintheworldonhowtorepresentthisfield seriesdefaulttime modelstimefield seriesstartdate modelsdatefield seriesenddate modelsdatefield location modelsforeignkey location class eventseriesanomalymodelsmodel eventseries modelsforeignkey eventseries relatednameexceptions overridename modelstextfield overridedescription modelstextfield overridetime modelstimefield overridelocation modelsforeignkey location eventdate modelsdatefield class eventseriescancellationmodelsmodel eventseries modelsforeignkey eventseries relatednamecancellations eventdate modelstimefield cancellationexplanation modelstextfield this seems make bit sense stated ruining brain right anything seems like would work another problem question someone wants modify remaining events series heck i i suppose i could change seriesdefaulttime generate anomaly instances past instances set original time ahhhhhh boiling three simple concrete questions how i series repeating events yet allow cancellations modifications individual events modifications rest series whole storing objects database absolutely necessary never generating objects individual events advance how i repeat events highly customizable way without losing mind i allow events repeat number ways making things easy storing objects possible how i allowing switch event series make happen falls holiday
2
don use regex perfectly good parser built python import urllib htmlparser import htmlparser baseurl http class imgparserhtmlparser def initself args kwargs selfdownloads htmlparserinitself args kwargs def handlestarttagself tag attrs tag img attr attrs attr src selfdownloadsappend attr imgp imgparser open testhtml f instead could feed original url obj directly imgpfeedfread path imgpdownloads url baseurl path print url urlliburlretrieveurl path
i trying retrieve source webpage including images at moment i import urllib page urlliburlretrieve httpmyurlphp urlgotphp print urlgotphp retrieves source fine i also need download linked images i thinking i could create regular expression searched img src similar downloaded source however i wondering urllib function would retrieve images well similar wget command wget r noparent httpmyurlphp i want use os module run wget i want script run systems for reason i use third party modules either any help much appreciated thanks
3
try arrayarray phase p array phase p returns boolean numpy array when idx boolean array arrayidx returns array composed rows idx true
i numpy rec array i would like quick queries similar sql select array phase p i would like get record array output row corresponding row original array met query criteria any ideas i pretty sure i done cannot remember function thanks recarray p p lr dtype eventid eventlat f eventlon f eventdepth f eventtime f stationid stationlat f stationlon f stationelv f phase s timeresidual f
3
emit warning instead let code decide handle
i number functions parse data files usually returning list results if i encounter dodgy line file i want soldier process valid lines return but i also want report error calling function the reason i want report calling function notify user file needs looking i want start gui things parse function seems big violation separation concerns the parse function access console i writing error messages anyway this leaves wanting return successful data also raise exception error clearly i consider code try parseresult parsemyfile except myerrorclass e handleerrorssomehowstre def parsefile file list lines actual file err false result lines file processedline processline processedline err true else resultappendprocessedline return result err raise myerrorclasssomething went wrong obviously last three lines make sense i figure nice way i guess i could return err result call like parseerr parseresult parsefile parseerr handleerrorssomehow but returning error codes seems unpythonic enough let alone returning tuples error codes actual result values the fact i feel like i want something strange application really terribly complicated making think i probably something wrong is better solution problem or way i use finally return value raise exception time
2
in principle wsgi intrinsically incompatible asynchronous program design fact pep goes considerable length specify servers applications middleware must behave support kind thing at heart returning iterator container every time asynchronous wsgi appiter invoked would check pending asyncronous tasks database connections etcetera data appiter yields data otherwise yields empty string to support wsgi container would need keep track inflight requests iterate turn get data addition servicing deferred work responsible in principle wsgi apps frameworks actually almost invariably wsgi frameworks block sorts reasons reading files disk loading data database reason most orm make tough problem prevent twisted wsgi container operates assumption since wsgi apps block perhaps wsgi app may block therefore always runs thread there two things either explore twisted web framework fairly solid consider creating wsgi wrapper twisted outside twisted container making sure wsgi app actually asyncronous certainly precondition latter wsgi pretty simple thin wrapper http easy enough
i building web interface twisted application would like use wsgi rather twistedweb directly since rest website wsgi i already substantial wsgi codebase the twisted documentation page i found wsgiresource httptwistedmatrixcomdocumentscurrentwebhowtowebinwsgihtml states like wsgi container anything asynchronous wsgi applications even though twisted wsgi container does true is lessthanhacky way twistedweb style asynchronous web request handling wsgi perhaps part another free software project supposing plan wsgi threads asynchronous work reactor thread block polling data available it pretty if reasonably uncomplicated way asynchronously handling wsgi requests twisted i love hear
3
nobody says valid way treat error throw exception in design caller wants two pieces information valid data whether error occurred probably something went wrong format useful error message that completely valid aboveground case returning pair values an alternative design would pass mutable collection function parameter let fill error messages wants emit that often simplify plumbing caller especially several layers calls parser code knows something error messages afterwards
i number functions parse data files usually returning list results if i encounter dodgy line file i want soldier process valid lines return but i also want report error calling function the reason i want report calling function notify user file needs looking i want start gui things parse function seems big violation separation concerns the parse function access console i writing error messages anyway this leaves wanting return successful data also raise exception error clearly i consider code try parseresult parsemyfile except myerrorclass e handleerrorssomehowstre def parsefile file list lines actual file err false result lines file processedline processline processedline err true else resultappendprocessedline return result err raise myerrorclasssomething went wrong obviously last three lines make sense i figure nice way i guess i could return err result call like parseerr parseresult parsefile parseerr handleerrorssomehow but returning error codes seems unpythonic enough let alone returning tuples error codes actual result values the fact i feel like i want something strange application really terribly complicated making think i probably something wrong is better solution problem or way i use finally return value raise exception time
3
if use numpy use numpyr import numpy np npr array npr array
after spending last months learning matlab seems i need switch vpython matlab colon operator comes handy often i found equivalent vpython for reference matlab is easy way thing vpython
1
try axon kamaelia it compatible pypy get actorflowbased programming significantly accelerated execution speeds pypy jit
is anything python concurrency like erlang particulary transparent actors networks i looked things like greenlet stackless seem network transparency actors i still quite jump hurdle erlangotp i interested something closer home
1
post data encoded using query string encoding multiple items name represented repeating key different values for instance votebetterampvotefasterampvotestronger python library functions though urlliburlencode vote better faster stronger true the second argument true urlencode called doseq instructs urlencode encode sequences lists separate elements
using webapp i create unit tests form checkboxes votes multiple values posted vote field retrieved via requestpostgetall vote input typecheckbox namevote valuebetter input typecheckbox namevote valuefaster input typecheckbox namevote valuestronger in unit test i tried passing list response appgetresponse vote post vote u better u faster u stronger headers contenttype applicationxwwwformurlencoded charsetutf but looks like simply converted string votes selfrequestpostgetall vote uu better u faster u stronger how i pass multiple values vote retrieved list via requestpostgetall
2
yes possible using translate function example translatenodenodename valname accountnumber output you use code line broken readability translate nodenodename straccountnumber valname accountnumber note white space included second argument translate even ampx necessary remove white spaces
okay i got example xml looks like node namedetails node name val nametypeuuval val nameownernval val nameaccountnumberuuval node node name val nametypeuuval val nameownernval val nameaccountnumberu uval node node name val nametypeuuval val nameownernval val nameaccountnumberuuval node node i trying search based accountnumber but many different formats could some spaces dashes mixture etc if i able search removing spaces dashes i able get account number with accountnumber search query ultimate goal get second level node name number search xpath doc libxmlparsedocxml ctxt docxpathnewcontext res ctxtxpathevalnodenodevalname accountnumber straccountnumber name is way use xpath search remove dashes spaces leave numbers thanks
1
i probably recommend download python official site configure aptana find you download latest version python httpwwwpythonorgdownload you specify whether using python x python x for compatibility reasons i probably go python x the latest bit windows version direct link httpwwwpythonorgftppythonpythonamdmsi after downloaded installed place python interpreter assuming use c windows drive cpythonpython you simply need point aptana to go preference left look pydev expand look section interpreter python in theory click auto config automatically detect cpython if simply need click new use file dialog prompt find cpythonpythonexe this also automatically import python libraries sitepackages installed well although fresh install stdlibs let us know issues cheers victor
i impression installing aptana studio also installed python interpreter i try create pydev project says project interpreter specified so let proceed is documentation proceed configuring interpreter studio i using latest build aptana studio standalone build thanks in advance assistance ps i already uninstalled reinstalled studio still issue i running windows bit machine
3
assuming fit whole log file memory i keep dictionary mapping thread ids lines written thread write whole files end threadmap keys thread ids values lists log lines line openfiletoopen sthdid line threadmap threadmapi threadmapiappendline key threadmap f openfolderpathkeylog w line threadmapkey fwriteline fclose if keep whole log file memory try multipass solution write file one time infile openfiletoopen sthdid infileseek reset file read beginning outfile openfolderpathilog w line infile line outfilewriteline outfileclose infileclose
i trying parse log file threadids every like there could number threads configured all threads write log file i parsing log file creating new files specific thread order check later below i capturing threadids list the code job i feel efficient can anything faster sthdid abc cdeefg folderpath newdir ossystemmkdir folderpath line openfiletoopen sthdid line openfolderpathilogawriteline
1
for event series model i created solution ihavenoideaintheworldonhowtorepresentthisfield use pickled object field save recurrence rule rrule dateutil event series model
i building calendar system ground requirement i working special type calendar alongside gregorian i need help logic i writing application django python essentially logical issues i running persist objects possible smartly possible without running tab cpu cycles i feeling polymorphism would solution i exactly sure express i two basic subsets events repeating events oneshot events repeating events subscribers people notified changes if example class canceled moved different address time people subscribed need know some events simply happen every day end time edited happen the problem i one object stores event info repeating policy canceling modifying one event series really screws things i account somehow keeping subscribers aware change keeping series together logical group paradox generating unique event objects normal event series end time repeats indefinitely make sense going store information however change happens single event series i almost create different object database represent cancellation can someone help logic it really twisting mind i really think straight anymore i really like input solve issue repeating events exactly easiest logical thing either repeat every day every mwf st m month every months year date week date month date tuesdays thursdays etc i like help understanding best route logic repeating events well here thought class eventseriesmodelsmodel seriesname modelstextfield seriesdescription modelstextfield seriesrepeatpolicy modelsihavenoideaintheworldonhowtorepresentthisfield seriesdefaulttime modelstimefield seriesstartdate modelsdatefield seriesenddate modelsdatefield location modelsforeignkey location class eventseriesanomalymodelsmodel eventseries modelsforeignkey eventseries relatednameexceptions overridename modelstextfield overridedescription modelstextfield overridetime modelstimefield overridelocation modelsforeignkey location eventdate modelsdatefield class eventseriescancellationmodelsmodel eventseries modelsforeignkey eventseries relatednamecancellations eventdate modelstimefield cancellationexplanation modelstextfield this seems make bit sense stated ruining brain right anything seems like would work another problem question someone wants modify remaining events series heck i i suppose i could change seriesdefaulttime generate anomaly instances past instances set original time ahhhhhh boiling three simple concrete questions how i series repeating events yet allow cancellations modifications individual events modifications rest series whole storing objects database absolutely necessary never generating objects individual events advance how i repeat events highly customizable way without losing mind i allow events repeat number ways making things easy storing objects possible how i allowing switch event series make happen falls holiday
1
you really need regex could use u u replace replace uu
i got string u u how i remove spaces hyphens returns currently i got usu but i figure working any insight would appreciated thanks
2
the error message indicates two conflicting metaclasses somewhere hierarchy you need examine classes qt classes figure conflict here simple example code sets situation class metaatype pass class metabtype pass class a metaclass metaa class b metaclass metab we subclass classes directly python know metaclass use class brokena b pass traceback recent call last file stdin line module typeerror error calling metaclass bases metaclass conflict metaclass derived class must nonstrict subclass metaclasses bases what error trying tell us need resolve conflict two metaclasses introducing third metaclass subclass metaclasses base classes i sure clearer error message basically fix class metaabmetaa metab pass class fixeda b metaclass metaab this code compiles runs correctly of course real situation conflictresolving metaclass would decide parent metaclass behaviors adopt figure application requirements bear mind inherited class gets one two metaclass init methods sometimes work lot cases going add init calls way helps get along
looks like i stumbled upon metaclass hell even i wanted anything i writing app qt using pyside i want separate eventdriven part ui definition generated qt designer files hence i create controller classes ease life i multipleinherit anyways an example class basecontrollerqobject def setupeventsself parent selfwindow parent class maincontrollerbasecontroller pass class mainwindowqmainwindow uimainwindow maincontroller def initself parentnone supermainwindow selfinitparent selfsetupuiself selfsetupeventsself this works expected it also inheritance qdialog uidialog basecontroller but i subclass basecontroller try inherit said subclass place basecontroller i receive error typeerror error calling metaclass bases metaclass conflict metaclass derived class must nonstrict subclass metaclasses bases clarification both qmainwindow qdialog inherit qobject basecontroller must also inherit qt event system peculiarities ui classes inherit simple python object class i searched solutions involve cases intentionally using metaclasses so i must something terribly wrong edit my description may clearer adding graphs working example qobject object qmainwindow basecontroller uimainwindow maincontroller mainwindow another working example qobject object qdialog basecontroller uiotherwindow otherwindow not working example qobject object qdialog basecontroller uiotherwindow othercontroller otherwindow
3
there fork djangomaintenancemode allows turn maintenance mode onoff setting value database this way example create simple management command toggle maintenance mode call via fabric i think flexible using modrewrite
i currently using maintenancemodemiddleware put site maintenance mode requires make change settingspy file remote server i would like use fabric remotely put site maintenance mode is way achieve or better method thanks update thanks feedback everyone end i works great httpgarthhumphreyscompainlessdjangomaintenancemodewithfabric i like idea uncomment lines setup i production server would overwritten i pushed new version end putting site maintenance mode server level django level works lot better truly easier flexible least
1
using perl syntax u u start body end body ssg start body end xesg or python equivalent e g u u z sg pre start body end pre definedstart body ssg start body end
i got string u u how i remove spaces hyphens returns currently i got usu but i figure working any insight would appreciated thanks
1
usu your pattern tell regex expect numbers usdu that get started python guy i give exact replacement syntax just aware digits repeating capture group edit this edit response comment like i said python guy probably need hold tongue right def replmatchobj matchobjgroup none return else return matchobjgroup source u u u u print resubr sdu repl source results uu uu if offends python deities i promise sacrifice next php developer i come across
i got string u u how i remove spaces hyphens returns currently i got usu but i figure working any insight would appreciated thanks
2
i admittedly good regexes way i would doing match uu pair resub bit match using group that looks like examplestr u su vvfv tmp researchuuexamplestrgroup cleanstr resubdtmp
i got string u u how i remove spaces hyphens returns currently i got usu but i figure working any insight would appreciated thanks
1
you expose correctly problem i firstly exactly understand having read comment tags u u tags i propose import ss kolu u maa print resub uu lambda mat joinc c matgroup c ss result koluu maa
i got string u u how i remove spaces hyphens returns currently i got usu but i figure working any insight would appreciated thanks
1
there many things wrong code i going mark i strongly recommend read python control flow constructs comparison operators builtin data types alistwhatever goes data opencdocuments settingsbhaadesktopblablablatxtread the filename needs string value put c quotes words data data string iterating give one letter per iteration one word words aside syntax remember colons remember means executes body every item collection collection kind print words wrong words say think says operator takes arbitrary value left collection right returns single boolean value right words previous line printwrong spelling properly splled words right
exercise problem given word list text file spell check contents text file print unique words found word list i get solutions problem somebody tell i went correct answer as disclaimer none parses python console my attempt alistwhatever goes data opencdocuments settingsbhaadesktopblablablatxtread i aware something wrong since i get error i use itwhen i write blablablatxt says find thing is function gonna work i working online ivle program files automatically linked console would i things python without logging online ivle words data words print words wrong words right words printwrong spelling properly splled words right oh yehi sure i indented everything correctly i know format question come block like sorry what think
1
for starters httpwwwcsyncorg sort rsync since rsync works ssh ftp httpftp transfers if like option always lftp curlftpfs stackoverflow sistersite provides answer httpserverfaultcomquestionshowtousersyncoverftp that give anything well always ftplib python httpdocspythonorglibraryftplibhtml ftplib import ftp ftpretr ftp getftpcom connect host default port ftpretrlogin user anonymous passwd anonymous ftpretrretrbinary retr readme open readme wb write ftpretrquit ftpsend ftp sendtoftpcom login password ftpsendstorbinary stor todotxt open readme rb ftpsendquit now help tbh without everything guessing want learn use sysargv fetch inputoutput files also sourcehost desition perhaps enjoy
i two ftp server b i need copy files server b server downloading file upload b complicate i want write script python desktop type command job python syncftppy acomsource server folderfolder name source server b comdestination server folderdestination folder name google still find good way sync two ftp server like dropbox is way thanks
1
you mention fact received encoding error motivated write swedify first place found solutions around chcp windows command on nix systems utf terminals swedify necessary rawinput hur lã¥ngt kilometer ã¤r ditt mã¥l hur lã¥ngt kilometer ã¤r ditt mã¥l rawinput hur lã¥ngt kilometer ã¤r ditt mã¥l hur lã¥ngt kilometer ã¤r ditt mã¥l fwiw i use swedify i get error def swedifyinp try return inpdecode utf except return dec strinp swedify hur lã¥ngt kilometer ã¤r ditt mã¥l u hur lxengt kilometer xer ditt mxel rawinputswedify hur lã¥ngt kilometer ã¤r ditt mã¥l traceback recent call last file stdin line module unicodeencodeerror ascii codec encode character u xe position ordinal range your swedify function returns unicode object the builtin rawinput happy unicode objects rawinput㥠ã¥eee eee rawinputu㥠traceback recent call last file stdin line module unicodeencodeerror ascii codec encode character u xe position ordinal range you might want try python see python bug also interest how read unicode input compare unicode strings python update according blog post way set system default encoding this might worth try
i trouble python rawinput command python for reason rawinput get converted string swedify produces giving encoding error aware made swedify begin here trying elif cmd help hjã¤lp info buffert just nu ã¤r programmet relativt begrã¤nsatnde funktioner du har att anvã¤nda ã¤rn buffert historik skriver ut din historikn buffert ã¤ndra nã¥got ã¤ndrar nã¥got databasen fã¶ljande finns att ã¤ndran print swedifybuffert this works fine outputs swedish characters want console but try code x values print piece core goaldistance rawinputswedify hur lã¥ngt kilometer ã¤r ditt mã¥l core goaltime rawinputswedify vad ã¤r ditt mã¥l minuter att springa core goaldistance km p㥠then get cusersanonpython lã¶ppy traceback recent call last file lã·ppy line module core goaldistance rawinputswedify hur l├ã‘ngt kilometer ├ã±r ditt m├ã‘l unicodeencodeerror ascii codec encode character u xe position ordinal range now googled around found solutions none work sad create batch script executes chcp beginning clean solution imo here swedify def swedifyinp try return inpdecode utf except return dec strinp any solutions get rawinput read return value swedify tried encodings import getencoder getdecoder others nothing better
2
since e string add operator for example add r b set word boundary note raw string without r prefix b backspace e pattern r b reescapee r b remember escape e researchpattern researchpattern spam researchpattern group researchpattern spam eggs group string xgroup x refinditerpattern string
e equal i would like add regular expression search prevent match can anyone help i beat head i get syntax error i try append anything slice researche sresrematch object xc
1
found great table httpwikipythonorgmoinmovingtopythonfromotherlanguages python indexes slices sixelement list indexes enumerate elements slices enumerate spaces elements index rear index front lena b c e f slice front slice rear ba b shallow copy
i need good explanation references plus python slice notation to notation needs bit picking it looks extremely powerful i quite got head around
3
another possible design invert control passing error handler parameter also feel like tell python accumulate data list it knows already it hard make list comprehension work def samplehandler print omg i expecting oh well parseresult parsemyfile samplehandler def parsefile handler file list lines actual file result processline line data allresult handler ie falseish values result filternone result remove falseish values return result
i number functions parse data files usually returning list results if i encounter dodgy line file i want soldier process valid lines return but i also want report error calling function the reason i want report calling function notify user file needs looking i want start gui things parse function seems big violation separation concerns the parse function access console i writing error messages anyway this leaves wanting return successful data also raise exception error clearly i consider code try parseresult parsemyfile except myerrorclass e handleerrorssomehowstre def parsefile file list lines actual file err false result lines file processedline processline processedline err true else resultappendprocessedline return result err raise myerrorclasssomething went wrong obviously last three lines make sense i figure nice way i guess i could return err result call like parseerr parseresult parsefile parseerr handleerrorssomehow but returning error codes seems unpythonic enough let alone returning tuples error codes actual result values the fact i feel like i want something strange application really terribly complicated making think i probably something wrong is better solution problem or way i use finally return value raise exception time
1
depending caller design using callbacks might reasonable def gotlineline print got valid line line def goterrorerror print got error error def parsefile line error lines file processedline processline processedline errormyerrorclasssomething went wrong else lineprocessedline parsesomefile gotline goterror
i number functions parse data files usually returning list results if i encounter dodgy line file i want soldier process valid lines return but i also want report error calling function the reason i want report calling function notify user file needs looking i want start gui things parse function seems big violation separation concerns the parse function access console i writing error messages anyway this leaves wanting return successful data also raise exception error clearly i consider code try parseresult parsemyfile except myerrorclass e handleerrorssomehowstre def parsefile file list lines actual file err false result lines file processedline processline processedline err true else resultappendprocessedline return result err raise myerrorclasssomething went wrong obviously last three lines make sense i figure nice way i guess i could return err result call like parseerr parseresult parsefile parseerr handleerrorssomehow but returning error codes seems unpythonic enough let alone returning tuples error codes actual result values the fact i feel like i want something strange application really terribly complicated making think i probably something wrong is better solution problem or way i use finally return value raise exception time
1
you kill python interpreter ctrl this send sigquit instead sigint
usually i interrupt stuff ctrlc sometimes i using threads work example python r apr gcc linux type help copyright credits license information import time timesleep ctraceback recent call last file stdin line module k eyboardinterrupt import queue q queuequeuemaxsize qput qput qput qput cccccccc ccc cc c edit is way get back interpreter solutions far kill python completely existing namespace
2
well i new python seems proccommunicate procstdoutreadlinereadlines waits till process completed as per knowledge implement rotational logging redirect output file using subprocess fire tailf n xx logfile loop program ends print output whenever request user end
i subprocess constantly producing data data i interested however occasionally random times i need grab sample output thing i need read well defined boundaries for example let assume process produces constant bytes per second useful information comes chunks bytes after running seconds i ask see bytes output i would interested bytes inclusive but i ask seconds i want intercept get bytes i need wait see bytes otherwise process happily streaming output devnull i want ever block output stream my friend fred might also ask bytes say seconds i also need tee stuff make data available multiple consumers reading is existing design pattern kind thing how i implement python subprocess ensure communication subprocess nonblocking
1
finally i created login view calls djangocontribauthviewslogin internally
i added djangocontribauthviewslogin everywhere webpage i load templatetag returns authenticationform basehtml this templatetags includes registrationloginhtml template the login working ok i want redirect users page login now redirects whereveriamlogin wich shows registrationloginhtml login ok login fails messages without rest basehtml i followed django documentation so questions like i cannot redirect correctly i modified next variable seem work next requestgetfullpath redirects whereveriamlogin have tried something similar ideas update now question could something like do i declare login view i want include login form everywhere web page thank
1
a quick workaround c failing suspending process threads first z killing this works linux many cases c fails i tested works tested python v python r apr gcc linux type help copyright credits license information import queue q queuequeuemaxsize qput qput qput c keyboardinterrupt kill process z suspends exits shell stopped python mdf kill killed python
usually i interrupt stuff ctrlc sometimes i using threads work example python r apr gcc linux type help copyright credits license information import time timesleep ctraceback recent call last file stdin line module k eyboardinterrupt import queue q queuequeuemaxsize qput qput qput qput cccccccc ccc cc c edit is way get back interpreter solutions far kill python completely existing namespace
1
cselect inbox readonlytrue range typ msgdata cfetchstri rfc responsepart msgdata isinstanceresponsepart tuple msg emailmessagefromstringresponsepart header subject print headerupper msgheader this give idea retrieve subject
i using pythons imaplib connect gmail account i want retrieve top messages unread read matter display subjects sender name address know display contents inbox here code far successful connection import imaplib mail imaplibimapssl imapgmailcom maillogin mygmailgmailcom somecrazypassword maillist mailselect inbox need add stuff maillogout i believe simple enough i familiar enough commands imaplib library any help would must appreciated update thanks julian i iterate message retrieve entire contents typ data mailsearchnone all num datasplit typ data mailfetchnum rfc print message snsn num data mailclose i wanting subject sender is imaplib command items i parse entire contents data text subject sender update ok got subject sender part working iteration done desc order apparently showing oldest messages first how i change i tried range lendata lendata print data gives none iterations ideas i also tried mailsort reverse date utf all gmail doesnt support sort function update figured way code except need import email module mailselect inbox typ data mailsearchnone all ids data idlist idssplit get recent email id latestemailid int idlist iterate messages decending order starting latestemailid dictates reverse looping order range latestemailid latestemailid typ data mailfetch rfc responsepart data isinstanceresponsepart tuple msg emailmessagefromstringresponsepart varsubject msg subject varfrom msg remove brackets around sender email address varfrom varfromreplace varfrom varfromreplace add ellipsis subject length greater characters len varsubject varsubject varsubject print varfromsplit varsubject gives recent message subject sender address decending order requested thanks helped
3
you might want constantly read given stdout chunks bytes then list consumers might implemented functions taking stringsbytestrings depending x x each chunk sent every consumer discarded something like def fas pass def fbs pass consumers fa fb true chunk processstdoutread chunk break something like c consumers cchunk if run thread modify consumers wantneed but take care consumers block otherwise loop blocks that problem last long os gives quite large buffer subprocess but infinite so might need add buffering either per consumer loop
i subprocess constantly producing data data i interested however occasionally random times i need grab sample output thing i need read well defined boundaries for example let assume process produces constant bytes per second useful information comes chunks bytes after running seconds i ask see bytes output i would interested bytes inclusive but i ask seconds i want intercept get bytes i need wait see bytes otherwise process happily streaming output devnull i want ever block output stream my friend fred might also ask bytes say seconds i also need tee stuff make data available multiple consumers reading is existing design pattern kind thing how i implement python subprocess ensure communication subprocess nonblocking
1
since using django builtin developement server try remove following line urlspy urlpatterns staticfilesurlpatterns in production de better serve static files django use collectstatic command edit if settingspy try something like staticroot ospathjoinospathdirnamefile static staticurl static
i configured static settings like staticroot ospathjoinsiteroot static staticurl static staticfilesdirs js ospathjoinstaticroot js css ospathjoinstaticroot css staticfilesfinders djangocontribstaticfilesfindersfilesystemfinder djangocontribstaticfilesfindersappdirectoriesfinder djangocontribstaticfilesfindersdefaultstoragefinder urlspy urlpatterns patterns urlr login login name login urlr logout logoutthenlogin name logout urlr profilepuseridd profilesviewsdetail urlr profileedit profilesviewsedit urlpatterns staticfilesurlpatterns it works well url localhostlogin i get localhostprofileedit site handled profiles app staticurl changes paths static profilestatic javascripts stylesheets found what i wrong edit here would basehtml doctype html html head titleneighr block title endblock title meta httpequivcontenttype contenttexthtml charsetutf script typetextjavascript src staticurl jsjqueryminjsscript block script endblock head body block content endblock body html
1
i dont think something built django many many relation less connection table one possible solution would something like class bookmodelsmodel pass class bookconnectionmodelsmodel book modelsforeignkeybook contenttype modelsforeignkeycontenttype objectid modelspositiveintegerfield contentobject genericgenericforeignkey contenttype objectid class somemodelmodelsmodel pass class someothermodelmodelsmodel pass connect book models book bookobjectscreate somemodelobjectscreate somemodelobjectscreate someothermodelobjectscreate bookconnectionobjectscreatebookbook contentobjectm bookconnectionobjectscreatebookbook contentobjectm bookconnectionobjectscreatebookbook contentobjectm
i want make book model belongs multiple libraries collections references editors together is possible generic relations like contenttype genericgenericmanytomanycontenttype djangoconf import settings djangocontribcontenttypes import generic djangocontribcontenttypesmodels import contenttype djangodb import models djangoutilstranslation import ugettextlazy librarynamemaxlength getattrsettings librarynamemaxlength class librarymodelsmodel name modelstextfieldmaxlengthlibrarynamemaxlength verbosenameu desc modelstextfield class meta verbosename ulibrary verbosenameplural ulibraries class collectionmodelsmodel name modelstextfield description modelstextfield period modelstextfield class meta verbosename ucollection verbosenameplural ucollections class editormodelsmodel blabla class referencemodelsmodel title modelstextfield isbn modelstextfield editor modelsforeignkeyeditor pubdate modelsdatetimefieldautonowaddtrue def unicodeself return us selftitle selfisbn class meta ordering pubdate verbosename ureference verbosenameplural ureferences class bookmodelsmodel contenttype modelsforeignkeycontenttype objectpk modelstextfield contentobject genericgenericforeignkeyctfieldcontenttype fkfieldobjectpk title modelstextfield cover modelstextfield fields class meta verbosename ubook verbosenameplural ubooks
1
i use ironpythontoolsscriptspycpy create exe xcopy deployment instead installer
i using sharpdevelop visual studio ironpython app development i reasons using app development what console based options compiling ironpython exe file packaging manually is possible create executable app ironpython pack using installer
2
you try sqlalchemy the sqlalchemy object relational mapper presents method associating userdefined python classes database tables instances classes objects rows corresponding tables you refer following links httpwwwsqlalchemyorgdocs httpwwwrmunncomsqlalchemytutorialtutorialhtml
is module available connection mssql python i downloaded pymssql python is equivalent module python i aware anyone provide links important note meantime pymssql module available don miss read answer end page httpstackoverflowcoma
2
as jitter points earlier answer syscurrentframes gives need v for lazy following code snippet worked may help print sysstderr n stacktrace start n code threadid stack syscurrentframesitems codeappendn threadid threadid filename lineno name line tracebackextractstackstack codeappend file line filename lineno name line codeappend linestrip line code print sysstderr line print sysstderr n stacktrace end n
i trying dump list active threads including current stack i get list threads using threadingenumerate figure way get stack background a zopeplone app freaks time time consuming cpu needs restarted i feeling loop terminate properly cannot reproduce testenvironemt verification i managed register signal handler triggered outside trigger code soon situation occurs if i could dump stacktrace active threads would give clue goes wrong the hole thing runs python any ideas trace situations like appreciated cheers chriss
3
imho update happen automatically treeview connect treeview correctly dragdataget dragdatareceived methods and allows source destination enablemodeldragdest enablemodeldragsource methods there nothing treeview the model must updated calls dragdatareceiveddata delete specific insertbefore insertafter shown def dragdatareceiveddataself treeview context x selection info etime model treeviewgetmodel data selectiondata dropinfo treeviewgetdestrowatposx dropinfo path position dropinfo iter modelgetiterpath position gtktreeviewdropbefore position gtktreeviewdropintoorbefore modelinsertbeforeiter data else modelinsertafteriter data else modelappenddata contextaction gtkgdkactionmove contextfinishtrue true etime return this snippet comes httpwwwpygtkorgpygtktutorialsectreeviewdraganddrophtmldragdropreordering program treeviewdndpy works perfectly show need hope solves quest
i custom generictreemodel works fine now i want user able rearrange nodes using drag drop i move node new parent data model however treemodel wants notified using methods like rowhaschildtoggled rowdeleted rowinserted so apparently rowmoved calling rowdeleted original path rowinserted new path seems enough so i thought i may recursively issue changes consider following example a b c d now i move c a following things happened rowdelete c rowdelete d rowinserted c rowinserted d childtoggle a childtoggle b childtoggle c however gtk still complains inconsistent state model two things come mind maybe order calling functions relevant idea technically childtoggle also happens however row already deleted b rowhaschildtoggled needs treeiter reference i get exist maybe i following totally wrong approach what’s best way go
1
have look documentation universal feed parser the frontpage nothing examples import feedparser feedparserparsehttpfeedparserorgdocsexamplesatomxml feed title feed data dictionary u sample feed
i trying make atom reader python i familiar php i want equivalent commands python if i using php i would use filegetcontents parse atom maybe use simplexml parser is equivalent commands like filegetcontents also i downloaded universal feed reader python rssatom reader module but i cannot find example i want see least example using universal feed reader
3
you also use pyodbc connect mssql python the recent version available python from getting started guide import pyodbc cnxn pyodbcconnect driversql serverserverlocalhostdatabasetestdbuidmepwdpass cursor cnxncursor cursorexecuteselect userid username users rows cursorfetchall row rows print rowuserid rowusername the sqlalchemy library mentioned another answer uses pyodbc connect mssql databases tries various libraries pyodbc preferred one example code using sqlalchemy sqlalchemy import createengine engine createenginemssqlmepasslocalhosttestdb row engineexecuteselect userid username users print rowuserid rowusername
is module available connection mssql python i downloaded pymssql python is equivalent module python i aware anyone provide links important note meantime pymssql module available don miss read answer end page httpstackoverflowcoma
3
there many ways get up status network interface via polling ranging simply parsing ifconfig output reading status procnet pseudofiles however way notified ie poll events best option ubuntu use netplug package it installed default need sudo aptget install netplug some documentation httpmanpagesubuntucommanpageslucidmannetplugdhtml to set need tweak etcnetplugnetplugdconf etcnetplugnetplug scripts for example config files check section configuring netplug httpnatisbadorgdynnetindexhtml with etcnetplugnetplug python script called network goes downup generate kind event application
i writing python application running linux i want able register notified system network cable plugged i already using pyudev python bindings libudev order get notified usb plug events however network eth module example always remains loaded regardless cable plugged i dont get information i require it works updown events i read lot posts windows wmi providing functionality none linux am i looking right direction a python way python library would ideal i want integrate program
1
this valid equality function since transitive mfloat mfloat mfloat mfloat mfloat also note order used set must override hash following property holds instances b class b ⇒ hasha hashb set finds hashmfloat hashmfloat since set assumes property holds concludes mfloat mfloat without actually calling eq in summary works math import floor class ffloatfloat def eqselfother return floorself floorother def hashself return floorself mapffloat printseta output
a person asked question so get list unique function python alternative equality function i thinking could done inheriting element class overloading equality function import functools functoolstotalordering class ffloatfloat def eqselfother floorself floorother return true else return false def leselfother self return true else return floatself floatother def hashself return floorself mapffloat in out true in seta out set edit replaced abs equality floor equality added hash ps way make class factory class two lambda returns class inherits first one overriding needed equality function
3
el oslistdir cusersmyuser try check open show folder except windowserror pass
i working python javascript i problem specific part program i need show userclient contents specific directory i using python oslistdir this function giving contents directory even inaccessible folders i want show userclient i give example while exploring directory cusersmyuser i get oslistdir in oslistdir cusersmyuser out eclipse gimp hdfview matplotlib pylintd recentlyusedxbel xy appdata application data aptana rubles contacts cookies definixexfes locais desktop documents downloads dropbox favorites installanywhere links menu iniciar modelos music my documents nethood opensignals files os meus documentos pictures printhood recent saved games scitesession searches sendto thumbsdb tracing videos workspace ipython i access given folders for example application data cookies menu iniciar portuguese start menu modelos os meus documentos portuguese my documents nethood printhood sendto if i try access python i get error windowserror traceback recent call last cuserspluxipython console module windowserror error denied access cuserspluxcookies so question i detect inaccessible folders skip show user folders explore
2
your phylip file broken the header says sequences fixing current version biopython seems load file fine maybe use leninfoplex creating header line ps it would good idea include version biopython question
i trying something similar previous question my purpose join sequences equal but time instead letters i numbers alignment file found phylip file problem i try records listseqioparsefilefilename phylip i get error valueerror sequence length expected length i understand second file i creating first one worked perfectly below code used build alignment file flwrite flwritestr flwrite flwritestrsize flwrite n infoplex ref hrv flwritestri num leni flwrite num x flwritestrx flwrite n so interpret number since string any ideas thank
1
how utilizing inlineformsetfactory formfieldcallback param instead providing formset provide callable turns returns field used form form fields callback gets st parameter field kwargs optional params eg widget for example using requestuser filter replace another needed def myviewrequest setup code def getfieldqsfield kwargs formfield fieldformfieldkwargs fieldname client formfieldqueryset formfieldquerysetfilteruserrequestuser return formfield attendanceformset inlineformsetfactory formfieldcallbackgetfieldqs formset attendanceformsetrequestpost instancesession to better understand see usage formfieldcallback django formset code
i using inlineformsetfactory create fields many many relationship clients sessions intermediary attendance model i following views file attendanceformset inlineformsetfactory session attendance formsetbaseattendanceformset exclude user extra maxnum session sessionuserrequestuser formset attendanceformsetrequestpost instancesession and i needed override one form fields i added following formset base class class baseattendanceformsetbaseformset def addfieldsself form index superbaseattendanceformset selfaddfieldsform index formfields client formsmodelchoicefield querysetclientobjectsfilteruser now form works correctly i need pass value formset i filter clients displayed based current user rather using id can anyone help any advice appreciated thanks edit for anyone reading worked def getfieldqsfield kwargs fieldname client return formsmodelchoicefieldquerysetclientobjectsfilteruserrequestuser return fieldformfieldkwargs
3
myfile mylist osaccessmyfile osrok mylistpopmylistindexmyfile list include paths else need modify loop depending attributes
i working python javascript i problem specific part program i need show userclient contents specific directory i using python oslistdir this function giving contents directory even inaccessible folders i want show userclient i give example while exploring directory cusersmyuser i get oslistdir in oslistdir cusersmyuser out eclipse gimp hdfview matplotlib pylintd recentlyusedxbel xy appdata application data aptana rubles contacts cookies definixexfes locais desktop documents downloads dropbox favorites installanywhere links menu iniciar modelos music my documents nethood opensignals files os meus documentos pictures printhood recent saved games scitesession searches sendto thumbsdb tracing videos workspace ipython i access given folders for example application data cookies menu iniciar portuguese start menu modelos os meus documentos portuguese my documents nethood printhood sendto if i try access python i get error windowserror traceback recent call last cuserspluxipython console module windowserror error denied access cuserspluxcookies so question i detect inaccessible folders skip show user folders explore
1
the easiest way i think contents open file f line f linestartswith start pass contentsappendline contents joincontents sections contentssplitstop basically make use pattern behavior store list use pattern get sections
a file programinputtxt content start content stop start content stop how i iterate txt file i take content store different file iteration
1
i found powermock library suitable java resembels mockspy
following cool mocking python anyway also java mockpath ospath mockpathisdir mockreturnvaluefalse myobj myclass myobjinvokesomemethod myobjsomeothermethodassertcalledwithfalse anything like possible java meaning updating return values behavior objects instantiated inside object methods convenient way framework nicely thanks
1
your code work i taken liberty adapt bit imports also know document selfcon make compatible python i use moment works future import withstatement import threading queue urllib contextlib class threaderthreadingthread def initself queue url host threadingthreadinitself selfqueue queue selfurl url selfhost host def runself print selfurl contextlibclosingurlliburlopenselfurl u source uread print hey main name threaderqueuequeue httpwwwstackoverflowcom tstart tjoin edit works also contextlib
i figure problem code class threaderthreadingthread def initself queue url host threadingthreadinitself selfqueue queue selfurl url selfhost host def runself print selfurl httpwwwstackoverflowcom contextlibclosingurlliburlopenselfurl u source uread print hey printing source selfcon doc documentsource selfqueueputdoc selfhost when i run code print selfurl succesfully outputs url print hey working so basically i believe something contextlib blocking code i also tried conventional urlopen method without using contextlib work either furthermore i tried try except program raise error so may problem
1
i sure get buffer changed event however might good idea look connecting signal preeditchanged entry the preeditchanged signal emitted input method used typed text immediately committed buffer so interested text connect signal and get input check valid manipulate fields value accordingly
i want user able type float numbers decimal point show characters how i edit i need get values like nothing like e inconsistent values also rejected
1
port name incorrect correct ports pygtk pygtk pygtk updated recently renamed pypygtk pypygtk pypygtk
my python code uses gtk gui need run osx snow leopard lion unfortunately unofficial pygtk build crashes window gtk windows resize decided test macports version i installed python pygtk via following macports commands sudo port install python sudo port select set python python sudo port install pygtk running python console correctly starts macports version python but trying execute import gtk import pygtk fails error package available i feeling i missed something simple get work something like setting correct sitepackage macports python whatever maybe guru may share bit wisdom update careful examination revealed pygtk installed optlocallibpythonsitepackages leaving pythonsitepackages pythonsitepackages blank running macports version python allows use pygtk but i want python preferred
3
i want address question holidays in several reporting databases i found handy define table let call almanac one row date within certain range if range spans ten years table contain rows that small today standards the primary key date some columns things like whether date holiday normal working day weekend day i know i know could compute weekend stuff using built function but turns convenient include stuff data it makes joins simpler similar then one application program populates almanac it calendar quirks built including enterprise rules figuring days holidays you even include columns fiscal month given date belongs relevant case the rest application entry programs extraction programs treat almanac like plain old data this may seem suboptimal minimal but trust design pattern useful wide variety situations it figure applies case the almanac really subset principles data warehousing star schema design want thing inside cpu could almanac object public features almanacholidaydate
i building calendar system ground requirement i working special type calendar alongside gregorian i need help logic i writing application django python essentially logical issues i running persist objects possible smartly possible without running tab cpu cycles i feeling polymorphism would solution i exactly sure express i two basic subsets events repeating events oneshot events repeating events subscribers people notified changes if example class canceled moved different address time people subscribed need know some events simply happen every day end time edited happen the problem i one object stores event info repeating policy canceling modifying one event series really screws things i account somehow keeping subscribers aware change keeping series together logical group paradox generating unique event objects normal event series end time repeats indefinitely make sense going store information however change happens single event series i almost create different object database represent cancellation can someone help logic it really twisting mind i really think straight anymore i really like input solve issue repeating events exactly easiest logical thing either repeat every day every mwf st m month every months year date week date month date tuesdays thursdays etc i like help understanding best route logic repeating events well here thought class eventseriesmodelsmodel seriesname modelstextfield seriesdescription modelstextfield seriesrepeatpolicy modelsihavenoideaintheworldonhowtorepresentthisfield seriesdefaulttime modelstimefield seriesstartdate modelsdatefield seriesenddate modelsdatefield location modelsforeignkey location class eventseriesanomalymodelsmodel eventseries modelsforeignkey eventseries relatednameexceptions overridename modelstextfield overridedescription modelstextfield overridetime modelstimefield overridelocation modelsforeignkey location eventdate modelsdatefield class eventseriescancellationmodelsmodel eventseries modelsforeignkey eventseries relatednamecancellations eventdate modelstimefield cancellationexplanation modelstextfield this seems make bit sense stated ruining brain right anything seems like would work another problem question someone wants modify remaining events series heck i i suppose i could change seriesdefaulttime generate anomaly instances past instances set original time ahhhhhh boiling three simple concrete questions how i series repeating events yet allow cancellations modifications individual events modifications rest series whole storing objects database absolutely necessary never generating objects individual events advance how i repeat events highly customizable way without losing mind i allow events repeat number ways making things easy storing objects possible how i allowing switch event series make happen falls holiday
1
joblib handles result caching quite transparent way here example documentation joblib import memory mem memorycachedir tmpjoblib import numpy np npvandernparange square memcachenpsquare b squarea memory calling square squarearray square min c squarea the call trigger evaluation result cached the calculation results automatically saved disk joblib might suit needs
i program slow computations i wish debug algorithm now tedious always rerun everything i rather restart middle program can think clever way achieve the first vague idea define checkpoints i make function call i save locals large data pickle andor sqlite sqlite able inspect intermediate data later i could try call program telling restart specific checkpoint however i want split code chunks checkpoints purpose has someone clever idea solve debugging issue
1
the rawinput call blocking use asyncore you need add third player ie like class cmdlineclientasyncorefiledispatcher def initself sender file asyncorefiledispatcherinitself file selfsender sender def handlereadself selfsenderbuffer selfrecv import sys sender sender cmdline cmdlineclientsender sysstdin
i trying learn asyncore module so i decided develop chat program i listen network broadcast udp packages time but problem user typing message user cannot see messages sent another users what i my code usrbinpython coding utf import asyncore import socket class listenerasyncoredispatcher def initself port asyncoredispatcherinitself selfport port selfcreatesocketsocketafinet socketsockdgram selfsetsockoptsocketsolsocket socketsoreuseaddr selfbind selfport def handleconnectself print connected def handlereadself data addr selfrecvfrom print straddr data def handlewriteself pass class senderasyncoredispatcher def initself port asyncoredispatcherinitself selfbuffer selfport port selfcreatesocketsocketafinet socketsockdgram selfsetsockoptsocketsolsocket socketsobroadcast selfbind def handleconnectself print connected def handlereadself pass def handlewriteself selfbuffer sent selfsendtoselfbuffer broadcast selfport selfbuffer selfbuffersent def handlecloseself selfclose def serveforeverself asyncoreloopcount name main listener sender sender true senderserveforever senderbuffer rawinputmessage
3
i finally acceptable answer thanks so question how extract floating number string python numericconstpattern r optional sign etc etc etc etc etc followed optional exponent part desired ee selfrx recompilenumericconstpattern reverbose init part def validatefloatself widget entry entrytext entrygettext newtext selfrxfindallentrytext lennewtext entrysettextnewtext else entrysettext connected changed event entry many thanks helped
i want user able type float numbers decimal point show characters how i edit i need get values like nothing like e inconsistent values also rejected
1
if selecting trailing axes reshape trailing axes apply func axis def ffunc array start shape arrayshape tmp arrayreshapeshapestart indices functmp axis return npunravelindexindices shapestart
i writing code optimize quantities depend variable number parameters for optimization i would like apply index selecting functions numpyargmax numpyargmin across multiple axes below code i using right is builtin efficient approach perform task across arbitrary number axes may may sequential def ndargaxesfunc array start applies index selecting function trailing axes start ntrail lenarrayshapestart number trailing axes apply indices npzerosntrailarrayshapestart dtypenpintp npndindexarrayshapestart indicesellipsisi npunravelindexfuncarrayi arrayshapestart return tupleindices test showing ndargaxes indeed return correct indices array nparangereshape maxjs ndargaxesnpargmax array arraytuplenpindicesarraymaxjs npsqueezenpapplyoveraxesnpamax array axes
1
more work would put xpathlike selector would work valid dictionary key would foo eggs ham handled fooselect would ambiguous
is way define xpath type query nested python dictionaries something like foo spam eggs morefoo bar soap morebar bacon foobar print fooselectmorefoomorebar bacon foobar i also needed select nested lists this done easily jellybean solution def xpathgetmydict path elem mydict try x pathstripsplit try x intx elem elemx except valueerror elem elemgetx except pass return elem foo spam eggs morefoo bar soap morebar bacon bla balbla bla print xpathgetfoo morefoomorebarbacon edit this question accepted answer ancient the newer answers may job better original answer however i test i change accepted answer
1
is reason query way like xpath pattern as commenter question suggested dictionary access elements nest manner also considering data form json use simplejson module load access elements there project jsonpath trying help people opposite intend given xpath make easily accessible via python objects seems useful
is way define xpath type query nested python dictionaries something like foo spam eggs morefoo bar soap morebar bacon foobar print fooselectmorefoomorebar bacon foobar i also needed select nested lists this done easily jellybean solution def xpathgetmydict path elem mydict try x pathstripsplit try x intx elem elemx except valueerror elem elemgetx except pass return elem foo spam eggs morefoo bar soap morebar bacon bla balbla bla print xpathgetfoo morefoomorebarbacon edit this question accepted answer ancient the newer answers may job better original answer however i test i change accepted answer
1
the following function performs required editing operations transpose contents current buffer fut letmnsline ldgpurjs glet mmaxmcol exe norm ma em d silnorms exe norm n gj endf below oneline version letmnsline ldgpurjsexe glet mmaxmcol exe norm ma em d exe silnorms exe norm n gj
i know i use awk i windows box i making function others may awk i also know i write c program i would love create maintain compile something little vim utility i making the original file might the day was long the way was fast would become tt hh ee dw aa yy ww aa ss lf oa ns gt update golf rules apply selecting correct answer update python fans check mr duffy answer
1
not exactly beautiful might use sth like def xpathgetmydict path elem mydict try x pathstripsplit elem elemgetx except pass return elem this support xpath stuff like indices course mention key trap unutbu indicated
is way define xpath type query nested python dictionaries something like foo spam eggs morefoo bar soap morebar bacon foobar print fooselectmorefoomorebar bacon foobar i also needed select nested lists this done easily jellybean solution def xpathgetmydict path elem mydict try x pathstripsplit try x intx elem elemx except valueerror elem elemgetx except pass return elem foo spam eggs morefoo bar soap morebar bacon bla balbla bla print xpathgetfoo morefoomorebarbacon edit this question accepted answer ancient the newer answers may job better original answer however i test i change accepted answer
2
another alternative besides suggested jellybean def querydictd q keys qsplit nd k keys k continue k nd nd ndk else return none return nd foo spam eggs morefoo bar soap morebar bacon foobar print querydictfoo morefoomorebar
is way define xpath type query nested python dictionaries something like foo spam eggs morefoo bar soap morebar bacon foobar print fooselectmorefoomorebar bacon foobar i also needed select nested lists this done easily jellybean solution def xpathgetmydict path elem mydict try x pathstripsplit try x intx elem elemx except valueerror elem elemgetx except pass return elem foo spam eggs morefoo bar soap morebar bacon bla balbla bla print xpathgetfoo morefoomorebarbacon edit this question accepted answer ancient the newer answers may job better original answer however i test i change accepted answer
1
may metaclasses best choice needs lowlevel type but cases use name value module like mymodel type mymodel modelsmodel field modelsbooleanfield module name django uses module value determine django app owns model models myappmodelspy contain myappmodels django knows models filemodule belongs myapp application
i attempting dynamically construct classes subclasses django modelsmodel my code looks like mymodel type mymodel modelsmodel field modelsbooleanfield when django tries load gives following exception traceback recent call last file usrlibpythonsitepackagesdjangocoremanagementcommandsrunserverpy line innerrun selfvalidatedisplaynumerrorstrue file usrlibpythonsitepackagesdjangocoremanagementbasepy line validate numerrors getvalidationerrorss app file usrlibpythonsitepackagesdjangocoremanagementvalidationpy line getvalidationerrors appname error getapperrorsitems file usrlibpythonsitepackagesdjangodbmodelsloadingpy line getapperrors selfpopulate file usrlibpythonsitepackagesdjangodbmodelsloadingpy line populate selfloadappappname true file usrlibpythonsitepackagesdjangodbmodelsloadingpy line loadapp models importmodule models appname file usrlibpythonsitepackagesdjangoutilsimportlibpy line importmodule importname file homeuserprojectappmodelspy line module field modelsbooleanfield file usrlibpythonsitepackagesdjangodbmodelsbasepy line new module attrspop module keyerror module it seems like class constructed using type getting module member present class defined class what going
3
i think best way sort plugin thing using entrypoints api querying
while fairly trivial python import child module another module list attributes becomes slightly difficult want import child modules i building library tools existing d application each tool menu item sub menus i like tool responsible creating menus many change based context templates i like base module able find child modules check createmenu function call finds what easiest way discover child modules
1
you looking ospathwalk globglob enumerating files directory subtree osstat oslstat getting timestamp recent modification
i given task converting c script python script the aim script loop directories start end date mediadb calculate size zipfile going i stuck getting loop go directories different python c experience could anyone offer suggestions c code this loop core files directory sum file size directoryiterator diritmediadbcorefilesdir directoryiterator diritmediadbcorefilesdirdiritdirectoryiteratordirit also anyone ideas get last update timestamp file python would much appreciated the c code get last update timestamp file stdtimet lastwritetimedirit ptime filetimestamp fromtimett edit trying write statement firstly loops directories sums file size i dont need edit delete print directories get file sizes is appropriate use oswalk ospathgetsize secondly need retrieve last updated timestamp files tho dont really understand process getting timestamp
1
pep added support bytes literal python python adopted unicode language’s fundamental string type denoted bit literals either b string using bytes constructor for future compatiblity bytes introduced python but note bytes different serves different purpose x bytes the accurate concise explaination inclusion bytes python given new document
since version bytes function exist python i writing code compatible much versions python possible kind information important is good source find answer questions easily
3
i tell generatetilespy originally modified slightly a memoryerror indicates either requesting abnormally large image rendered found mapnik bug since former likely i figure made mistake modification generatetilespy so i took script overwrote latest version svn got diff differences httpsgistgithubcom on line likely want use otherwise making large x values invalid may cause large image requests wrong given tile
i trying create tiles using generatetilespy every time i run script i get following error exception thread thread traceback recent call last file usrlibpythonthreadingpy line bootstrapinner selfrun file usrlibpythonthreadingpy line run selftargetselfargs selfkwargs file rendertilespy line loop selfrendertiletileuri x z file rendertilespy line rendertile mapnikrenderselfm im memoryerror here script usrbinpython math import picossinlogexpatan subprocess import call import sys os queue import queue import mapnik import threading import random import argparse customfontsdir usrsharefonts mapnikregisterfontscustomfontsdir degtorad pi radtodeg pi default number rendering threads spawn roughly equal number cpu cores available numthreads def minmax abc maxab minac return class googleprojection def initselflevels selfbc selfcc selfzc selfac c rangelevels e c selfbcappendc selfccappendc pi selfzcappendee selfacappendc c def fromlltopixelselfllzoom selfzcintzoom e roundd floatll selfbczoom f minmaxsindegtorad floatll g roundd logffselfcczoom return eg def frompixeltollselfpxzoom e selfzczoom f px eselfbczoom g px eselfcczoom h radtodeg atanexpg pi return fh class renderthread def initself tiledir mapfile q printlock maxzoom selftiledir tiledir selfq q selfm mapnikmap selfprintlock printlock load style xml mapnikloadmapselfm mapfile obtain projection selfprj mapnikprojectionselfmsrs projects tile pixel coordinates latlong epsg selftileproj googleprojectionmaxzoom def rendertileself tileuri x z calculate pixel positions bottomleft topright p x p x convert latlong epsg l selftileprojfrompixeltollp z l selftileprojfrompixeltollp z convert map projection eg mercator coords epsg c selfprjforwardmapnikcoordll c selfprjforwardmapnikcoordll bounding box tile hasattrmapnik mapnikversion mapnikmapnikversion bbox mapnikboxdcxcy cxcy else bbox mapnikenvelopecxcy cxcy rendersize selfmresizerendersize rendersize selfmzoomtoboxbbox selfmbuffersize render image default agg renderer im mapnikimagerendersize rendersize mapnikrenderselfm im imsavetileuri png def loopself true fetch tile queue render r selfqget r none selfqtaskdone break else name tileuri x z r exists ospathisfiletileuri exists exists else selfrendertiletileuri x z bytesosstattileuri empty bytes empty empty tile selfprintlockacquire print name z x exists empty selfprintlockrelease selfqtaskdone def rendertilesbbox mapfile tiledir minzoommaxzoom nameunknown numthreadsnumthreads print rendertilesbbox mapfile tiledir minzoom maxzoom name launch rendering threads queue queue printlock threadinglock renderers rangenumthreads renderer renderthreadtiledir mapfile queue printlock maxzoom renderthread threadingthreadtargetrendererloop renderthreadstart print started render thread renderthreadgetname renderersi renderthread ospathisdirtiledir osmkdirtiledir gprj googleprojectionmaxzoom bboxbbox bboxbbox z rangeminzoommaxzoom px gprjfromlltopixelllz px gprjfromlltopixelllz print fromlattolon check directories place zoom z ospathisdirtiledir zoom osmkdirtiledir zoom x rangeintpxintpx validate x coordinate x z continue check directories place strx x ospathisdirtiledir zoom strx osmkdirtiledir zoom strx rangeintpxintpx validate x coordinate z continue stry tileuri tiledir zoom strx stry png submit tile rendered queue name tileuri x z queueputt signal render threads exit sending empty request queue rangenumthreads queueputnone wait pending rendering jobs complete queuejoin rangenumthreads renderersijoin name main minlon maxlon minlat maxlat bbox minlon minlatmaxlon maxlat stylefilehomemossplixprojectsdevmapitmapstatictilemillugandadistrictsxml tiledirhomemossplixprojectsunicefdevmapitmapstatictiles minzoom maxzoom rendertilesbbox stylefile tiledir minzoom maxzoom here mapnik config file mapnik config shapefile i compiled mapnik source good could problem
2
this swapping implemented sorted data structures class instances
i big class lots members quite references instances class lying around unfortunately reasonable reasons references wrong way around instead recreating finding updating everywhere objects referenced adding extra level indirection time i access class individually swapping members i defined method def swapself assertisinstanceother selfclass selfdict otherdict otherdict selfdict i instanceaswapinstanceb references instancea everywhere instancea instanceb the question it seems work fine i use slots feels like might reason i here actual use case i type implements comparison operators necessarily expensive way i various sorted datastructures containing objects type when i something one objects i know comparison order changed order data structures restored swapping modified object next bigger one
1
personobjectscreatename adam persontype appellant here persontype argument create method expects get persontype instance string so prowide perstype persontypeobjectsgetperstype appelant assuming perstype unique personobjectscreatename adam perstypeperstype taking account case appellant present db try perstype persontypeobjectsgetperstype appelant except persontypedoesnotexists persontype persontypeobjectscreateperstype appellant personobjectscreatename adam perstypeperstype
i new django sqlite i model person foreign key persontype class personmodelsmodel name modelscharfieldmaxlength perstype modelsforeignkeypersontype def unicodeself return selfname class persontypemodelsmodel perstype modelscharfieldmaxlength def unicodeself return selfperstype i trying add entries person using python managepy shell so far i tried import sqlite trialsmodels import conn sqliteconnect privydb print person returns class privytrialsmodelsperson cur conncursor fields name perstype row adam appellant personobjectscreatedictzipfields row but returns error valueerror cannot assign appellant personperstype must persontype instance the string appellant already stored one values persontypeperstype table what i need change get reference perstype field happy provide details needed thanks much time
2
you could use pythongestreamer playing works linux also work windows this requires pythongstreamer pythongobject i would recommend use allinone installer here code import os import sys import tkinter tkinter import gobject import gst def onsyncmessagebus message windowid messagestructure none messagestructuregetname preparexwindowid imagesink messagesrc imagesinksetproperty forceaspectratio true imagesinksetxwindowidwindowid gobjectthreadsinit window tkintertk windowgeometry x video tkinterframewindow bg videopacksidetkinterbottomanchortkintersexpandtkinteryesfilltkinterboth windowid videowinfoid player gstelementfactorymake playbin player playersetproperty videosink none playersetproperty uri files ospathabspathsysargv playersetstategststateplaying bus playergetbus busaddsignalwatch busenablesyncmessageemission busconnect syncmessageelement onsyncmessage windowid windowmainloop
is way play video files like avi mp etc i tried using pymedia apparently works pygame what solution problem
3
this works python x x fix python x try input rawinput except nameerror pass printhi inputsay something
import sys print sysplatform print rawinput i using python get rawinput freeze dos popup the book i reading i using what i fix
3
import joinllower l refindall azaz thisisagoodexample edit actually works first letter uppercase otherwise taken right thing def convertname resub azaz r name return resub azaz r slower
i new python i trying replace uppercaseletters within word underscores example thisisagoodexample become thisisagoodexample any ideastipslinkstutorials achieve
3
example thisisagoodexample don put underscore first character newexample example character example append underscore character uppercase characterisupper newexample newexample characterlower
i new python i trying replace uppercaseletters within word underscores example thisisagoodexample become thisisagoodexample any ideastipslinkstutorials achieve
1
when turn cherrypy tool particular url turned child url well so images css js parts config seem redundant so robotstxt section the faviconico would redundant except faviconico special cherrypy sets one typically attribute root object see cptreepy so overriding appropriate toolsstaticdiron true toolsstaticdirroot projectsmysitetrunkroot toolsstaticdirdir toolsstaticfileroot projectsmysitetrunkroot faviconico toolsstaticfileon true toolsstaticfilefilename imagesfaviconico
when i try browse faviconico instance i get error valueerror static tool requires absolute filename got faviconico i get anything images css js folders those serving fine the site looks acts great it darn two files here rootconf file toolsstaticdiron true toolsstaticdirroot projectsmysiteroot toolsstaticdirdir faviconico toolsstaticfileon true toolsstaticfilefilename faviconico toolsstaticdiron true toolsstaticdirdir images robotstxt toolsstaticfileon true toolsstaticfilefilename robotstxt toolsstaticdiron true toolsstaticdirdir images toolsstaticdiron true toolsstaticdirdir images css toolsstaticdiron true toolsstaticdirdir css js toolsstaticdiron true toolsstaticdirdir js here cherrypyconf file global serversocketport serverthreadpool toolssessionson true here startwebpy script import cherrypy rootroothandler import root cherrypyconfigupdatecherrypyconf cherrypytreemountroot rootrootconf hasattrcherrypyengine block syntax cherrypyenginestart cherrypyengineblock else syntax cherrypyserverquickstart cherrypyenginestart
3
here regex way import example thisisagoodexample print resub az example lower this saying find points string preceeded start line followed uppercase character substitute underscore then lowercase whole thing
i new python i trying replace uppercaseletters within word underscores example thisisagoodexample become thisisagoodexample any ideastipslinkstutorials achieve
3
indeed traditional cross validation fscore vmeasure scoring function would need labeled data ground truth but case could count number classes ground truth dataset use optimal value k hence noneed crossvalidation alternatively could use cluster stability measure unsupervised performance evaluation kind cross validation procedure however yet implemented scikitlearn even though still personal todo list you find additional info approach following answer metaoptimizecomqa in particular read clustering stability an overview ulrike von luxburg
in document clustering process data preprocessing step i first applied singular vector decomposition obtain u s vt choosing suitable number eigen values i truncated vt gives good documentdocument correlation i read now i performing clustering columns matrix vt cluster similar documents together i chose kmeans initial results looked acceptable k clusters i wanted dig bit deeper choosing k value to determine number clusters k kmeans i suggested look crossvalidation before implementing i wanted figure builtin way achieve using numpy scipy currently way i performing kmeans simply use function scipy import numpy scipy preprocess data compute svd u s vt svda a tfidf representation original termdocument matrix obtain documentdocument correlations vt this threshold obtained examining scree plot s docvectors numpytransposeselfvt prepare data run kmeans whitened whitendocvectors res idx kmeanswhitened iter assuming methodology correct far please correct i missing step stage standard way using output perform crossvalidation any referenceimplementationssuggestions would applied kmeans would greatly appreciated
1
if i mistaken would need git client install machine in event git installed try pip install httpsgithubcomfacebookpythonsdkzipballmaster pip install httpsgithubcomfacebookpythonsdktarballmaster you need install gitcore since git protocol associated anything sudo aptget install gitcore
i trying install package github using pip using following syntax pip install e githttpsgithubcomfacebookpythonsdkgiteggfacebooksdk getting error cannot find command git this question unchecked answers saying git needs installed system however answer states git subversion bazaar mercurial supported pip the pip documentation also says native support version control systems git mercurial bazaar so i install package pip i really want install git vps or nonpip tools pulling files repositories without full git install update i bit bullet installed git vps pip still able grab package giving different set errors progress i finally git clone httpgithubcomfacebookpythonsdkgit note http https manage download package installed manually
3
i using formalchemy httpdocsformalchemyorgpyramidformalchemy pyramid author wrote deform httpsdocspylonsprojectorgprojectsdeformdev
since pyramid form dependencies i need recommendations form handling this covers form generation validation etc i know wtforms i dont mind use thing advanced
2
i think looking findprevious could use way import beautifulsoup import content ul classbobby listrongvolume strongli li class hrefcontentbencchts titleissue september issue september li listrongvolume strongli li class hrefcontentbencchts titleissue december issue december li li class hrefcontentbencchts titleissue november issue november li ul lastvolume lastissue soupbeautifulsoupbeautifulsoupcontent results soupfind ul attrs class bobby astring resultsfindall textrecompile issue volumeastringfindprevioustextrecompile volume volumeintresearchr volumegroup issueintresearchr astringgroup hrefastringparent href volumelastvolume volumelastvolume issuelastissue printvolumeissuehref yields u contentbencchts u contentbencchts
i variables one last volume last issue the html i dealing contains list volumes issues recent first i need return href links volumes issues newer i file so using example say last volume last issue i would need return href vol vol i hard time since volume here i far html ul classbobby listrongvolume strongli li class hrefcontentbencchts titleissue september issue september li listrongvolume strongli li class hrefcontentbencchts titleissue december issue december li li class hrefcontentbencchts titleissue november issue november li ul script snipped results soupfind ul attrs class bobby temp i get reading file lastvol find last volume findlastvol resultsfindnext strong text recompile volume lastvol temp i get reading file lastiss find last issue findlastiss findlastvolfindnext text recompile issue lastiss so i get tag last volume issue file i several failed attempts traversing back stopping first issue or starting top traversing volume issue condition met can someone please give assistance thanks
1
pypy source contains purepython implementation sha poking around directory probably also find purepython implementations standard hashes
i looking implementation sha hash function written python i want use get better understanding sha function works i think python ideal language pseudocode limitation i runtest see modifications code output
3
disclaimer easily done explanation solution as slott pointed definitely technically correct behavior streamclose streamwrite called closed socket however i understand motivation question context wsgi app clients terminating connection full partial read exceptional behavior happens time for left unhandled leaves impression unexpected code unprepared fact expected worthy note so nice fix the catch find way distinguish cases situations like client read status closed connection client read bytes closed connection even though requested connection reused ones would appropriate issue sort logging besides logdebug call but situations like client stopped reading middle file connection died isp router stroke worthy error logged something successfully complete transactional state server app builtup rolled back in case ioerror propagating upwards right thing such errors silenceable every place could raised code modified distinguish two cases until wsgi authors seem erred side caution so quick fix i know also i note djangospecific i use pastepylons thing happen
i iphone app using web services implemented python using django piston running apache server wsgi sometimes app closes connection server call finished when causes tue sep error client modwsgi pid exception occurred processing wsgi script myscriptwsgi tue sep error client ioerror failed write data appear server error logs i fix problem app explicitly closing connection leaving finish downloading ignoring result however i like fix serverside possible how i
3
you set blocking signals using qobjectblocksignals httpdocqtnokiacomstableqobjecthtmlblocksignals bool qobjectblocksignals bool block if block true signals emitted object blocked ie emitting signal invoke anything connected if block false blocking occur the return value previous value signalsblocked note destroyed signal emitted even signals object blocked see also signalsblocked
i populating branch qtreewidget setting expanded attribute parent branch true the itemexpanded signal fires response i want is temporary way suppress absorb signals segment code
2
i really sure think need import sqlalchemyextsqlsoup sqlsoup import sqlalchemy engine sqlalchemycreateengine sqlitetestsqlite db sqlsoupengine res dbpeoplefilterbyid first enginedispose return res use queryfirst queryall create engine separately sqlsoup pass engine you dispose engine afterwards do note new pool created dispose engine database perminantly disconnected open connections closed new connections drawn new pool dispose operation
i using sqlsoup perform simple query my question i close engine thanks import sqlalchemyextsqlsoup sqlsoup db sqlsoup sqlitetestsqlite res dbpeoplefilterbyid return res
1
askopenfile returns opened file name need call open if really want name use askopenfilename instead seem necessary
why error appear error exception tkinter callback traceback recent call last file cpythonliblibtktkinterpy line call return selffuncargs file editorpy line onopen fileopened openfno w typeerror coercing unicode need string buffer file found code httpscodegooglecompchildreneditorsourcebrowsetrunkeditornewpy
2
you create cython declaration file pxd it shall contain declarations classes functions want import
i directory structure mymodule init py a initpy apyx b initpy bpyx in bpyx i want cimport functions aa a regular python import works cimport always fails also i compiling a b separately i figure put setuppy top module can anyone help
1
no a generator asynchronous this multiprocessing if want avoid waiting calculation use multiprocessing package independent process expensive calculation you want separate process calculating enqueueing results your generator simply dequeue available results
i generator takes long time iteration run is standard way yield value generate next value waiting called the generator would called time button pressed gui user would expected consider result button press edit workaround might def initialize res nextgen def btncallback displayres res nextgen res return
3
i think backwards print joinset
basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets
1
joinset the join string method set method
basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets
3
netaddr import allmatchingcidrs netaddr import allmatchingcidrs allmatchingcidrs ipnetwork here usage method helpallmatchingcidrs help function allmatchingcidrs module netaddrip allmatchingcidrsip cidrs matches ip address subnet given sequence ip addresses subnets param ip single ip address subnet param cidrs sequence ip addresses andor subnets return matching ipaddress andor ipnetwork objects provided sequence empty list match basically provide ip address first argument list cidrs second argument a list hits returned
given ip address say i check network say python are general tools python ip address manipulation stuff like host lookups ip adddress int network address netmask int hopefully standard python library
1
the join called string print joinset
basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets
2
nor set list method join string joinset b c by way use name list variables give list mylist name list often used python function
basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets
2
you join statement backwards try print joinset
basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets
1
sets join method use strjoin instead joinset the strjoin method work iterable object including lists sets note careful using sets containing integers need convert integers strings call join for example set joinstrs set
basically i trying join together entries set order output one string i trying use syntax similar join function lists here attempt list gathiitcgmx set setlist set setmx set set set print setjoin however i get error attributeerror set object attribute join what equivalent call sets
3
see httpcodegooglecompmodwsgiissuesdetailid if processing iterable message logged debug level python exception used thus see client closed connection problems iterable used need loglevel debug apparently would need tweak django response iterable instead string
i iphone app using web services implemented python using django piston running apache server wsgi sometimes app closes connection server call finished when causes tue sep error client modwsgi pid exception occurred processing wsgi script myscriptwsgi tue sep error client ioerror failed write data appear server error logs i fix problem app explicitly closing connection leaving finish downloading ignoring result however i like fix serverside possible how i
1
if use lxml module becomes much easier from lxml tutorial parser etreexmlparserremoveblanktexttrue lxmletree root etreexmlroot b b root parser etreetostringroot b rootab broot
is easy way accomplish thing python xsl accomplishes xslstripspace elements so instance following event elem elementtreeiterparsetmpexamplexml elemtag example print elementtreetostringelem example nodes printed spaces line feeds input file children example node removed
2