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 w... | 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... | 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 t... | 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... | 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... | 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 gene... | 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 expre... | 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 in... | 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 w... | 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... | 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 se... | 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 ... | 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 appl... | 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 ... | 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 se... | 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 seq... | 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... | 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 account... | 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 downloa... | 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 reinstall... | 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... | 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 folde... | 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 expre... | 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 b... | 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 par... | 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 httpgarthhumphreyscompainlessdjangomaintenancemodew... | 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... | 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 iteratio... | 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 ... | 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 ... | 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 dropb... | 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... | 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 buff... | 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 proc... | 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 se... | 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 se... | 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... | 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 inte... | 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 with... | 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 stoppe... | 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... | 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 ad... | 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... | 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 inte... | 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 djangocontribstaticfilesfindersdefaultsto... | 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 ... | 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 djang... | 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 c... | 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 ... | 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 dragdatare... | 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... | 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 e... | 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 sqla... | 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 httpmanpagesubuntucommanpageslucidmann... | 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 event... | 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 ... | 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 t... | 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... | 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 b... | 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 k... | 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 ins... | 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... | 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 t... | 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 runse... | 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 se... | 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 cons... | 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 ... | 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 expre... | 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 aut... | 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 progr... | 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 asyncoredispat... | 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 selfrxfind... | 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 star... | 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 exc... | 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 exc... | 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... | 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 exc... | 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 exc... | 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 selfvalidat... | 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 ... | 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 diritmediadbcorefilesd... | 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 pyth... | 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 ... | 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... | 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 assertisins... | 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 persontyp... | 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 m... | 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 pr... | 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 projec... | 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 faviconi... | 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 ... | 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 r... | 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 documenta... | 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 nov... | 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 hr... | 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 impress... | 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 lo... | 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 sign... | 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... | 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 ... | 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 lo... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.