text_a
stringlengths
5
12.3k
text_b
stringlengths
36
15.7k
Score
int64
1
3
if ntop installed look example files usrsharentoppython ubuntu package version least if epydoc installed run make within usrsharentoppythondocs directory generate documentation once about online documentation python ntop engine python api link work correctly seems like bug requires work part user fix link
can anyone point towards tutorials using python api ntop luca deris paper in web interfaces online documentation python engine i think link error does anyone access document repost online
2
one fell swoop divmod the docs divmod found
x x xintx ok x want round say use later way dont know x time real place start even possible know change int want store ever took store right id write statments figure say doent strike best way
3
you correct height attribute change that attribute tell actual height height configured the actual height depends factors much text wrap length font widget geometry managed tkinter font objects measure method lets determine tall wide string given font you get font widget use method determine much space required string
i label i going put content different sizes i would like know high i need make label i size window stay different content sizes i strategy seems complicated i want set label given width wraplength l labelroot l width l wraplength l text testing now i want query label find many lines used l height stays best i able come use lwinfoheight convert height given pixels number lines used nothing dirl seems give information directly strategy fragile font changes changes any suggestions update using brian oakley suggestion similar i got usenet i following approximation solution needs polishing eg take account label breaks whitespace import tkinter tk import tkfont import random import sys def genstr j rno randomrandint retval strj range rno retval hello stri return retval def gendata lh retval rangelh retvalappend genstr return retval data gendata root tktk font tkfontfontfamily times size class lines def init self selflastct remember cutoff last work def count self text cutoff global font nolines startidx idx selflastct true idx len text idx len text shrink guessed value fontmeasure textstartidxidx cutoff idx startidx print error sysexit else idx selflastct idx startidx adjust since big increase guessed value note first shrunk done idx len text fontmeasure textstartidxidx cutoff idx selflastct idx startidx adjust since small next line determined print textstartidxidx idx lentext fontmeasure textstartidx cutoff return nolines elif idx lentext return nolines else nolines startidx idx idx startidx selflastct lin lines rangelendata lincountdatai rangeminlendata l tklabelroot lpack l text datai print lincount datai print computed lines l width l justify tkleft l anchor w l wraplength l padx l pady l height l font font l background grey else l background grey rootmainloop
1
take number modulus
x x xintx ok x want round say use later way dont know x time real place start even possible know change int want store ever took store right id write statments figure say doent strike best way
1
yes exact way wrote your code fine
for example mymessage dear hello name jj print mymessage name does python feature accomplishing something like code
3
python really concept constant find c so fairly good approach i would actually argue one example consenting adults hold terribly well think language awesome constant every would nice
for example mymessage dear hello name jj print mymessage name does python feature accomplishing something like code
2
your code correct i believe preferred way mymessage dear hello mymessageformat jj dear jj hello preferred possible future replacement operator format method as mentioned mark lutz learning python fourth edition format method features found expression make substitution values explicit trades operator arguably mnemonic method name support different syntax single multiple substitution value cases later book risk python developers may deprecate expression favor format method future in fact note effect python manuals
for example mymessage dear hello name jj print mymessage name does python feature accomplishing something like code
1
yield sucks continuations better actually python yield continuation what continuation a continuation saving present point execution state one continue point later that precisely python yield also precisely implemented it understanding python continuations delimited however i know much i might wrong fact nor i know implications may scala continuation work runtime fact continuations library java work stuff bytecode runtime free constrains scala continuation scala continuation entirely done compile time require quite bit work it also requires code continued prepared compiler and forcomprehensions work a statement like x xs procx if translated xsforeachx procx where foreach method xs class unfortunately xs class long compiled cannot modified supporting continuation as side note also scala continue aside yes duplicate question yes find different way write code
i writing code phd research starting use scala i often text processing i used python whose yield statement extremely useful implementing complex iterators large often irregularly structured text files similar constructs exist languages eg c good reason yes i know previous threads but look like hackedup least badly explained solutions clearly work well often unclear limitations i would like write code something like import generator def yieldvaluesfilestring generate x sourcefromfilefilegetlines scala already using yield keyword givesomething field rsplitx field contains subfield rsplitfield givesubfield else scala continue imo considered bug scala preferred fieldstartswith continue actual need indent following code fieldstartswith val somecalculation stuff somecalculation ampamp fieldstartswithr giver givefieldslice else typically good deal code handle different cases givefield i like see code implements generate give btw give named yield scala taken keyword already i gather reasons i understand scala continuations may work inside statement if generate supply equivalent function works close possible statement iterator code yield almost inevitably sits inside loop please i would prefer get following answers yield sucks continuations better yes general continuations but hella hard understand time iterator want need if scala provides lots powerful tools hard use practice language succeed this duplicate please see comments you rewrite code using streams continuations recursion etc etc please see i also add technically need loops either for matter technically absolutely everything ever need using ski combinators your function long break smaller pieces need yield you production code anyway first need yield doubtful case second production code third text processing like often breaking function smaller pieces especially language forces lacks useful constructs makes code harder understand rewrite code function passed technically yes but result longer iterator chaining iterators much nicer chaining functions in general language force write unnatural style certainly scala creators believe general since provide shitloads syntactic sugar rewrite code way cool awesome way i thought sorry sarcasm previous list typical responses i seen similar scala questions stack overflow thanks help
3
data x data x mathlogy
i looking elegant way something like datai else logdatai xrangelendata so data i want make list fyi output csv file
1
data itertoolschainxlogx x data make list
i looking elegant way something like datai else logdatai xrangelendata so data i want make list fyi output csv file
1
if i understand correctly actually swapping instances class classes instance state kept two possible places slots dict if swap basically swapped instances retaining original name bindings one caveat class cannot immutable must define hash instances already members set keys dictionary would become irretrievable if i think i would swap method class method instead i think would read easier class somebigclass staticmethod def swapdictinstancea instanceb instanceadict instancebdict instancebdict instanceadict classmethod def swapslotcls instancea instanceb values attr clsslots valuesappend attr getattrinstancea attr getattrinstanceb attr attr val val values setattrinstancea attr val setattrinstanceb attr val later somebigclassswapdictthisinstance otherinstance somebigclassswapslotthisinstance otherinstance why if instances bound names consider frubbah somebigclassattrhi mom zikroid somebigclassattr hi dad somebigclassswapdictfrubbah zikroid after swap potentially everything thought knew zikroid changed
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
3
sumx mathlogx x data
i looking elegant way something like datai else logdatai xrangelendata so data i want make list fyi output csv file
1
the premise question seems want exactly python yield want reasonable suggestions thing different way scala if true important use python it quite nice language unless phd computer science using scala important part dissertation already familiar python really like features design choices use instead anyway actually want learn solve problem scala turns code delimited continuations overkill all need flatmapped iterators here you want write x xs complex yield instead write xsiteratorflatmap produce iterators you want write yielda yieldb instead write iteratorab you want write yielda complex set yields instead write iteratora produce complex iterator that all cases reduced one three in case example would look something like sourcefromfilefilegetlinesflatmapx iteratorsomething rsplitxiteratorflatmapfield field contains rsplitfielditerator else fieldstartswith vals whatever somecalculation ampamp fieldstartswithr iteratorrfieldslice else iteratorfield else iteratorempty ps scala continue done like implemented throwing stackless lightweight exceptions import scalautilcontrolbreaks blah breakable break get want scala yield want
i writing code phd research starting use scala i often text processing i used python whose yield statement extremely useful implementing complex iterators large often irregularly structured text files similar constructs exist languages eg c good reason yes i know previous threads but look like hackedup least badly explained solutions clearly work well often unclear limitations i would like write code something like import generator def yieldvaluesfilestring generate x sourcefromfilefilegetlines scala already using yield keyword givesomething field rsplitx field contains subfield rsplitfield givesubfield else scala continue imo considered bug scala preferred fieldstartswith continue actual need indent following code fieldstartswith val somecalculation stuff somecalculation ampamp fieldstartswithr giver givefieldslice else typically good deal code handle different cases givefield i like see code implements generate give btw give named yield scala taken keyword already i gather reasons i understand scala continuations may work inside statement if generate supply equivalent function works close possible statement iterator code yield almost inevitably sits inside loop please i would prefer get following answers yield sucks continuations better yes general continuations but hella hard understand time iterator want need if scala provides lots powerful tools hard use practice language succeed this duplicate please see comments you rewrite code using streams continuations recursion etc etc please see i also add technically need loops either for matter technically absolutely everything ever need using ski combinators your function long break smaller pieces need yield you production code anyway first need yield doubtful case second production code third text processing like often breaking function smaller pieces especially language forces lacks useful constructs makes code harder understand rewrite code function passed technically yes but result longer iterator chaining iterators much nicer chaining functions in general language force write unnatural style certainly scala creators believe general since provide shitloads syntactic sugar rewrite code way cool awesome way i thought sorry sarcasm previous list typical responses i seen similar scala questions stack overflow thanks help
3
matplotlib python closer may think httpsgithubcommatplotlibmatplotlibpy httpwwwlfduciedugohlkepythonlibsmatplotlib why use pythonstartup instead sitecustomizepy localhost cat startuppy future import printfunction future import division localhost export pythonstartup localhost python python va jun gcc apple inc build dot darwin type help copyright credits license information printfredend file stdin line printfredend syntaxerror invalid syntax d localhost export pythonstartupstartuppy localhost python python va jun gcc apple inc build dot darwin type help copyright credits license information printfredend fred
in python using future import division printfunction i print showing however possible automatically imported python startup i tried use sitecustomizepy special module inport valid inside module shell as i sure people ask i need teaching python teenagers i noticed integer division easy decided switch python however one requirement course able plot function matplotlib pretty good valid python so idea use custom installationnot perfect i better idea matplotlib new natural division any advice maybe matplotlib alternative working python
3
the smtplib prints directly stderr eg line smtplibpy printstderr connect fail host you either monkey patch sysstderr import smtplib smtplibstderr run mail code i might also suggest patching smtplibstderr custom object write method wrap logging code using logging library instance import logging import smtp class stderrloggerobject def initself selflogger logginggetlogger mail def writeself message selfloggerdebugmessage orgstderr smtpstderr smtpstderr stderrlogger smtp stuff smtpstderr orgstderr this question contains useful examples patching stderr context managers
as know python smtplib debug levelwhen i set true param print send information the problem i try get debug info log file they stay cmd console how i log info like connect connect reply esmtp winwebmail ready httpwwwwinwebmailcomrn reply retcode msg esmtp winwebmail ready httpwwwwinw ebmailcom connect esmtp winwebmail ready httpwwwwinwebmailcom send ehlo rn reply sizern reply auth loginrn reply retcode msg size auth login bla bla bla bla
3
no need compile new version python x you start as found sitecustomizepy work this future import identifier import it flags module compiled special rules any module uses features must future import well interactive console the following shell command start interactive console division printfunction active python ic future import division printfunction you could alias python linux set launcher hide extra stuff if using idle pythonstartup script dsm suggests work well note global throughout interpreter affects interactive console modules filesystem must import future explicitly use feature if issue i suggest making template base work needed imports true division future import division modules import matplotlib code def main pass name main main
in python using future import division printfunction i print showing however possible automatically imported python startup i tried use sitecustomizepy special module inport valid inside module shell as i sure people ask i need teaching python teenagers i noticed integer division easy decided switch python however one requirement course able plot function matplotlib pretty good valid python so idea use custom installationnot perfect i better idea matplotlib new natural division any advice maybe matplotlib alternative working python
1
you explicitly say appears using matplotlib i say certain posted i guess happening already bound save figure matplotlib figure and default matplotlib uses tkbased backend thus tk error there need use urwid module matplotlib hooks things like going need disconnect hooks need as simple standalone example reproduce problem import matplotlibpyplot plt import numpy np def saveevent eventkey print saved figure eventcanvasfiguresavefig temppng fig ax pltsubplots aximshownprandomrandom figcanvasmplconnect keypressevent save pltshow notice figure saved also get popup file selection dialogue save figure you avoid either using different key something list b temporarily disabling matplotlib key binding save it pretty easy temporarily disable appropriate matplotlibrc setting import matplotlibpyplot plt import matplotlib mpl import numpy np disable interactive keybinding mplrcparams keymapsave def saveevent eventkey print saved figure eventcanvasfiguresavefig temppng fig ax pltsubplots aximshownprandomrandom figcanvasmplconnect keypressevent save pltshow
i try understand python codes i want select part open image zoom save selected part right trying quickly save open zoom image pressing key for explain better need fire function savefig pressing keyboard key i tried use urwid module import urwid import pil import image imimageopenfigtif imshowim def saveinput input savefigfigpng and i used uinput well try thing import uinput import pil import image def main capabilities uinputevkey uinputkeys device uinputdevicenamepythonuinputkeyboard capabilitiescapabilities deviceemituinputevkey uinputkeys savefigsatpng imimageopenfigtif imshowim and result codes error message appeared exception tkinter callback traceback recent call last file usrlibpythonlibtktkinterpy line call return selffuncargs file usrlibpymodulespythonmatplotlibbackendsbackendtkaggpy line keypress figurecanvasbasekeypresseventself key guieventevent file usrlibpymodulespythonmatplotlibbackendbasespy line keypressevent selfcallbacksprocesss event file usrlibpymodulespythonmatplotlibcbookpy line process funcargs kwargs file usrlibpymodulespythonmatplotlibbackendbasespy line keypress selfcanvastoolbarsavefigureselfcanvastoolbar typeerror savefigure takes exactly argument given it strang never open tkinter please helpâ´me how save zoom image key event i sorry ignorance python new
1
check pyftpdlib giampaolo rodola it one best ftp servers python it used google chromium browser bazaar version control system it complete implementation python rfc aka ftp server implementation spec from commandline python pyftpdlib alternatively myserverpy usrbinenv python pyftpdlib import servers pyftpdlibhandlers import ftphandler address listen every ip machine port server serversftpserveraddress ftphandler serverserveforever there examples website want something complicated to get list command line options python pyftpdlib help note want override use standard ftp port need admin privileges eg sudo
is possible one line command python simple ftp server i like able quick temporary way transfer files linux box without install ftp server preferably way using built python libraries nothing extra install
3
it worked fine fixing two things variable meta metadata nd arg table referred global variable lines createuserstable metadatacreateallengine moved bottom functions called defining as syntax error i guess file got invalid characters last line printed screen my suggestion delete last line retype
i getting maddening syntax error i run following program here error file createthedatabasepy line syntaxerror invalid syntax here code long repetitive easy skim import sqlalchemy sqlalchemy import engine createengine sqliteusersbenscholzdropboxomnicloudomniclouddevdb meta metadata createuserstable createaccountstable createpasswordstable metabind engine metacreateallengine def createuserstable printcreating user table users table users metadata column id integer primarykey true column username string nullable false column emailaddress string nullable false column firstname string column fullname string column joindate datetime def createaccountstable printcreating accounts table accounts table accounts metadata column userid foreignkey usersid column facebookusername string column emailusername string column emailusername string column emailusername string column emailusername string column emailusername string column twitterusername string column twitterusername string column twitterusername string column kloutusername string column dropboxusername string column boxusername string column flickrusername string column flickrusername string column instagramusername string column disqususername string column stackoverflowusername string def createpasswordstable printcreating passwords table passwords table passwords metadata column userid foreignkey usersid column facebookpass string column emailpass string column emailpass string column emailpass string column emailpass string column emailpass string column twitterpass string column twitterpass string column twitterpass string column kloutpass string column dropboxpass string column boxpass string column flickrpass string column flickrpass string column instagrampass string column disquspass string column stackoverflowpass string the program lines long seems get end expect something
1
the string formatting operator also neat things string this foos also foos print string foo bar this bar also bar this really useful repeating one argument sure beats formatstring bar bar you also padding number formatting
for example mymessage dear hello name jj print mymessage name does python feature accomplishing something like code
1
inheriting nothing creates oldstyle class different behaviour newstyle classes i remember specifics see explanation general rule reason favour oldstyle classes always inherit object nothing else
in one past questions answerer suggests better inherit object class want create like scratch need inherit class for example like i always class myclass class inherits nothing def initself pass for suggested class suggestedclassobject class inherits object type def initself pass i confused benefits disadvantage approaches question so idea inherit object type nothing
2
to deal path file names best use builtin module ospath python please look function dirname basename split module
i files i want foo bar left split dn cxdata files f cxdatafootxt f cxdatsbartxt i tried fsplit i thought since dn txt predefined i could subtract nope split work
1
using proper path handling methods os f cxdatafootxt import os ospathbasenamef footxt ospathdirnamef cxdata ospathsplitext f cxdatafoo txt ospathsplitext ospathbasenamef foo txt
i files i want foo bar left split dn cxdata files f cxdatafootxt f cxdatsbartxt i tried fsplit i thought since dn txt predefined i could subtract nope split work
3
being big fan jquery i recommend pyquery offers strong selector like jquery pyquery import pyquery pq dom pqfile yourhtml read print lendom hsectiontitle table h element class name you use id name target class id next adjacent element in case next table element here i added table returns a elements inside table
i would like count urls specific class class h classsectiontitleinsiders at loews corp lh links like hrefresearchstockspeoplerelationshipasppersonidampsymbollus i would like count number kind links class this program i wrote count work headings bsfind h text insiders at loews corp l section headingsfindnext aa sectionfindall href true bbaacount href print bb work would mind giving tip solve issue thank much h classsectiontitleinsiders at loews corp lh table cellpadding cellspacing classtable width stylemarginbottompxtheadtrtdname connectionstdtd colspan stylewidthpxboard relationshipstdtdtitletdtdtype board membertdtd alignrightagetdtrtheadtrtda hrefresearchstockspeoplepersonasppersonidampsymbollus classlinkxsbandrew tisch atdtd stylewidthpx paddingleft pxa hrefresearchstockspeoplerelationshipasppersonidampsymbollusimg srcimagesiconspeoplegif styleverticalalignmiddle atdtd stronga hrefbusinessweekresearchstockspeoplerelationshipasppersonidampsymbollusstrong relationshipsatdtd stylewidthpxcochairman member office president chairman executive committee member finance committee chairman bulovatdtd tdtd alignright stylewidthpxtdtrtrtda hrefresearchstockspeoplepersonasppersonidampsymbollus classlinkxsbjonathan tisch atdtd stylewidthpx paddingleft pxa hrefresearchstockspeoplerelationshipasppersonidampsymbollusimg srcimagesiconspeoplegif styleverticalalignmiddle atdtd stronga hrefbusinessweekresearchstockspeoplerelationshipasppersonidampsymbollusstrong relationshipsatdtd stylewidthpxcochairman member office president member executive committee chairman loews hotels chief executive officer loews hotelstdtd tdtd alignright stylewidthpxtdtrtrtda hrefresearchstockspeoplepersonasppersonidampsymbollus classlinkxsbjames tisch atdtd stylewidthpx paddingleft pxa hrefresearchstockspeoplerelationshipasppersonidampsymbollusimg srcimagesiconspeoplegif styleverticalalignmiddle atdtd stronga hrefbusinessweekresearchstockspeoplerelationshipasppersonidampsymbollusstrong relationshipsatdtd stylewidthpxchief executive officer president member office president director member executive committee member finance committee chairman diamond offshore director cnatdtd tdtd alignright stylewidthpxtdtrtable
1
let try answer questions in dev mode hit ctrl alt t get shell however trimsecure shell let wish you load type os usb install i friends ubuntu everyone moved back chromeos may case different cloud cloud ide give ability develop python you read blog post i wrote past developers chromebook httpgreenidowordpresscomwebdevelopersandthenewchromebook good luck
i would like use samsung chromebook develop app engine using python unfortunately possible i browser there online ide like codule good enough yet so regards i questions is way hack chrome os pull native linux is way install second os chromebook i new samsung chromebook first one is chrome os extension help programming python app engine
3
some time ago i forked smtplib added logfile option among things you try want it also new name smtppy
as know python smtplib debug levelwhen i set true param print send information the problem i try get debug info log file they stay cmd console how i log info like connect connect reply esmtp winwebmail ready httpwwwwinwebmailcomrn reply retcode msg esmtp winwebmail ready httpwwwwinw ebmailcom connect esmtp winwebmail ready httpwwwwinwebmailcom send ehlo rn reply sizern reply auth loginrn reply retcode msg size auth login bla bla bla bla
1
it likely optimisation side browser trying reuse connection see httpenwikipediaorgwikihttppersistentconnection if want make sure sniff traffic using wireshark although localhost based address may require fancy setup
i binding socket localhost order make simple server here simple python script i used create server import os import socket import fcntl tuples socketgetaddrinfo localhost socketafunspec socketsockstream socketaipassive socketaiaddrconfig res tuples af socktype proto canonname sockaddr res sock socketsocketaf socktype proto flags fcntlfcntlsockfileno fcntlfgetfd flags fcntlfdcloexec fcntlfcntlsockfileno fcntlfsetfd flags socksetblocking sockbindsockaddr socklisten now i open script using interactive shell then i go browser visit httplocalhost queue connection server i repeat last step times time inside new tab at point i expect many connections queued server to check i go interactive shell i type sockaccept this works first try subsequent tries i get erno eagain tells connections queued however browser little connecting spinner still going tab i opened i tried chrome firefox i wrote client connects localhost able queue connections problems what going can anyone please check experiment verified browsers for convenience client import os import socket import fcntl socketsocketsocketafinet socketsockstream sconnect localhost srecv
1
you iterate columns table first table sqlalchemyormattributes import managerofclass dummytable managerofclassdummymappermappedtable finally query col dummytablecolumns dummy sessionquerydummyfiltercol first or maybe actually generating specific set columns elaborate function showing in case use getattr no really range n cname cd dummy dbsessionquerydummyfiltergetattrdummy cname first
i table many columns class dummyobject tablename dummies c columninteger c columninteger c columninteger cn columninteger can i query columns individually without specifying column name manually range n cname cd dummy dbsessionquerydummyfilterbyfirst thanks
2
selfassertcontainsresponse invalid message
i like simulate requests views django i writing tests this mainly test forms here snippet simple test request djangotests import testcase class myteststestcase def testformsself response selfclientpostmyform something something selfassertequalresponsestatuscode get page back error the page always returns response whether form error how i check form failed particular field soemthing error
2
to wrap comment tomasz zielinski real answer for several reasons indeed better let apachenginxetc work sending files most servers mechanisms help usecase apache lighttpd xsendfile nginx xaccelredirect the idea use features django like nice urls authentification methods etc let server work serving files what django view return response special header the server replace response actual file example apache def songdownloadrequest path pathtofilemp response httpresponse response xsendfile smartstrpath response contenttype audiompeg response contentlength osstatpathstsize return response install modexsendfile add xsendfileon depending version xsendfileallowabove xsendfilepath thepathtoservefrom apache configuration this way reveale file location keep url management django
so i want serve couple mps folder homeusernamemusic i think would big deal i bit confused using generic views url urlspy urlr songpsongidddownload songdownload name songdownload the example i following found generic view section django documentations httpdocsdjangoprojectcomendevtopicsgenericviews it way bottom i sure tailor needs here viewspy def songdownloadrequest songid song songobjectsgetidsongid response objectdetail request objectid songid mimetype audiompeg response contentdisposition attachment filenames smp songartist songtitle return response i actually loss convey i want spit mp instead output mp current pages html contained should template mp do i need setup apache serve files django able retrieve mp filesystemproper permissions course serve if need configure apache i tell django thanks advance these files hd i need generate anything spot i like prevent revealing location files possible a simple songdownload would fantastic
3
i think want test form test form view form rendered example get idea djangotest import testcase myappforms import myform class myteststestcase def testformsself formdata something something form myformdataformdata selfasserttrueformisvalid tests relating forms example checking form data
i like simulate requests views django i writing tests this mainly test forms here snippet simple test request djangotests import testcase class myteststestcase def testformsself response selfclientpostmyform something something selfassertequalresponsestatuscode get page back error the page always returns response whether form error how i check form failed particular field soemthing error
3
there way get usage statistics api this issue actively discussed aws forum years feedback aws team httpsforumsawsamazoncomthreadjspamessageid the alternatives would turn amazon s server log analyze another option would take advantage amazon devpay service thanks andy edit here official amazon s documentation related amazon s access logs httpdocsamazonwebservicescomamazonslatestdevindexhtmlserverlogshtml
is way programmatically access amazon s account usage data i building application charge endusers use amazon s bucket because i middleman aws end user putdelete operations i able keep track uploads storage usage i allowing users directly access files public access links i able directly monitor downstream usage as plan check download usage regularly is anywhere aws api i access usage statistics
2
i would configure relation onetoone uselistfalse add property would wrap link relationship the sa configuration would look like code work fine creating updating deleting link you might need configure relation deleteorphan option cascade class submissionsbase tablename submissions id columninteger primarykeytrue created columndatetime defaultdatetimenow title columntext linkid columninteger foreignkey linksid linkrel relationlinks backrefbackrefsubmission uselistfalse def initself title linknone selftitle title selflink link property def linkself return selflinkrel selflinkrellink linksetter def linkself value value none selflinkrel none elif selflinkrel none selflinkrel linksvalue else selflinkrellink value
i learning use sqlalchemy i trying following storing title link two separate tables temp submissionstitleu facebook homepage linku httpfacebookcom sessionaddtemp sessionflush transactioncommit via class linksbase tablename links id columninteger primarykeytrue link columntext created columntimestamp defaultdatetimenow def initself link selflink link class submissionsbase tablename submissions id columninteger primarykeytrue created columntimestamp defaultdatetimenow title columntext linkid columninteger foreignkey linksid link relationlinks def initself title link selftitle title selflink link however i always get error attributeerror unicode object attribute sainstancestate what going is better way code
1
you use defaultdict list collections import defaultdict b c dd defaultdictlist k v miteritems ddvappendk dictdd b c if care dict defaultdict omit last step und use defaultdict directly
for example i call function passing dictionary parameter invmap b c b c invmap b c c b invmap b c b c if map b i invert map get invmap b using dictvk k v mapiteritems anyone knows case
3
you probably use defaultdict setdefault def invertdictionaryorigdict result change defaultdictlist k v origdictiteritems resultsetdefaultv appendk
for example i call function passing dictionary parameter invmap b c b c invmap b c c b invmap b c b c if map b i invert map get invmap b using dictvk k v mapiteritems anyone knows case
3
to create custom responses need use bottlebaseresponse object the documentation describes class seems quite easy use so achieve want create baseresponse object status code wish data need include return view
well i working bottle right and i wondering excatly i able build custom response i little script operates data i send i want send responsecode done modification i looking docs bottle find anything thanks advance
1
the argument cursorexecute represents values need inserted database tuple sequence however consider example see happening jason jason jason jason the first example evaluates string instead correct way representing single valued tuple second evaluation anyhow code fix error selfcursorexecuteselect weight from equipment where name item also giving cursorexecute value arguments stringswhich results first evaluation example results error getting
using sqlite python i trying iterate list pull weight item database based item name i tried using parameter substitution suggested prevent sql injections work for example i use item selfinventorynames selfcursorexecuteselect weight from equipment where name item selfcursorclose i get error sqliteprogrammingerror incorrect number bindings supplied the current statement uses supplied i believe somehow caused initial creation database module i made actually creates db bindings cursorexecutecreate table equipment id integer primary key name text price integer weight real info text ammocap integer availabilitywest text availabilityeast text however i use lesssecure substitution item name works fine like item selfinventorynames selfcursorexecuteselect weight from equipment where name item selfcursorclose i figure thinks i bindins i calling one how i fix
3
why temporarily stop patch selfurlopenstop points real urlopen urlliburlopen put patch place selfurlopenstart
is way temporary undo patching using mock within sideeffect in particular i like make something like work mock import patch import urllib import unittest class simpletestunittesttestcase def setupself selfurlpatcher patch urlliburlopen selfurlopen selfurlpatcherstart def sideeffecturl interesting stuff first temporary unpatch urlliburlopen call real one r urlliburlopenurl ought real deal patch return r selfurlopensideeffect sideeffect def testfeatureself almost real urlliburlopen usage goes p urlliburlopenwwwgooglecomread name main unittestmain
1
have look django facebook there examples included link httpsgithubcomtschellenbachdjangofacebook also try list sharing flow fashiolista real life demo httpwwwfashiolistacomstylemodedamourlistultimatesummerwishlist click save photo album
i trying publish photo available server users photo album is job pythondjango done javascript and anyone example code i going round circles week i got users accesstoken permissions publish update basically something like djangopython so i call page upload photo server post users wall upload photo to album facebooks graph api thanks
1
the command works executed terminal except command the code running mv pdf testpdf type runs mv pdf testpdf the difference shell globs wildcard executing mv you simulate using glob module
i trying rename set pdf files desktop using simple python script i somehow successful my current code import ossubprocess path usersarmeddesktop file oslistdirpath command mv pdf testpdf mv command rename files testpdf subprocesscallcommand the output get code files renamed the command works executed terminal i using mac helps way
3
python going expand shell wildcard string default you also without subprocess but code lose pdf files except last one glob import glob import os path usersarmeddesktop oschdirpath filename globpdf osrenamefilename testpdf but i sure really want you need better destination name
i trying rename set pdf files desktop using simple python script i somehow successful my current code import ossubprocess path usersarmeddesktop file oslistdirpath command mv pdf testpdf mv command rename files testpdf subprocesscallcommand the output get code files renamed the command works executed terminal i using mac helps way
1
you looking zipfile stringio create stringio open zipfile add files send
please help problem i sorry sounds noobie coz i really there files jpg docs certain database would i select file database save zip file send browser httpresponse something like response httpresponsemimetype applicationzip response contentdisposition filenamegroupzip the part greatly bothers taking files database coz google seem helpful some relevant codes i temp requestpostgetlist cbox cbox field form tempx modelsfiletableobjectsfilterpkin temp i longer know thanks advance p
1
all multiprocessingpoolmap methods consume iterators fully demo code soon function called to feed map function chunks iterator one chunk time use groupernofill def groupernofilln iterable listgroupernofill abcdefg a b c d e f g ititeriterable def take yield listitertoolsisliceitn return itertakenext chunksize asyncresults finput groupernofillchunksizeitertoolsizipmatrices inds asyncresultsextendpoolmapasyncmyfunc finputget asyncresultsnparrayasyncresults ps poolmapasync chunksize parameter something different it breaks iterable chunks gives chunk worker process calls mapfuncchunk this give worker process data chew funcitem finishes quickly help situation since iterator still gets consumed fully immediately mapasync call issued
i xx numpy array element matrix i need calculations matrices i want use multiprocessing module speed things the results calculations must stored xx array like original one result matrix element ijk original array must put ijk element new array to i want make list could written pseudoish way arrayijk j k pass function multiprocessed assuming matrices list matrices extracted original array myfunc function calculations code would look somewhat like import multiprocessing import numpy np itertools import izip def myfuncfinput do calculations return result index return result finput make indices inds nprollaxisnpindices reshape make function input matrices indices finput izipmatrices inds pool multiprocessingpool asyncresults npasarraypoolmapasyncmyfunc finputget however seems like mapasync actually creating huge finput list first my cpu much memory swap get completely consumed matter seconds obviously i want is way pass huge list multiprocessing function without need explicitly create first or know another way solving problem thanks bunch
3
httpdocspythonorgextendingextendinghtml httpdocspythonorgextending httpenwikibooksorgwikipythonprogrammingextendingwithc httpwikicacrcaltechedudanseindexphpwritingcextensionsforpython
we developing software python two team know cc my question make plugins possible include dll python
1
unless already existing cc libraries want integrate python waste time toss copy tutorial desks tell take days learn
we developing software python two team know cc my question make plugins possible include dll python
3
when working flickrapi python frequently useful print xml returned api calls order see going in example add xmletree import elementtree top add print elementtreetostringfavs see structure returned rsp statok photosets page pages perpage total photoset photoset photoset photoset photosets rsp in real application want check return status check page attributes quickly get want let look photoset elements to iterate change loop elm favsgetchildren print elementtreetostringelm then see structure photoset element navigate for example one would photoset cancomment countcomments countviews datecreate dateupdate farm id needsinterstitial photos primary secretfde server videos visibilitycanseeset titlebirdstitle description photoset title actually stored title subelement from see get information want elm favsgetchildren title elmgetchildrentext print id secret setname elmget id elmget secret title produces output id secret ef setname french creek state park id secret dceddf setname las vegas id secret fde setname birds etc
i wish list sets created user along set id i using flickrapi python here code the setname returning none output the elmget title returning none import flickrapi apikey apikey apisecret apisecret flickr flickrapiflickrapiapikey apisecret token frob flickrgettokenpartoneperms write token rawinputpress enter authorized program flickrgettokenparttwotoken frob try favs flickrphotosetsgetlistuserid n favs flickrfavoritesgetpubliclistuserid n elm favsgetiterator print id secret setname elmget id elmget secret elmget title except raise exceptionsome error encountered
1
edit it seems certain equations definitely possible automate process see original answer left intact based many painful hours fighting latex equation settings failures notice missing elements huge equation blocks almost certainly possible convert latex python vice versa probably painful hand likely need spend time tidying results anyway that said similar questions asked answered how convert math formula python code converting python numeric expression latex maybe get started edit i took look previous questions tested combination comments all credit authors comments import sympy def pythontolatexexpression simplifyfalse symexpr sympysympifyexpression simplify symexpr sympysimplifysymexpr return sympylatexsymexpr name main print pythontolatexrawinputenter python math expression simplifytrue
i writing code long mathematical equations many trigonometric identities is way visualising expression latex making c python expression way around how enter check mathematical expressions see brackets etc right position use latex documents thanks advance
2
it called bit vector bitmap try eg bitvector if want implement need use numeric object list use bitwise operations toggle bits eg bitmap bit bitmap bit enable bit bitmap amp bit disable bit
i big list represented integers default python i think randint range and i want optimize code utilizes much less memory the obvious way use bit represent numbers is possible build list real binary numbers python regards bruno edit thank from answers i found python default i found library installed macports osx saves trouble bit operations pythonbitstring
1
paths specified relative directory containing appyaml try handlers url dailybasic script dailybasicdailybasicpy did want map file indexhtml root url app engine automatically like web servers to mapping try something like url staticfiles indexhtml upload indexhtml
i making project using gae terrible problem i wanted make twitter bot i started first step posting tweets i made tweetstxt folder dailybasicpy here parts codes appyaml application mathgirlna version runtime python apiversion handlers url static staticdir static url dailybasic script dailybasicdailybasicpy url script mainpy mainpy works error usrbinpython coding utf import os import sys googleappengineapi import users googleappengineext import webapp googleappengineext import db googleappengineextwebapp import template googleappengineextwebapputil import runwsgiapp import wsgirefhandlers class mainpagewebapprequesthandler def getself path ospathjoinospathdirnamefile indexhtml selfresponseoutwritetemplaterenderpath none application webappwsgiapplication mainpage debugtrue def main runwsgiappapplication name main main dailybasicpy run every minutes usrbinpython coding utf import os import sys googleappengineext import webapp googleappengineext import db googleappengineextwebapputil import runwsgiapp import tweepy import wsgirefhandlers import time def tweetittweet lentweet apiupdatestatustweet else diaryentriesappendtweet consumerkey consumersecret accesstoken accesstokensecret auth tweepyoauthhandlerconsumerkey consumersecret authsetaccesstokenaccesstoken accesstokensecret api tweepyapiauth class dailybasicwebapprequesthandler def getself timelocaltime path ospathjoinospathdirnamefile tweetstxt fdb openpath r db fdbreadline db todaynow wday nowtmwday dbwday nowtmhour nowtmmin intdb intdb nowtmhour nowtmmin intdb intdb todaynowappenddb iflentodaynow import random tweetittodaynowrandomrandrangelentodaynow application webappwsgiapplication dailybasic dailybasic debugtrue def main runwsgiappapplication name main main cronyaml cron description day process url dailybasic schedule every minutes timezone asiaseoul i googled problem tried everything i put part appyaml workedit able deployed gae warned file referenced handler found dailybasicpy here file tree root dailybasic dailybasicpy tweetstxt mainpy appyaml cronyaml indexyaml indexhtml i want keep indexhtml contains html codes without scripts how i place files write appyaml and sorry poor english added the problem open works tweetstxt uploaded wrong directory
1
this uses bitstring module constructs bitarray object list bitstring import bitarray b bitarrayrandint range internally stored packed bytes take considerably less memory you slice index check set bits etc usual notation additional methods set modify bits to get data back binary string use bbin get byte packed data use btobytes pad zero bits byte boundary
i big list represented integers default python i think randint range and i want optimize code utilizes much less memory the obvious way use bit represent numbers is possible build list real binary numbers python regards bruno edit thank from answers i found python default i found library installed macports osx saves trouble bit operations pythonbitstring
2
as delnan already said comment able use real binary numbers mean bitforbit equivalent memory usage integers longs course real binary numbers meaning address individual bits using bitwise operators easily hidden class also long objects become arbitrarily large ie use simulate arbitrarily large bitsets it going fast python difficult either good start using binary generation scheme following reduce lambda p b b p p randomrandint range of course random supports arbitrarily large upper boundaries r randomrandint this entirely since individual binary digits independent way independent create digit then knowing prngs work really independent case either if concern probably use random module hardware rng
i big list represented integers default python i think randint range and i want optimize code utilizes much less memory the obvious way use bit represent numbers is possible build list real binary numbers python regards bruno edit thank from answers i found python default i found library installed macports osx saves trouble bit operations pythonbitstring
1
you use rollyourown solution function overloading this one copied guido van rossum article multimethods little difference mm overloading python registry class multimethodobject def initself name selfname name selftypemap def callself args types tupleargclass arg args generator expression function selftypemapgettypes function none raise typeerrorno match return functionargs def registerself types function types selftypemap raise typeerrorduplicate registration selftypemaptypes function def multimethodtypes def registerfunction name functionname mm registrygetname mm none mm registryname multimethodname mmregistertypes function return mm return register the usage would multimethods import multimethod import unittest overload makes sense case overload multimethod class spriteobject pass class pointobject pass class curveobject pass overloadsprite point direction int def addbulletsprite start direction speed overloadsprite point point int int def addbulletsprite start headto speed acceleration overloadsprite str def addbulletsprite script overloadsprite curve speed def addbulletsprite curve speed most restrictive limitations moment methods supported functions class members inheritance handled kwargs supported registering new functions done import time thing threadsafe
i know python support method overloading i run problem i seem solve nice pythonic way i making game character needs shoot variety bullets i write different functions creating bullets for example suppose i function creates bullet travelling point a b given speed i would write function like def addbulletsprite start headto speed code but i want write functions creating bullets like def addbulletsprite start direction speed def addbulletsprite start headto spead acceleration def addbulletsprite script for bullets controlled script def addbulletsprite curve speed bullets curved paths and and many variations is better way without using many keyword arguments cause getting kinda ugly fast renaming function pretty bad get either addbullet addbullet addbulletwithreallylongname to address answers no i create bullet class hierarchy thats slow the actual code managing bullets c functions wrappers around c api i know keyword arguments checking sorts combinations parameters getting annoying default arguments help allot like acceleration
3
static files served directly user url specified appyaml they cannot read application deployed servers serve static files infrastructure runs application if need read files script upload nonstatic if need serve files statically directly user browser read scripts need include copies files application although symlink nonstatic directory count second copy get deployed
i making project using gae terrible problem i wanted make twitter bot i started first step posting tweets i made tweetstxt folder dailybasicpy here parts codes appyaml application mathgirlna version runtime python apiversion handlers url static staticdir static url dailybasic script dailybasicdailybasicpy url script mainpy mainpy works error usrbinpython coding utf import os import sys googleappengineapi import users googleappengineext import webapp googleappengineext import db googleappengineextwebapp import template googleappengineextwebapputil import runwsgiapp import wsgirefhandlers class mainpagewebapprequesthandler def getself path ospathjoinospathdirnamefile indexhtml selfresponseoutwritetemplaterenderpath none application webappwsgiapplication mainpage debugtrue def main runwsgiappapplication name main main dailybasicpy run every minutes usrbinpython coding utf import os import sys googleappengineext import webapp googleappengineext import db googleappengineextwebapputil import runwsgiapp import tweepy import wsgirefhandlers import time def tweetittweet lentweet apiupdatestatustweet else diaryentriesappendtweet consumerkey consumersecret accesstoken accesstokensecret auth tweepyoauthhandlerconsumerkey consumersecret authsetaccesstokenaccesstoken accesstokensecret api tweepyapiauth class dailybasicwebapprequesthandler def getself timelocaltime path ospathjoinospathdirnamefile tweetstxt fdb openpath r db fdbreadline db todaynow wday nowtmwday dbwday nowtmhour nowtmmin intdb intdb nowtmhour nowtmmin intdb intdb todaynowappenddb iflentodaynow import random tweetittodaynowrandomrandrangelentodaynow application webappwsgiapplication dailybasic dailybasic debugtrue def main runwsgiappapplication name main main cronyaml cron description day process url dailybasic schedule every minutes timezone asiaseoul i googled problem tried everything i put part appyaml workedit able deployed gae warned file referenced handler found dailybasicpy here file tree root dailybasic dailybasicpy tweetstxt mainpy appyaml cronyaml indexyaml indexhtml i want keep indexhtml contains html codes without scripts how i place files write appyaml and sorry poor english added the problem open works tweetstxt uploaded wrong directory
3
i would use pth file see httpdocspythonorginstallindexhtmlinstsearchpath a pth file file consisting one directory path per line it insert listed directories python path that may better executing shell scripts downsides complex installation break portability etc
ok i following situation i need edit pythonpath dynamically target pc now structure project trunk bin startscript dependencies dependencies from python i could startscript rootpath ospathsplitospathdirnameospathabspathfile dependenciesroot ospathjoinrootpath dependencies sys import path pathextendrootpath dependenciesroot this would trick i need start new python processes processpopen changes syspath gone seems now i thinking sh script would job better unfortunately i total noob idea proceed the sh script basically things python get absolute path directory script located get parent folder say parentpath export pythonpathpythonpathparentpath python startscriptpy so basically first two steps ones i need help also way make changes python syspath persist subprocess opened subprocesspopen please let know
1
have looked sympy it module generating latex python code actually quite bit sympy probably guess name python library symbolic computation the sympy library also includes builtin interpreter cd sympy directory sitepackages type ipython shell prompt with sympy interpeter things like in cosxseriesx out x ⋠x ⋠x ⋠x ── ──── ───── ────── ox in xyexpand out x ⋠x⋠in cosxseriesx out x ⋠x ⋠x ⋠x ── ──── ───── ────── ox quite latexbut sympy easily generate latex python code sympy import integral latex sympyabc import x latexx x latexx mode inline x latexx mode equation beginequationxendequation i also wanted generally recommend sympy libraryunder active development four years improved substantially year excellent mature library symbolic computation excellent docs active helpful community aside submitting couple patches i sympy devcommitter user
i writing code long mathematical equations many trigonometric identities is way visualising expression latex making c python expression way around how enter check mathematical expressions see brackets etc right position use latex documents thanks advance
3
as far i know done the problem ironpython class clr class compatible clr class a clr class static ironpython class dynamic dlr far i know example provide ironpython classes net clr attributes need cmdlet development
i want able write powershell cmdlets using ironpython furthermore i need one cmdlet look environment add cmdlets powershell based contents for example reading directory adding cmdlet remove every filename sees
1
i back jã¶rg w mittag answer the python implementation diioc lightweight completely vanishes to back statement take look famous martin fowler example ported java python pythondesignpatternsinversionofcontrol as see link container python written lines code class container def initself systemdata componentname componentclass componentargs systemdata typecomponentclass typesclasstype args selfdictarg arg componentargs selfdictcomponentname componentclassargs else selfdictcomponentname componentclass
in java ioc di common practice extensively used web applications nearly available frameworks java ee on hand also lots big python web applications beside zope i heard really horrible code ioc seem common python world please name examples think i wrong there course several clones popular java ioc frameworks available python springpython example but none seems get used practically at least i never stumpled upon django sqlalchemy insert favorite wsgi toolkit based web application uses something like in opinion ioc reasonable advantages would make easy replace djangodefaultusermodel example extensive usage interface classes ioc python looks bit odd â»pythonicâ« but maybe someone better explanation ioc widely used python
3
you could update pythonpath environment variable moment update syspath startscript using osenviron dict
ok i following situation i need edit pythonpath dynamically target pc now structure project trunk bin startscript dependencies dependencies from python i could startscript rootpath ospathsplitospathdirnameospathabspathfile dependenciesroot ospathjoinrootpath dependencies sys import path pathextendrootpath dependenciesroot this would trick i need start new python processes processpopen changes syspath gone seems now i thinking sh script would job better unfortunately i total noob idea proceed the sh script basically things python get absolute path directory script located get parent folder say parentpath export pythonpathpythonpathparentpath python startscriptpy so basically first two steps ones i need help also way make changes python syspath persist subprocess opened subprocesspopen please let know
2
splitnum anything numsplit would valid solve problem splits spaces what want convert digit characters num numbers represent list comprehension digits intc c num then sum result expression
i trying make program whatever number entered user digits composing number added sum good done something wrong this simple i suppose though i struggling add together numbers i split do know i this attempt numrawinputinput number numsplit suma print num valid number else print num invalid thank
2
you using rawinput prompt user function returns string composed digits case need make computations convert int here code could look like num rawinput input number suminti num print ok else print failed keep mind python x functions rawinput returns string input returns integers fails something else given python x rawinput function replaced input
i trying make program whatever number entered user digits composing number added sum good done something wrong this simple i suppose though i struggling add together numbers i split do know i this attempt numrawinputinput number numsplit suma print num valid number else print num invalid thank
1
use map function in in mapinta out in summapinta out mapfunction sequence calls functionitem sequence’s items returns list return values see docspythonorg this works rawinput returns string
i trying make program whatever number entered user digits composing number added sum good done something wrong this simple i suppose though i struggling add together numbers i split do know i this attempt numrawinputinput number numsplit suma print num valid number else print num invalid thank
3
your first problem split split string characters splits string whitespace split to go character input string use split use character string i find hard read code variable names like lol rofl i changed your check intdigit excludes i assume accident i using intdigit including instead your current code prints error message time sees invalid character instead i break loop i print first time print success message loop completes without broken if intdigit fails convert digit int raise exception instead i compare character see instead converting code rawinputwhat code digit code digit print the verification code valid please check credit card code break else print thank we process order a compact alternative using loop use generator expression function code rawinputwhat code digit digit code print thank we process order else print the verification code valid please check credit card code
brief i trying write simple program checks given code valid the code valid three characters entered digits if code valid progam displays message thank we process order the output program error message the verification code valid please check credit card code input valid attempt lol rawinputwhat code rofllolsplit int rofl introfl print thank we process order else print the verification code valid please check credit card code purpose to learn i found another way involving checking whole thing worked perfectly but i trying learn request that give explicit direction fix code provide additional relevant advice close thank advance
1
could rawinput aisdigit inta lena print yeah else print nope isdigit cool builtin function checks strings see made entirely digits you wrap inta tryexcept acts shortcircuit operator prevent inta evaluated isdigit returns false edit added lena
brief i trying write simple program checks given code valid the code valid three characters entered digits if code valid progam displays message thank we process order the output program error message the verification code valid please check credit card code input valid attempt lol rawinputwhat code rofllolsplit int rofl introfl print thank we process order else print the verification code valid please check credit card code purpose to learn i found another way involving checking whole thing worked perfectly but i trying learn request that give explicit direction fix code provide additional relevant advice close thank advance
2
what trying check given input matches given pattern three digits case basically regular expressions made using regex code would look like import code rawinputwhat code rematchr code print code ok else print wrong code in regex means beginning string means digit could also means repeated times means end string for informations regular expressions look module documentation
brief i trying write simple program checks given code valid the code valid three characters entered digits if code valid progam displays message thank we process order the output program error message the verification code valid please check credit card code input valid attempt lol rawinputwhat code rofllolsplit int rofl introfl print thank we process order else print the verification code valid please check credit card code purpose to learn i found another way involving checking whole thing worked perfectly but i trying learn request that give explicit direction fix code provide additional relevant advice close thank advance
2
lol rawinputwhat code rofllolsplit split perform think separates parts string according space tab line ends int rofl loop using int variable name good idea int standard type introfl rofl list redefine int use lol instead loop digits intd witll throw exception digit print thank we process order else print the verification code valid please check credit card code you test exactly digits and reply test loop per item loop
brief i trying write simple program checks given code valid the code valid three characters entered digits if code valid progam displays message thank we process order the output program error message the verification code valid please check credit card code input valid attempt lol rawinputwhat code rofllolsplit int rofl introfl print thank we process order else print the verification code valid please check credit card code purpose to learn i found another way involving checking whole thing worked perfectly but i trying learn request that give explicit direction fix code provide additional relevant advice close thank advance
1
i tried addressing problem unfound dynamics library compiling mysqldb module static libraries set static true sitecfg but generated error mysqlo still asking dynamic library to fix i added libraries block static setupposixpy
i downloaded followed install instructions mysql httpdevmysqlcomdownloadsmysql mysqldb python plugin httpsourceforgenetprojectsmysqlpython when i attempt import mysqldb python terminal i get error safira yanigisawa python version python safira yanigisawa python c import mysqldb traceback recent call last file string line module file buildbdistmacosxuniversaleggmysqldbinitpy line module file buildbdistmacosxuniversaleggmysqlpy line module file buildbdistmacosxuniversaleggmysqlpy line bootstrap importerror dlopenusersyanigisawapythoneggsmysqlpythonpymacosxuniversaleggtmpmysqlso library loaded libmysqlclientdylib referenced usersyanigisawapythoneggsmysqlpythonpymacosxuniversaleggtmpmysqlso reason image found safira yanigisawa i found question stack overflow followed instructions safira yanigisawa echo dyldlibrarypath usrlocalmysqllib safira yanigisawa ls l usrlocalmysqllib total rwxrxrx root wheel jan libmysqlclientdylib rwrr root wheel dec libmysqlclienta lrwxrxrx root wheel jan libmysqlclientdylib libmysqlclientdylib lrwxrxrx root wheel jan libmysqlclientrdylib libmysqlclientdylib lrwxrxrx root wheel jan libmysqlclientra libmysqlclienta lrwxrxrx root wheel jan libmysqlclientrdylib libmysqlclientdylib rwrr root wheel dec libmysqlddebuga rwrr root wheel dec libmysqlda rwrr root wheel dec libmysqlservicesa drwxrxrx root wheel dec plugin safira yanigisawa md usrlocalmysqlliblibmysqlclientdylib md usrlocalmysqlliblibmysqlclientdylib baabdbeddad safira yanigisawa and cleaning python egg files rebuilding i still got error then i found bug httpbugsmysqlcombugphpid mysql affecting mac i tried workaround listed cleaned eggs rebuilt i still getting error is another workaround problem specific python am i missing something else edit adding output otool commands safira yanigisawa otool l usersyanigisawapythoneggsmysqlpythonpymacosxuniversaleggtmpmysqlso usersyanigisawapythoneggsmysqlpythonpymacosxuniversaleggtmpmysqlso libmysqlclientdylib compatibility version current version usrliblibsystembdylib compatibility version current version safira yanigisawa otool dx usrlocalmysqlliblibmysqlclientdylib usrlocalmysqlliblibmysqlclientdylib safira yanigisawa
1
the java approach seems either get streaming dom parser python allows mixing two
stax seems pulling parser like sax without inversion control but i find equivalent python expandnode i interested first place i care inversion control for know pulldom stax parser point obtain current subtree dom node
1
in develop branch new option change css hashing method httpsgithubcomjezdezdjangocompressor see line filterscssdefaultpy the settings i using compressenabled true compressoffline false compressstorage compressorstoragegzipcompressorfilestorage compresscsshashingmethod hash using mtime since differs servers there option like js files since hash key never generated using mtime anyway this works perfectly behind loadbalancer when written following latest commit develop branch httpsgithubcomjezdezdjangocompressorcommitdbcfdabfebccfabffcb
i two servers behind load balancer each server running memcached server settings file identical servers defined short shared cache i want paths generated files identical servers client download for get working i need understand django compressor works what actual purpose cache django compressor is file content stored cache filesystem if happens first i hope i asking right questions feel free add a detailed better constructed sequence would helpful edit since servers share memcached server i set compresscachekeyfunction compressorcachesocketcachekey see develop branch using cache key contribute point file names the way i understand mtime collected source jscss files determine may changed new file generated correct this probably happen every load when happen
3
here nice demo using python opencv seems looking video code whether work without modification depends details spot the example uses cvhoughcircles identify circle object circle need replace
i working program python able following a webcam watching movement object moving path the object tracked marked big yellow spot i find yellow spot calculate centerpoint spot make calculations it would awesome centerpoint would draw picture remains whole time how would make happen ive already looked pil pygame opencv find working solution halfsolutions in steps would thanks help d
1
from html specs the html syntax support namespace declarations so i think lxmlhtmlhtmlparser removesignores namespace however beautifulsoup parses html differently i thought might worth shot if also beautifulsoup installed use beautifulsoup parser lxml like import lxmlhtmlsoupparser soupparser import lxmlhtml import io psomeparap opmsofficeparaop htmlsoupparserparseiobytesios beautifulsoup remove namespace neither recognize namespace instead part name tag that say htmlxpath op namespaces foo work but workaroundhack htmlxpath nameop print tag ttag text ttext yields tag op text msofficepara
i processing html files python lxml some edited ms word p tags written opampnbspop instance ie firefox interpret ms tags real p tags display line breaks op tags original editors formatted files eg spaces around nbsp lxml hand tidy processing html files see op tags changed proper p tags unfortunately tidying browsers display line breaks around nbsp breaks original formatting so idea browse op tags either remove add text attribute parent text attribute ie remove op tag markers lxml import etree import lxmlhtml stringio import stringio psomeparap opmsofficeparaop parser lxmlhtmlhtmlparser htmllxmlhtmlparse stringio parser htmlxpath p print tag ttag text ttext the result tag p text somepara tag p text msofficepara so lxlm removes namespace name tag marker is way know p tag namespace i remove ones op thanks
1
since march mathjax cdn use without uploading files gae just make sure page header script typetextjavascript srchttpcdnmathjaxorgmathjaxlatestmathjaxjsconfigtexamsmmlhtmlormml script
i trying add tex support application i would like use mathjax render mathematics formulas client side since i gave server side solution explained the mathjax library pretty fat files easily installed app engine due files number limitation i experience mathjax library i open strategies like available mathjax cdn cutting directoriesfiles reduce package files number do know way use mathjax google app engine
3
in code buttonself text open commandselfonsavepacksideleft first argument button instance tkinter container eg root window frame according httpcodegooglecompchildreneditorsourcebrowsetrunkeditornewpy self instance scrolledtext cannot contain widgets try changing self frm
why error tk attribute error traceback recent call last file editornewpy line module texteditormainloop file editornewpy line init buttonself text open commandselfonsavepacksideleft file cpythonliblibtktkinterpy line init widgetinitself master button cnf kw file cpythonliblibtktkinterpy line init basewidgetsetupself master cnf file cpythonliblibtktkinterpy line setup selftk mastertk attributeerror texteditor instance attribute tk code httpcodegooglecompchildreneditorsourcebrowsetrunkeditornewpy what wrong
1
check permissions classdump command chmod x classdump executable here docs chmod you might also need specify absolute path classdump path also try print joincommand see run pasting results shell
i trying execute following code python import ossubprocess glob import glob path usersarmedprivatesdks oschdirpath file globframework command classdump h file usersarmeddesktopheaders subprocesscallcommand on executing script get following error traceback recent call last file pyshell line module subprocesscallcommand file libraryframeworkspythonframeworkversionslibpythonsubprocesspy line call return popenpopenargs kwargswait file libraryframeworkspythonframeworkversionslibpythonsubprocesspy line init errread errwrite file libraryframeworkspythonframeworkversionslibpythonsubprocesspy line executechild raise childexception oserror errno permission denied any help much appreciated
1
encode turns unicode bytes decode turns bytes unicode you careful mix two your error means either chatter msgtext already bytes trying encode one worst features python lets tries first decode bytes using ascii limited encoding reencode whatever asked this fixed python use app engine app engine expects store unicode so need pass unicode string without encoding in fact data already bytestring would need decode store in short first thing try simply calling encode store data i may pointed please take time read article unicode
i roaming around forums asking questions issues related python utf encodingdecoding this time around i stumbled upon something initially seemed easy problem in previous question httpstackoverflowcomquestionsproblemswithpythoningoogleappengineutfandascii i asked ensure proper addition utf strings variables messagesappendchatmessagechatter msg the solution something along lines messagesappendchatmessagechatterencode utf msgencode utf pretty simple however i faced challenge send data google app engine datastore the code book i using code cloudlooked follows i skipped redundant parts start chatmessage class chatmessagedbmodel user dbstringpropertyrequiredtrue timestamp dbdatetimepropertyautonowaddtrue message dbtextpropertyrequiredtrue def strself return selfuser selftimestamp selfmessage end chatmessage start posthandler class chatroomposterwebapprequesthandler def postself chatter selfrequestgetname msgtext selfrequestgetmessage msg chatmessageuserchatter messagemsgtext msgput callout idcoput selfredirect end posthandler i thought swaping part posthandler following bit msg chatmessageuserchatterencode utf messagemsgtextencode utf would trick unfortunately happen i still keep getting file basedatahomeappssmarkccchatroomoneplpchatpy line post msg chatmessageuserchatterencode utf messagemsgtextencode utf unicodedecodeerror ascii codec decode byte xc position ordinal range naturally i declared coding utf statement put selfresponseheaders contenttype texthtml charsetutf file it nothing alleviate issue as see i wellversed python encodingdecoding problems bit novelty i would appreciate assistance if anyonone could explain i went wrong case practices use avoid similar quandaries future thank advance
2
i would treat different problem if imagine origin centre figure want print manhattan distance cell greater half length edge for example could following import sys r rangerr x rangerr c absx absy r else sysstdoutwritec print produces
you may noticed last query similar task i trying replicate structure if think composed triangles i able produce corners individually put one another i know i would go putting together larger construct though would i attempt would i approach problem tackling single construct work line line i individual triangle parts i assumed triangles bigger thing might shortcut
1
this worked w lines xrangew linesappendjoin w lines reversedlines l lines print l you could shrink wanted well lines join w xrangew print njoinlines lines output w
you may noticed last query similar task i trying replicate structure if think composed triangles i able produce corners individually put one another i know i would go putting together larger construct though would i attempt would i approach problem tackling single construct work line line i individual triangle parts i assumed triangles bigger thing might shortcut
1
print n join range print n join range httpcodepadorgzldeog
you may noticed last query similar task i trying replicate structure if think composed triangles i able produce corners individually put one another i know i would go putting together larger construct though would i attempt would i approach problem tackling single construct work line line i individual triangle parts i assumed triangles bigger thing might shortcut
1
for determinate mode want call start instead simply configure value widget call step method if know advance many bytes going download i assume since using determinate mode simplest thing set maxvalue option number going read then time read chunk configure value total number bytes read the progress bar figure percentage here simulation give rough idea import tkinter tk tkinter import ttk class sampleapptktk def initself args kwargs tktkinitself args kwargs selfbutton ttkbuttontextstart commandselfstart selfbuttonpack selfprogress ttkprogressbarself orienthorizontal length modedeterminate selfprogresspack selfbytes selfmaxbytes def startself selfprogressvalue selfmaxbytes selfprogressmaximum selfreadbytes def readbytesself simulate reading bytes update progress bar selfbytes selfprogressvalue selfbytes selfbytes selfmaxbytes read bytes ms selfafter selfreadbytes app sampleapp appmainloop for work going need make sure block gui thread that means either read chunks like example reading separate thread if use threads able directly call progressbar methods tkinter single threaded you might find progressbar example tkdocscom useful
i want show progress bar downloading file web using urlliburlretrive method how i use ttkprogressbar task here i done far tkinter import ttk tkinter import root tk pb ttkprogressbarroot orienthorizontal length modedeterminate pbpack pbstart rootmainloop but keeps looping
3
if need custom tool specific needs might want develop small django based wep app use celery spawn managed tasks you store log files models this probably require lot effort new web development if want cut programming time would like start generic solution might able start httpcodegooglecomppythonloggingserver some nonpython options cacti munin update see also djangotaskscheduler a web based python console tricky option considered risky non standard addition you consider thoroughly might security stability implications server apps if decide use one check links httpsgithubcomsympysympylive ajax console window ansivt support the probable alternative would probably ssh see also httpwwwpersonalumichedumresslwebshell
i like create web based control center i start processes watch statistics logs outputs also i would like run something like interactive python console webpage i know web development yet i know python something python based would nice could please suggest tools methods i learn implement ideally minimal effort achieve first results
1
encountered problem unmarshalling output p g option marshalloadsstr reads first record marshalloadstringiostr fails marshalload arg must file instead splitting suggested i used temporary file workaround import subprocess marshal tempfile tempf tempfiletemporaryfile subprocesspopencmd stdouttempfcommunicate tempfseek try record marshalloadtempf listdataappend record except eoferror pass tempfclose note python would delete temp file soon close
this really unfortunate situation maya comes code work pipe subprocesspopen p g edit csomefiletxt stdoutsubprocesspipestdout try record marshalload pipe listappend record except eoferror pass various versions work latest also works version ships maya course it throws error error typeerror file maya console line marshalload arg must file what best course action just move life code changed dump file marshalload could load actual file while works lame maya accesses python via zip small test i zipped pythonlib swapped syspath entries pointed zip zip while i tested extensively appears work i tell better worse idea one ideally i think something within i could make work without mixing python versions writing tempfiles disk time any ideas update regarding marshalloads trying marshalloads works error still work way i definitely fumbling around dark stuff the perforce stuff unbearably slow file operations done individually one query must the original code files abcn huge list files p subprocesspopencmd shelltrue stdinsubprocesspipe stdoutsubprocesspipe fi pipe pstdin pstdout fill command files file files fiwritefile n ficlose get results try record marshalload pipe listdataappend record except eoferror pass i know works x listdata ends list file results i figure marshalloads i get back first result this method taken almost verbatim perforce i know way things done it easy imagine i know use subprocess marshal properly update marshalloads totally work after testing piperead supplying data contains null characters something else i fully understand marshalloads would read first entry in particular case i split data collect data listdata results pipereadsplit skip first entry since empty result results listdataappend marshalloads result thanks cristian pointing right direction hopefully anyone upgrading maya using perforce things go little smoother
1
selflogger refer returned property threadawarelogger property
i code like class debugobject property def threadawareloggerself selfloggerinstanceforcurrentthread selfloggerinstanceforcurrentthreadselfclonemainlogger return selfloggerinstanceforcurrentthread def clonemainloggerself return loggerinstanceforcurrentthread class someotherclassobject def initself selfloggerdebugthreadawarelogger def othermethodself selfloggerinfomessage the problematic thing assignment selfloggerdebugthreadawarelogger i sure gonna content selflogger i want whole getter i want getter executed everytime i use selflogger someotherclass but i affraid selflogger stored result getter loggerinstanceforcurrentthread that means logger thread active time assignment this logger right one i call selfloggerinfomessage how get getter threadawarelogger executed everytime i call selfloggerinfomessage sidenote why i actually need shortcut selflogger when i decide replace threadawarelogger advancedthreadawarelogger i change one assignment instead thousand calls selfloggerinfomessage also none business othermethod care logger used edit the assignment getter works described answer unutbu but assigning getter causes issue i think from threadawarelogger i actually call method clonemainlogger now call someotherclasslogger ends exception attributeerror someotherclass object attribute clonemainlogger so far i bypassed issue small hack the someotherclass actually debug instance so i call debugclonemainlogger instead selfclonemainlogger inside threadawarelogger the program works i consider really dirty edit if i add line selfcomptreeloggerdebugthreaawarelogger inside method eg clonemainlogger i getting attributeerror property object attribute debug conclusion i still understand solution
1
a couple things there method order query get first ten entries it would efficient loop the reason template work referring list rather individual entry it entry entrieslist ibnameib entryname br img srcimages entrypicture height widthimgbr ibingredientsib entryingredients br pi entrydescription ip ibcreated byib entryuser brbr endfor once get template working try get entrieslist entrieslist recipesobjectsorderby id here docs sorting slicing queries httpsdocsdjangoprojectcomendevtopicsdbqueries
can seem see i going wrong forgive i new i trying display newest objects within model here loop i used put objects within list put top newest recipe objects list entrieslist allrecipes recipesobjectsannotatecount id newestrecipeindex lenallrecipes index index try x recipesobjectsgetidnewestrecipeindex entrieslistappendx newestrecipeindex newestrecipeindex index index except index index pass i render page like c requestcontextrequest form form entrieslist entrieslist return rendertoresponsemainhtml c and html entries entrieslist ibnameib entrieslistname br img srcimages entrieslistpicture height widthimgbr ibingredientsib entrieslistingredients br pi entrieslistdescription ip ibcreated byib entrieslistuser brbr endfor and modelspy class recipesmodelsmodel name modelscharfieldmaxlength ingredients modelscharfieldmaxlength picture modelsimagefielduploadto recipesymd user modelscharfieldmaxlength date modelsdatetimefieldautonowtrue description modelstextfield comments modelsmanytomanyfieldcomments it seems loop working the correct amount entries it template tags working they blank so seems working fine putting objects inside list retrieve individual fields
3
one way get whole property would make another property class someotherclass property def loggerself return selfdebugthreadawarelogger there might ways
i code like class debugobject property def threadawareloggerself selfloggerinstanceforcurrentthread selfloggerinstanceforcurrentthreadselfclonemainlogger return selfloggerinstanceforcurrentthread def clonemainloggerself return loggerinstanceforcurrentthread class someotherclassobject def initself selfloggerdebugthreadawarelogger def othermethodself selfloggerinfomessage the problematic thing assignment selfloggerdebugthreadawarelogger i sure gonna content selflogger i want whole getter i want getter executed everytime i use selflogger someotherclass but i affraid selflogger stored result getter loggerinstanceforcurrentthread that means logger thread active time assignment this logger right one i call selfloggerinfomessage how get getter threadawarelogger executed everytime i call selfloggerinfomessage sidenote why i actually need shortcut selflogger when i decide replace threadawarelogger advancedthreadawarelogger i change one assignment instead thousand calls selfloggerinfomessage also none business othermethod care logger used edit the assignment getter works described answer unutbu but assigning getter causes issue i think from threadawarelogger i actually call method clonemainlogger now call someotherclasslogger ends exception attributeerror someotherclass object attribute clonemainlogger so far i bypassed issue small hack the someotherclass actually debug instance so i call debugclonemainlogger instead selfclonemainlogger inside threadawarelogger the program works i consider really dirty edit if i add line selfcomptreeloggerdebugthreaawarelogger inside method eg clonemainlogger i getting attributeerror property object attribute debug conclusion i still understand solution
1
the problem col a b c d e f g your list supposed contain strings need quote letter like quoted strings print statements unquoted treated identifiers variables classes functions etc end error additionally mentioned voooza answer need sliceindex input string gets first character letter gets second character number either quote numbers row cast int inta comparison work finally since raw input variable called need format first print statement using input
question write program takes position chess board column col row value row checks whether position valid remember column chess board letter ranging a h inclusive row number inclusive a e valid inputs l if coordinates valid e programs prints the piece moved e otherwise prints the position valid my answer arawinputyou move col a b c d e f g row col row print the piece moved sd input else print the position valid error plugging value like d traceback recent call last file web session line module nameerror name a defined request can direct fix program context the purpose task set answer following question so far program used two separate inputs column row value can modify previous program chess problem version accept position chess board single input in words assume variable position stores column row value chess board b when coordinates input valid example c program prints message the piece moved c if first coordinate range print the first coordinate range ah ah second coordinate range print the second coordinate range close thank assistance
2
col a b c d e f g otherwise looks variables a b c find
question write program takes position chess board column col row value row checks whether position valid remember column chess board letter ranging a h inclusive row number inclusive a e valid inputs l if coordinates valid e programs prints the piece moved e otherwise prints the position valid my answer arawinputyou move col a b c d e f g row col row print the piece moved sd input else print the position valid error plugging value like d traceback recent call last file web session line module nameerror name a defined request can direct fix program context the purpose task set answer following question so far program used two separate inputs column row value can modify previous program chess problem version accept position chess board single input in words assume variable position stores column row value chess board b when coordinates input valid example c program prints message the piece moved c if first coordinate range print the first coordinate range ah ah second coordinate range print the second coordinate range close thank assistance
1
so if know basic c language your problem print element array so go like array int foriii print print array wrong similarly case iterating entrieslist assigning element variable entries now play entries entries entrieslist ibnameib entriesname br img srcimages entriespicture height widthimgbr ibingredientsib entriesingredients br pi entriesdescription ip endfor and ofcourse carl given better solution getting latest recipes case models
can seem see i going wrong forgive i new i trying display newest objects within model here loop i used put objects within list put top newest recipe objects list entrieslist allrecipes recipesobjectsannotatecount id newestrecipeindex lenallrecipes index index try x recipesobjectsgetidnewestrecipeindex entrieslistappendx newestrecipeindex newestrecipeindex index index except index index pass i render page like c requestcontextrequest form form entrieslist entrieslist return rendertoresponsemainhtml c and html entries entrieslist ibnameib entrieslistname br img srcimages entrieslistpicture height widthimgbr ibingredientsib entrieslistingredients br pi entrieslistdescription ip ibcreated byib entrieslistuser brbr endfor and modelspy class recipesmodelsmodel name modelscharfieldmaxlength ingredients modelscharfieldmaxlength picture modelsimagefielduploadto recipesymd user modelscharfieldmaxlength date modelsdatetimefieldautonowtrue description modelstextfield comments modelsmanytomanyfieldcomments it seems loop working the correct amount entries it template tags working they blank so seems working fine putting objects inside list retrieve individual fields
1
what get bytestring you must decode order get unicode string it basically comes bytestring fxevrier bytestringdecode utf u fã©vrier
i trouble get unicode values mysql queries here i mysqldb import connect mysqldbcursors import dictcursor con connect passwd db mydb user dbuser host localhost cursorclass dictcursor useunicodetrue charsetutf cursor concursor cursorexecute u select basicapplet res cursorfetchall printres titlede test title typeres titlede type str as see returning unicode in table structure titlede set unicode idbasicapplet int titlede varchar utfbin i really know i wrong help would really welcome thanks advance simon
1
ospath module using list think looking syspath
running testpy gives traceback recent call last file testpy line module map parsermapospath startwmap typeerror module object subscriptable parserpy import configparser def stringisnumberstring try intstring except return false return true class map parser configparserrawconfigparser mapurl def initself map selfparserreadmap selfmapurl map def tiletypesself all numerical sections assumed tiles return n n selfparsersections stringisnumbern testpy import parser import os map parsermapospath startwmap printmaptiletypes
1
import logging import random class debugobject property def threadawareloggerself loggers logginggetlogger abc logginggetlogger def return selfanotherdebugmethodloggers def anotherdebugmethodselfloggers return randomchoiceloggers class someotherclassobject def initself selfdebugdebug property def loggerself return selfdebugthreadawarelogger def othermethodself selfloggerinfo message name main loggingbasicconfiglevelloggingdebug xsomeotherclass range xothermethod yields output like infodefmessage infoabcmessage infodefmessage infodefmessage infoabcmessage notice changes abc def show debugthreadawarelogger function getting called time
i code like class debugobject property def threadawareloggerself selfloggerinstanceforcurrentthread selfloggerinstanceforcurrentthreadselfclonemainlogger return selfloggerinstanceforcurrentthread def clonemainloggerself return loggerinstanceforcurrentthread class someotherclassobject def initself selfloggerdebugthreadawarelogger def othermethodself selfloggerinfomessage the problematic thing assignment selfloggerdebugthreadawarelogger i sure gonna content selflogger i want whole getter i want getter executed everytime i use selflogger someotherclass but i affraid selflogger stored result getter loggerinstanceforcurrentthread that means logger thread active time assignment this logger right one i call selfloggerinfomessage how get getter threadawarelogger executed everytime i call selfloggerinfomessage sidenote why i actually need shortcut selflogger when i decide replace threadawarelogger advancedthreadawarelogger i change one assignment instead thousand calls selfloggerinfomessage also none business othermethod care logger used edit the assignment getter works described answer unutbu but assigning getter causes issue i think from threadawarelogger i actually call method clonemainlogger now call someotherclasslogger ends exception attributeerror someotherclass object attribute clonemainlogger so far i bypassed issue small hack the someotherclass actually debug instance so i call debugclonemainlogger instead selfclonemainlogger inside threadawarelogger the program works i consider really dirty edit if i add line selfcomptreeloggerdebugthreaawarelogger inside method eg clonemainlogger i getting attributeerror property object attribute debug conclusion i still understand solution
1
you use producerconsumer threads the threads synchronized using queuequeue edit example producerconsumer system threading import thread queue import queue def producequeue nitems rangenitems queueputd print put queueformatd def consumequeue nitems nitems you need sort stop condition queueget print got queueformatd def startproducerandconsumerwait q queue consumerthread threadtarget consume args q producerthread threadtarget produce args q producerthreadstart consumerthreadstart wait producerthreadjoin consumerthreadjoin name main startproducerandconsumertrue as see execute everything consumed correct order
imagine text file mb i reading char char extracting useful information i actually main functions one reading file second extracting info something like def readerpath f openpath r source fread fclose true i read char char call function extractor def extractors i extract useful information now goal continue read extractor working so basicaly question appropriate way accomplish goal
2
available x since using work correctly if upgrade get latest set commands able use command
i trying form fulltext search one mongodb collections la flowdock i create keywords entry document populate lowercased words fields document i search like prefixed search ex searchstring car foundshots connectionshotfind keywords recompile searchstringlowerlimitlimitskipskip the problem i try search multiple words ex searchstring car online regex recompile searchstringslower regex recompile searchstringslower foundshots connectionshotfind keywords regex keywords regexlimitlimitskipskip that work ideas please
1
groups empty since capturing groups httpdocspythonorglibraryrehtmlrematchobjectgroups group always returns whole text matched regardless captured group edited
when i run code print researchr groups i get result however group gives match shouldn groups give something containing match update thanks answers so means i research subgroups i use groups get match
3
creating closure self technically bind function alternative way solving similar underlying problem here trivial example selfmethod lambda self lambda args selfdoargsself
in python way bind unbound method without calling i writing wxpython program certain class i decided nice group data buttons together classlevel list tuples like class mywidgetwxwindow buttons ok onok cancel oncancel def setupself text handler mywidgetbuttons this following line problem line b wxbuttonparent labeltextbindwxevtbutton handler the problem since values handler unbound methods program explodes spectacular blaze i weep i looking around online solution seems like relatively straightforward solvable problem unfortunately i find anything right i using functoolspartial work around anyone know cleanfeeling healthy pythonic way bind unbound method instance continue passing around without calling
3
the reason capturing groups since use pattern httpdocspythonorglibraryrehtmlrematchobjectgroups and group returns entire search result even capturing groups httpdocspythonorglibraryrehtmlrematchobjectgroup
when i run code print researchr groups i get result however group gives match shouldn groups give something containing match update thanks answers so means i research subgroups i use groups get match
2
you groups regex therefore get empty list result try researchr groups with brackets creating capturing group result matches part pattern stored group then get result
when i run code print researchr groups i get result however group gives match shouldn groups give something containing match update thanks answers so means i research subgroups i use groups get match
1
to best knowledge groups returns tuple remembered groups ie groups regular expression enclosed parentheses so write print researchr groups would get response in general groups return tuple groups objects regular expression enclosed within parentheses
when i run code print researchr groups i get result however group gives match shouldn groups give something containing match update thanks answers so means i research subgroups i use groups get match
3
in qt pyqt events called signals bind using slots docs generally speaking define slot decorator class windowimpl qtguiqmainwindow uitremormain uigraphs def init self buffer parent none configuration none initialisation gui setup however qtcorepyqtslotint nameonconfselectorcombocurrentindexchanged def confchanged self newconf stuff handle event the would triggered currentindexchanged event object called confselectorcombo the setup confselectorcombo done gui builder qt creator nokia decided call this really want use get started there tutorials using qt creator obviously want go docs see signals emitted widgets as font stuff i know says docs if set font application default font machine used default font different different machines on windows default windows font used x one qtrc used if default font can’t found font specified qt used the qstylesheet qstyle act proxies changing appearance widgets qstylesheet qstyle as making application wait i found qtime dietime qtimecurrenttimeaddsecs qtimecurrenttime dietime qcoreapplicationprocesseventsqeventloopallevents there also qthreadsleep docs depending kind effect want probably also worth looking threading support nokia docs overall finding information stuff pyqt i found surprisingly useful look qt documentation writing stuff python times works on another note probably also worth looking pyside another python qt library i used works previously i noticed released version update just reiterate luke woodward use qgraphicsscene qgraphicsview render stuff object oriented way the qgraphicsscene actually render anything scene graph qgraphicsview used render contents scene graph for low level drawing thereâ´s also qpainter basic drawing tutorial it also worth looking qgraphicsitem base graphics items includes defining item geometry collision detection painting implementation item interaction event handlers docs the contextd provides html canvas i mistaken use webkit the canvas changed slot objects place canvas willcan slots there fairly complete looking tutorial contextd contextdcanvas for explanation many different ways rendering stuff ask someone else my two cents something fact qt supposed work everywhere trolltech later nokia wanted provide lots choice luckily docs really good
maybe i jumping deep end i give shot here useful features tkinter the tkinter canvas widget object oriented drawing canvas the elements drawing essentially widgets moved modified bound events tkinter uses bindings trigger callbacks the event passed string custom events easily created eventgenerate tkinter method waits specified amount time without freezing gui tkinter predefined fonts like tkdefaultfont colors like systembuttonface dependant system my questions what pyqt equivalents features especially bold ones how i bind elements widget eg label checkbutton event
1
httpsdocsdjangoprojectcomenstabletopicstestingtoolsdjangotestsimpletestcaseassertformerror djangotests import testcase class myteststestcase def testformsself response selfclientpostmyform something something selfassertformerrorresponse form something this field required where form context variable name form something field name this field required exact text expected validation error
i like simulate requests views django i writing tests this mainly test forms here snippet simple test request djangotests import testcase class myteststestcase def testformsself response selfclientpostmyform something something selfassertequalresponsestatuscode get page back error the page always returns response whether form error how i check form failed particular field soemthing error
3
it sounds like mean line profiler something measures time spent ie instrumenting within line i hope mean time wallclock time real goodsize software look cpu time going missing lot another way stacksampling wallclock time zoom ltprof profilers since every line stack sample localized line code using map pdb file way debuggers need parse modify source the percent time taken line code simply percent stack samples containing since working line level need distinguish exclusive self time inclusive time this line percent time active matters whether call another function call blind system function call microcode the advantage looking percents instead absolute times need worry app slowed either sampling competition processes things affect percents much also worry recursion if line code recursive function appears sample ok it still counts one sample containing line the reason ok line code could somehow made take time removing sample would occurred therefore samples containing line would removed sample set program total time would decrease amount fraction samples removed that irrespective recursion you also need count many times line code executed number matters locating code optimize percent time active here explanation issues
i trying determine necessary write line profiler language like available python matlab a naive way interpret line profiler assume one insert time logging around every line definition line dependent parser handles whitespace first problem it seems one needs use parse tree insert timings around individual nodes is conclusion correct does line profiler require parse tree needed beyond time logging update offering bounty question still unresolved update here link well known python line profiler case helpful answering question i yet able make heads tails behavior relative parsing i afraid code matlab profiler accessible also note one could say manually decorating input code would eliminate need parse tree automatic profiler update although question language agnostic arose i thinking creating tool r unless exists i found update regarding use line profiler versus call stack profiler post relating using call stack profiler rprof case exemplifies painful work call stack rather directly analyze things via line profiler
2
i know vpython perusing tutorial i would guess python range
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