text_a
stringlengths 5
12.3k
⌀ | text_b
stringlengths 36
15.7k
| Score
int64 1
3
|
---|---|---|
you use facebook graph batch query api query users | i working facebook application it written python running google app engine gae i know get relationship status users network way i running way slow there time limit gae order reduce cpu usage seconds using following code i get relationship status persons time frame getting deadlineexceedederror of course good enough since manymost people higher amount friends facebook what i get friend list user making api call one asking name relationship status the code i use f friends friendsinfof facebookapi f u fields namerelationshipstatus u accesstoken facebookaccesstoken and i get data relstatus friendsinfofu relationshipstatus what i need suggestions optimization ways extract relationship status entire network thanks advance edit the answers seems good ways solve problem though i find good tutorials batch request python i ended using fql call by using following takes seconds get data q select uid sex relationshipstatus user uid select targetid connection sourceid and actual data retrieved data fqlqueryqfacebookaccesstoken call function def queryselfqaccesstoken endpoint httpsapifacebookcommethod params dictqueryq accesstokenaccesstoken format json url endpoint fqlquery return selffetchurl paramsparams def fetchself url paramsnone conn urlliburlopenurl dataurlencodeparams try return jsonloadsconnread finally connclose hope someone make use well | 1 |
why would exit you iterating elements range exit condition run elements rebinding name change anything inside iterable if want break prematurely use break range break | python noob please explain loop exit range print hello world print next regards | 1 |
because done range created array elements like going one in programming languages called foreach loop otherwise another way | python noob please explain loop exit range print hello world print next regards | 3 |
because whatever means element whatever loop body executed setting element there rule says end iteration must still element whatever reassigning loop body effect whatsoever often loop body executes value hold next iteration | python noob please explain loop exit range print hello world print next regards | 1 |
because python loop count iterates range produces iterable list python x iterable iterated each time loop body executed next item pulled changes make loop body iteration variable affect memory next value supposed that saved elsewhere generally affect simply use break | python noob please explain loop exit range print hello world print next regards | 3 |
you iterating range object collection values ranging there logic behind collection numbers the item set syntax essentially loops every element set breaking every item looped your code equivalent c loop would produce desired result int if want break loop break loop range print hello world break print | python noob please explain loop exit range print hello world print next regards | 2 |
in python loop loop like c java instead iteration iterable in case assuming python x range way range function returns list a python list iterable therefore used loop language assigning variable first second third element time execute body part it matter alter variable body python pick next element list elements processed consider loop really different print hello world print turn also quite similar print hello world print assignment break loop | python noob please explain loop exit range print hello world print next regards | 1 |
you could try shutilmove shutil import move move cuserstesttxt cuserstestscsv or osremove shutilmove os import remove shutil import move remove cuserstestscsv move cuserstesttxt cuserstestscsv | is possible force rename osrename overwrite another file already exists for example code file testscsv already exists would replaced teststxt file also renamed testscsv osrenamecuserstesttxtcuserstestscsv | 3 |
change function bit lots ways add id form idchoiceform add line submits form function writetostorage user user count count localstoragesetitemchooser user documentgetelementbyidchoiceformsubmit | i handler choice textarea field choicehandler writes information returned database but posting form i want write user name localstorage this form form namechoiceform actionchoicehandler methodpost textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form on click i want assign username user write localstorage writetostorage head script typetextjavascript var count function writetostorage user user count count localstoragesetitemchooser user script head what i confused use onclickwritetostorage call writetostorage time actionchoicehandler form what correct way achieve something like i working google app engine python i add ajax call choicehandler later i solve as summary i want write javascript variable user localstorage post textarea choicehandler one click update i trying johndoe answer writetostorage never fired what i wrong the full code handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage alertcount count user user count line giving error fixed alertuser user count count alertuser user count count count localstoragesetitemchooser user script head body form namechoiceform idchoiceform actionchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form selfresponseoutwrite body html | 1 |
on unix dst exists file replaced silently user permission the operation may fail unix flavors src dst different filesystems if successful renaming atomic operation posix requirement on windows dst already exists oserror raised even file may way implement atomic rename dst names existing file httpdocspythonorglibraryoshtmlosrename | is possible force rename osrename overwrite another file already exists for example code file testscsv already exists would replaced teststxt file also renamed testscsv osrenamecuserstesttxtcuserstestscsv | 3 |
let function get invoked right form gets submitted form namechoiceform actionchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form | i handler choice textarea field choicehandler writes information returned database but posting form i want write user name localstorage this form form namechoiceform actionchoicehandler methodpost textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form on click i want assign username user write localstorage writetostorage head script typetextjavascript var count function writetostorage user user count count localstoragesetitemchooser user script head what i confused use onclickwritetostorage call writetostorage time actionchoicehandler form what correct way achieve something like i working google app engine python i add ajax call choicehandler later i solve as summary i want write javascript variable user localstorage post textarea choicehandler one click update i trying johndoe answer writetostorage never fired what i wrong the full code handler class choicewebapprequesthandler def getself selfresponseoutwrite html head script typetextjavascript var count function writetostorage alertcount count user user count line giving error fixed alertuser user count count alertuser user count count count localstoragesetitemchooser user script head body form namechoiceform idchoiceform actionchoicehandler methodpost onsubmitwritetostorage textarea namechoice rows colstextareabr input typesubmit valuesubmit choice form selfresponseoutwrite body html | 1 |
as documentation says impossible guarantee atomic renaming operation windows file exists python asking double step osremove osrename handling potential errors on unix systems rename overwrites destination exists operation guaranteed atomic note windows also possible deleting destination file fail even permission file may use this another essential limitation windows file system handle code | is possible force rename osrename overwrite another file already exists for example code file testscsv already exists would replaced teststxt file also renamed testscsv osrenamecuserstesttxtcuserstestscsv | 3 |
sorry misreading question in case i would suggest cache table yes updated using trigger on insert delete table transactions when allow user go transaction insert hash expiration timestamp table it triggers trigger update cached value ie value cache table according insert delete when checking wheteher free seats check cache table would sort caching work | i looking system people rsvp free web conference web conferences get really busy lot interest limited places way ensure get oversubscribed so need countdown time book seat time order completed confirmed this way first x amount people actually click attending get seats conference if user complete booking allocated seat put back pool someone else grab an overview happens i see best working user clicks rsvp event makes ajax request rsvpeventid this goes stores unique id refered token rest question along timestamp it stores token session the user notified x amount time let say mins complete rest details nameemaildob etc however anything put database checks amount pending orders less total seats available seats left conference returns saying sorry seats available keep checking bookings completed seats become available if user fills time stores details database attending if however fail fill form time cron job running every second go delete tokens timestamp minutes ago loose chance attend seat conference put back pool they notified unsuccessful taken back first step all easy enough write simply putting records database count from pendingbookings where conferenceid x working many seats either confirmed orders pending subtracting total seats available conference but i feel using mysql would scalable i sure excess k people trying grab around seats count one people get pretty expensive decent caching needs checking real time many people process i looked using amazon simpledb deployandgo scalability i used seen count necessarily accurate nature scalability i guess obvious reasons count needs accurate i need able add records along timestamp able delete records older five minutes | 1 |
instead checking corrupted file assume intact import bz try bzbzfilezipfileread print intact except ioerror print corrupted | is way check crc validity bz file python i using check png corrupted bz file thank | 3 |
elif location default item nothing print you picked item inventoryappenditem location elif location default item nothing print you enter room location i guess want call function name for need reference module class inside defined module somemodule function defined function getattrmodule location get reference function function call function if function defined current module function globalslocation function call function | i trying make textbased game python however code could get hand pretty quickly i one thing one line first source code sys import exit prompt inventory def menu true print enter start game start playing print enter password skip level want print enter exit exit game choice rawinputprompt choice start game shell elif choice password password elif choice exit exit else print input invalid try def password print enter password password rawinputprompt password go back print going menu else print wrong password you trying cheat pointlessly guess passwords deadcheating def shelllocationdefault item nothing location default item nothing print starting game starterroom disabled room actually made elif location default item nothing print you picked item inventoryappenditem location elif location default item nothing print you enter room location else print error closing game def location print nothing see placeholder location script spout errors def deadreason print you died reason exit print welcome menu first explanation game basically works the game shell input done receives information sends information different rooms game stores inventory it receive two arguments location eventual item added inventory however line first elif block shell line last elif block shell supposed go back whatever location location line exact i tried location work seems work printing things something is way if even writing engine game would nightmare or i make entirely different engine i think would way better approach case sorry i made mistakes first questionpost ever | 1 |
the cost depends implementation obviously i worry it unlikely going matter anyway standard protocols raise exceptions strangest places think stopiteration surrounded raising catching whether like when choosing lbyl eafp worry readability code instead focusing microoptimisations i avoid typechecking possible might reduce generality code | i looking python faq mentioned another question having never really looked detail i came across question âhow fast exceptionsâ a tryexcept block extremely efficient actually catching exception expensive in versions python prior common use idiom try value mydictkey except keyerror mydictkey getvaluekey value mydictkey i little bit surprised âcatching exception expensiveâ part is referring except cases actually save exception variable generally except including one example iâve always thought using idioms shown would pythonic especially python âit easier ask forgiveness get permissionâ also many answers so generally follow idea is performance catching exceptions really bad should one rather follow lbyl âlook leapâ cases note iâm directly talking example faq many examples look exception instead checking types | 3 |
no running quick tests heroku proxy proxyherokucom i make connections ports being heroku provide popsmtp make sense ports open i afraid | web services heroku normally use port environment variable i want run custom mail server heroku so i need expose ports preferably i live alternatives is possible | 2 |
use import eventlet eventletmonkeypatch import module or module eventletimportpatchedmodule either work httpeventletnetdocpatchinghtml | i would like multithread sending mail using django smtpconnection perhaps smtplib module i hoping module similar urllib i import eventlet eventletgreen import urllib except using smtplib instead urllib import however appear supported i read could monkey patched i unsure proceed any ideas accomplished eventlets or i drop python thread class etc | 1 |
here simple example based code provided tkinter import def changeimageargs change image label accordingly labelconfigimagephotosintstudfilesget app tk apptitleexample appgeometry x appconfigurebackground black appresizable studfiles stringvar studfilesset image files number corresponding list index studdropdown optionmenuapp studfiles files studdropdownconfigfonttimes italic studdropdownmenuconfigfonttimes italic studdropdownpack studfilestracew changeimage list photoimages image photos photoimagefile imgif photoimagefile imgif label labelappimagephotos labelpack appmainloop you make listtuple photoimage every graphic want you also trace stringvar know value optionmenu changed then set image label config method | i dropdown menu couple choices label image i would like change image according choice selected dropdown menubut cant figure example code tkinter import import tkinter tk def image list imgif imgif studdropdown menu delete end string list studdropdown menu addcommandlabelstringcommandlambda valuestringstudfilessetvalue apptk apptitleexample appgeometry x appconfigurebackground black appresizable buttonbuttonapptext press commandimage buttonpack studfiles stringvar studfilesset image files please wait studdropdown optionmenuapp studfiles files studdropdownconfigfonttimesitalic studdropdownmenuconfigfonttimesitalic studdropdownpack photo photoimagefile imgif label labelappimagephoto labelimage photo keep reference labelpack appmainloop maybe even use label display image suitable any ideas | 3 |
first tornado fapws web servers bottle web framework those belong completely different categories web frameworks usually run wsgi server behind http web proxy the http server included frameworks fast development deployment easy deployment sites high efficiency matter the idea basically http server apachelighttpdnginxtornadofapws etc good understanding http serving static files disk the dynamic content hand generated python server using web framework like bottleflaskwebpypylonsetc the document produced web framework sent back http server wsgi put http response sent client | so i done reading python web frameworks servers mostly tornado bottle also fapws still grey areas first three web frameworks said fast yet include web server written python except fapws put behind nginxapache isn reducing performance i mean know python much slower c use nginx worst included python web server | 3 |
the format response cmgl indexmessagestatusaddressaddresstextservicecentertimestampaddresstypesmsmessagebodylength smsmessagebody source you want text apart first line messagebody smstextsmstextindex rn | this sms message i obtained using at commands mobile cmgl rec readdd hey working bbc news channel pack rs dial now i need extract text message i tried approaches something always gets missed i using python any good suggestion | 1 |
your custom execute method return anything meaning checkuserid code none furthermore interested least one row returned query if none userid available the docs say calling fetchone returns none rows available you use checksql select userid from bsmembers where userid checkuser true newuseruserid gagetinput enter userid w dsexecutechecksqlcheckusernewuseruserid dsfetchone none this userid available break else print that user name already use please enter new username i assuming ds instance cursor subclass thereof | checksql select userid from bsmembers where userid checkuser doesuserexist false true doesuserexist false newuseruserid gagetinput enter userid w checkuserid dsexecutechecksqlcheckusernewuseruserid row ds row checkuserid doesuserexist true print that user name already use please enter new username break doesuserexist false break else continue i using cxoracle module python i trying prompt user enter userid the program check userid already exists prompt user different userid the execute method helper method uses execute method cxoracle interact oracle database the getinput method prompts user input checked regular expression i know i wrong i believe loop starts first action taken user prompted userid then userid checked database the loop starts checks row returned dsexecute userid provided user if user told use another user name break exits loop the statement checks user exists breaks loop if loop iterates user prompted enter nonexistent userid what happens user prompted userid none checking ever appears happen user program moves next piece code what i missing i included link docs execute the execute method code part following helper method def executeself statement parameters parameters none selfcursexecutestatement else selfcursexecutestatementparameters if i need provide information let know edit i forgot line doesuserexist false immediately beginning loop i added | 2 |
all deduced information available something expecting bytestring fed unicode object containing unicode character ub cyrillic small letter che with descender course encodable ascii default encoding hence error message best possible answer far don update you still asked question nonetheless so something crypto gadget decrypt method that surely needs str object what print reprencrypted tell if looks like random rubbish encrypted stuff somehow converted str object unicode object you need backtrack see happening if encrypted looks like meaningful text encryption process broken step start known plaintext encrypt decrypt simple script outside gae apparatus use print repr stage reasonable expectations next step step repeat step using gae inspecting type contents piece data update it appears urlencode page a corresponding urldecode page b part problem | i trying pass encrypted query string another url the following code gives error unicodeencodeerror ascii codec encode character u ub position ordinal range the encryption module pycrypto running python app engine page a import crypto cryptocipher import arc objarcnew stackoverflow msg this secret msg encrypted objencryptmsg selfredirect pageb urlliburlencode q encrypted page b import crypto cryptocipher import arc encrypted selfrequestget q objarcnew stackoverflow decrypted objdecryptencrypted getdata cgiparseqsdecrypted selfresponseoutwritedecrypted selfresponseoutwritepprintpprintgetdata traceback traceback recent call last file cprogram filesgooglegoogleappenginegoogleappengineextwebappwebapppy line call handlergetgroups file cprogram filesgooglegoogleappenginedemosguestbookguestbookpy line get decrypted objdecryptencrypted unicodeencodeerror ascii codec encode character u ub position ordinal range | 1 |
any directory write access long filesystem enough space store whoosh index like homemysitewhooshindex straight docs just make sure contents made public webserver | requires setting haystackwhooshpath place filesystem whoosh index located can anyone explain exactly path pointing i mean give path | 1 |
if tweepy feature need always access twitter directly http request the full twitter rest api described httpsdevtwittercomdocsapi the ones seem relevant interest get trendswoeid looks tweets woeid yahoo identifier collecting information given placelandmarketc get geoidplaceid mines geotagged tweets there documentation information available get request ip address among available fields httpsdevtwittercomdocsapigetsearch lastly twitter location search faq may interest | i following questions tweepy python module i trying retrieve tweets specific location i able using tweepy python module streaming api i get tweets whose geo locations enabled means i would loose rest tweeterâs tweet enabled geo location is better way retrieve tweets given location i use streamsample method retrieve tweets can someone tell parameters used sample method i see count async parameters now specify what firehose method tweepystream any help much appreciated | 2 |
catching exceptions expensive exceptions exceptional read happen often if exceptions rare trycatch faster lbyl the following example times dictionary key lookup using exceptions lbyl key exists exist import timeit sappend try x d key except keyerror x none sappend x d key key d else none sappend try x d xxx except keyerror x none sappend x d xxx xxx d else none ic enumerates timeittimercd key value print run mintrepeat output run trycatch key exists run lbyl key exists slower run trycatch key exist much slower run lbyl key exist when usual case exception trycatch extremely efficient compared lbyl | i looking python faq mentioned another question having never really looked detail i came across question âhow fast exceptionsâ a tryexcept block extremely efficient actually catching exception expensive in versions python prior common use idiom try value mydictkey except keyerror mydictkey getvaluekey value mydictkey i little bit surprised âcatching exception expensiveâ part is referring except cases actually save exception variable generally except including one example iâve always thought using idioms shown would pythonic especially python âit easier ask forgiveness get permissionâ also many answers so generally follow idea is performance catching exceptions really bad should one rather follow lbyl âlook leapâ cases note iâm directly talking example faq many examples look exception instead checking types | 3 |
don use nested loops use enumerate get index item item enumeratelst writetome open listitemtxt formati w writetomewriteitem writetomeclose sidenote don forget close files finished using | i list length n each item list need written n txt files for reason following basic approach working item lst rangelenlst writetome open listitemitxt w writetomewriteitem the file names fine listitemtxt listitemtxt etc same item written file so i end n files duplicate contents file any ideas | 1 |
i facing kind problem timesleep reliable android device locked mode here things i tried sla release pythonforandroidr android samsung galaxy s wrap timesleepinterval loop inside droidwakelockacquirepartial droidwakelockrelease this prevent cpu slowing use eventwaitforeventname timeoutinmilliseconds call droideventwaitforthiseventcannothappen interval threadingtimer object seems also work expected tests device confirmation needed i sure better keep mind tricks might drain power expected true lockedsleeping mode therefore reduce runtime device update eventwaitfor reliable either long intervals here snippet showing timer works import android import threading import logging def dostuff logginginfotesttimerpy stuff done droidnotify testtimerpy dostuff called droidvibrate def createlogpath loggingbasicconfigfilenamepath levellogginginfo format asctimes messages delay droidandroidandroid logpathmntsdcardtesttimerpylog createloglogpath timerthreadingtimerdelaydostuff logginginfotimer starting timerstart logginginfodostuff called timerdelayd delay | here python script written using androidscripting import android time droid androidandroid interval every minute true define vibrate pattern droidvibrate timesleep droidvibrate timesleepinterval it basically vibrates every minute like motivator however phone locked screen blanked i sense vibration perhaps android freezing script hence loop note i indeed running script service longtap click start service is way make script work time regardless phone suspend state update i hear vibration occasionally every minute rather like every minutes randomly update this problems occurs i run script normally service seems like timesleep sleeping specified time | 1 |
this worked note sort return sorted list sorted want pass template use sorted parameters sort pass list parameter itemizedactionlist listchaindetectionpointinsertbodyactionsetall detectionpointinsertheaderactionsetall detectionpointmodifybodyactionsetall detectionpointmodifyheaderactionsetall detectionpointremovebodyactionsetall detectionpointremoveheaderactionsetall detectionpointredirectactionsetall sorteditemizedactionlist keyattrgetter priority | i custom objects dictionaries i want sort i want sort objects dictionaries together i want sort objects attribute dictionaries key objectname jack name jill sortme object how i sort list using object name attribute dictionary name key | 1 |
here simple rule thumb code acts upon single instance object use method even better use method unless compelling reason write function in specific example want look like chessboard chessboard chessboardgetkingmoves don think always use methods point comes say make sense make method case make function | the zen python states one way things yet frequently i run problem deciding use function versus use method let take trivial example chessboard object let say need way get legal king moves available board do write chessboardgetkingmoves getkingmoveschessboard here related questions i looked why python use magic methods is reason python strings dont string length method the answers i got largely inconclusive why python use methods functionality eg listindex functions eg lenlist the major reason history functions used operations generic group types intended work even objects didnât methods eg tuples it also convenient function readily applied amorphous collection objects use functional features python map apply et al in fact implementing len max min builtin function actually less code implementing methods type one quibble individual cases itâs part python itâs late make fundamental changes the functions remain avoid massive code breakage while interesting really say much strategy adopt this one reasons custom methods developers would free choose different method name like getlength length getlength whatsoever python enforces strict naming common function len used slightly interesting my take functions sense pythonic version interfaces lastly guido talking abilitiesinterfaces made think rogue special method names in language reference says a class implement certain operations invoked special syntax arithmetic operations subscripting slicing defining methods special names but methods special names like len unicode seem provided benefit builtin functions rather support syntax presumably interfacebased python methods would turn regularlynamed methods abc len would become class container def lenself raise notimplemented though thinking i see syntactic operations invoke appropriate normallynamed method specific abc instance would presumably invoke objectlessthan perhaps comparablelessthan so another benefit would ability wean python away mangledname oddness seems hci improvement hm i sure i agree figure there two bits python rationale i like explain first first i chose lenx xlen hci reasons def len came much later there two intertwined reasons actually hci for operations prefix notation reads better postfix prefix infix operations long tradition mathematics likes notations visuals help mathematician thinking problem compare easy rewrite formula like xab xa xb clumsiness thing using raw oo notation b when i read code says lenx i know asking length something this tells two things result integer argument kind container to contrary i read xlen i already know x kind container implementing interface inheriting class standard len witness confusion occasionally class implementing mapping get keys method something file write method saying thing another way i see len builtin operation i hate lose i say sure whether meant def lenself certainly sounds like want demote ordinary method i strongly the second bit python rationale i promised explain reason i chose special methods look special merely special i anticipating lots operations classes might want override standard eg add getitem standard eg pickle reduce long time support c code i want special operations use ordinary method names preexisting classes classes written users without encyclopedic memory special methods would liable accidentally define operations mean implement possibly disastrous consequences ivan krstiä explained concise message arrived i written guido van rossum home page httpwwwpythonorgguido my understanding certain cases prefix notation makes sense ie duckquack makes sense quackduck linguistic standpoint functions allow interfaces in case guess would implement getkingmoves based solely guido first point but still leaves lot open questions regarding say implementing stack queue class similar push pop methods functions methods i would guess functions i really want signal pushpop interface tldr can someone explain strategy deciding use functions vs methods | 2 |
my general rule operation performed object object done object member operation if could apply things done something else object function perhaps member something else when introducing programming traditional albeit implementation incorrect describe objects terms realworld objects cars you mention duck let go class duck def initselfpass def eatself pass def crapself pass def dieself in context objects real things analogy correct add class method anything object so say i want kill duck i add kill duck no far i know animals commit suicide therefore i want kill duck i def killo duck odie elif dog print why odie elif nyancat raise exceptionnyan else print kill moving away analogy use methods classes because want contain data hopefully structure code manner reusable extensible future this brings us notion encapsulation dear oo design the encapsulation principal really comes designer hide everything implementation class internals absolutely necessarily user developer access because deal instances classes reduces operations crucial instance if operation instance specific member function tldr bryan said if operates instance needs access data internal class instance member function | the zen python states one way things yet frequently i run problem deciding use function versus use method let take trivial example chessboard object let say need way get legal king moves available board do write chessboardgetkingmoves getkingmoveschessboard here related questions i looked why python use magic methods is reason python strings dont string length method the answers i got largely inconclusive why python use methods functionality eg listindex functions eg lenlist the major reason history functions used operations generic group types intended work even objects didnât methods eg tuples it also convenient function readily applied amorphous collection objects use functional features python map apply et al in fact implementing len max min builtin function actually less code implementing methods type one quibble individual cases itâs part python itâs late make fundamental changes the functions remain avoid massive code breakage while interesting really say much strategy adopt this one reasons custom methods developers would free choose different method name like getlength length getlength whatsoever python enforces strict naming common function len used slightly interesting my take functions sense pythonic version interfaces lastly guido talking abilitiesinterfaces made think rogue special method names in language reference says a class implement certain operations invoked special syntax arithmetic operations subscripting slicing defining methods special names but methods special names like len unicode seem provided benefit builtin functions rather support syntax presumably interfacebased python methods would turn regularlynamed methods abc len would become class container def lenself raise notimplemented though thinking i see syntactic operations invoke appropriate normallynamed method specific abc instance would presumably invoke objectlessthan perhaps comparablelessthan so another benefit would ability wean python away mangledname oddness seems hci improvement hm i sure i agree figure there two bits python rationale i like explain first first i chose lenx xlen hci reasons def len came much later there two intertwined reasons actually hci for operations prefix notation reads better postfix prefix infix operations long tradition mathematics likes notations visuals help mathematician thinking problem compare easy rewrite formula like xab xa xb clumsiness thing using raw oo notation b when i read code says lenx i know asking length something this tells two things result integer argument kind container to contrary i read xlen i already know x kind container implementing interface inheriting class standard len witness confusion occasionally class implementing mapping get keys method something file write method saying thing another way i see len builtin operation i hate lose i say sure whether meant def lenself certainly sounds like want demote ordinary method i strongly the second bit python rationale i promised explain reason i chose special methods look special merely special i anticipating lots operations classes might want override standard eg add getitem standard eg pickle reduce long time support c code i want special operations use ordinary method names preexisting classes classes written users without encyclopedic memory special methods would liable accidentally define operations mean implement possibly disastrous consequences ivan krstiä explained concise message arrived i written guido van rossum home page httpwwwpythonorgguido my understanding certain cases prefix notation makes sense ie duckquack makes sense quackduck linguistic standpoint functions allow interfaces in case guess would implement getkingmoves based solely guido first point but still leaves lot open questions regarding say implementing stack queue class similar push pop methods functions methods i would guess functions i really want signal pushpop interface tldr can someone explain strategy deciding use functions vs methods | 3 |
use class want isolate calling code implementation details taking advantage abstraction encapsulation when want substitutable objects taking advantage polymorphism when want reuse code similar objects taking advantage inheritance use function calls make sense across many different object types example builtin len repr functions apply many kinds objects that said choice sometimes comes matter taste think terms convenient readable typical calls for example would better xsin ycossqrt sqrtsinx cosy | the zen python states one way things yet frequently i run problem deciding use function versus use method let take trivial example chessboard object let say need way get legal king moves available board do write chessboardgetkingmoves getkingmoveschessboard here related questions i looked why python use magic methods is reason python strings dont string length method the answers i got largely inconclusive why python use methods functionality eg listindex functions eg lenlist the major reason history functions used operations generic group types intended work even objects didnât methods eg tuples it also convenient function readily applied amorphous collection objects use functional features python map apply et al in fact implementing len max min builtin function actually less code implementing methods type one quibble individual cases itâs part python itâs late make fundamental changes the functions remain avoid massive code breakage while interesting really say much strategy adopt this one reasons custom methods developers would free choose different method name like getlength length getlength whatsoever python enforces strict naming common function len used slightly interesting my take functions sense pythonic version interfaces lastly guido talking abilitiesinterfaces made think rogue special method names in language reference says a class implement certain operations invoked special syntax arithmetic operations subscripting slicing defining methods special names but methods special names like len unicode seem provided benefit builtin functions rather support syntax presumably interfacebased python methods would turn regularlynamed methods abc len would become class container def lenself raise notimplemented though thinking i see syntactic operations invoke appropriate normallynamed method specific abc instance would presumably invoke objectlessthan perhaps comparablelessthan so another benefit would ability wean python away mangledname oddness seems hci improvement hm i sure i agree figure there two bits python rationale i like explain first first i chose lenx xlen hci reasons def len came much later there two intertwined reasons actually hci for operations prefix notation reads better postfix prefix infix operations long tradition mathematics likes notations visuals help mathematician thinking problem compare easy rewrite formula like xab xa xb clumsiness thing using raw oo notation b when i read code says lenx i know asking length something this tells two things result integer argument kind container to contrary i read xlen i already know x kind container implementing interface inheriting class standard len witness confusion occasionally class implementing mapping get keys method something file write method saying thing another way i see len builtin operation i hate lose i say sure whether meant def lenself certainly sounds like want demote ordinary method i strongly the second bit python rationale i promised explain reason i chose special methods look special merely special i anticipating lots operations classes might want override standard eg add getitem standard eg pickle reduce long time support c code i want special operations use ordinary method names preexisting classes classes written users without encyclopedic memory special methods would liable accidentally define operations mean implement possibly disastrous consequences ivan krstiä explained concise message arrived i written guido van rossum home page httpwwwpythonorgguido my understanding certain cases prefix notation makes sense ie duckquack makes sense quackduck linguistic standpoint functions allow interfaces in case guess would implement getkingmoves based solely guido first point but still leaves lot open questions regarding say implementing stack queue class similar push pop methods functions methods i would guess functions i really want signal pushpop interface tldr can someone explain strategy deciding use functions vs methods | 3 |
suppose array xnprandomrandintsize printx create array ynparray you look upon array mapping mapped then array desire given yx printyx | in numpy i array like i want replace element array array eg etc this convert elements arrays whole array array i tried things nothing worked what right way thanks | 2 |
you may interested arbitrary precision floating point library one httpcodegooglecompmpmath | is way python count significant figures doublefloatetc i seeing easy way i expect library thanks advance | 1 |
dir returns names current scope i remember exactly equivalent localskeys differences | question what object queried call dir python interpreter info i playing around package i want able pull names functions global dictionary i thought would dirglobal dirsysmodules i really sure if jump command line type dir fresh interpreter session give builtins doc name package would ob dirob would give return | 2 |
it appears installed xcode removed gcc used build python installed from path names traceback chances bitonly python downloaded pythonorg with xcode try installing latest bitbit os x installer python pythonorg instead you likely need reinstall packages installed like distribute pip dependencies depending version xcode may also need supply following environment variable setting running pip easyinstall export ccgcc | i used pip install scrapy mac get error anyone help please creating buildlibmacosxfattwistedinternetiocpreactoriocpsupport copying twistedinternetiocpreactoriocpsupportiocpsupportc buildlibmacosxfattwistedinternetiocpreactoriocpsupport copying twistedinternetiocpreactoriocpsupportwinsockpointersc buildlibmacosxfattwistedinternetiocpreactoriocpsupport copying twistedpythonepollc buildlibmacosxfattwistedpython copying twistedpythoninitgroupsc buildlibmacosxfattwistedpython copying twistedrunnerportmapc buildlibmacosxfattwistedrunner copying twistedtestraiserc buildlibmacosxfattwistedtest running buildext gcc fnostrictaliasing fnocommon dynamic arch ppc arch g o dndebug g o ilibraryframeworkspythonframeworkversionsincludepython c conftestc conftesto usrlibexecgccpowerpcappledarwinas assembler usrbinlibexecgccdarwinppcas usrbinlocallibexecgccdarwinppcas architecture ppc installed installed assemblers usrbinlibexecgccdarwinxas architecture x usrbinlibexecgccdarwinias architecture lipo open input file varfoldersjkjktyafdwecfvztscjwktitmpccbidblout no file directory gcc fnostrictaliasing fnocommon dynamic arch ppc arch g o dndebug g o ilibraryframeworkspythonframeworkversionsincludepython c conftestc conftesto conftestc error sysepollh no file directory conftestc error sysepollh no file directory lipo figure architecture type varfoldersjkjktyafdwecfvztscjwktitmpcceiymstout building twistedtestraiser extension creating buildtempmacosxfat creating buildtempmacosxfattwisted creating buildtempmacosxfattwistedtest gcc fnostrictaliasing fnocommon dynamic arch ppc arch g o dndebug g o ilibraryframeworkspythonframeworkversionsincludepython c twistedtestraiserc buildtempmacosxfattwistedtestraisero in file included usrincludearchitectureimathh usrincludemathh libraryframeworkspythonframeworkversionsincludepythonpyporth libraryframeworkspythonframeworkversionsincludepythonpythonh twistedtestraiserc usrincludeavailabilitymacrosh warning warning building intel mac os x deployment target invalid usrlibexecgccpowerpcappledarwinas assembler usrbinlibexecgccdarwinppcas usrbinlocallibexecgccdarwinppcas architecture ppc installed installed assemblers usrbinlibexecgccdarwinxas architecture x usrbinlibexecgccdarwinias architecture lipo open input file varfoldersjkjktyafdwecfvztscjwktitmpccnvrcyzout no file directory error command gcc failed exit status command libraryframeworkspythonframeworkversionsresourcespythonappcontentsmacospython c import setuptoolsfile usersbbbdropboxprojectsandroidcontinuousintegrationbuildtwistedsetuppy execcompileopenfilereadreplace rn n file exec install singleversionexternallymanaged record varfoldersjkjktyafdwecfvztscjwktitmppipmxezuxrecordinstallrecordtxt failed error code storing complete log usersbbbpippiplog | 1 |
sort pymongo takes key direction parameters so want sort let say id sortid | i trying use sort feature querying mongodb failing the query works mongodb console code follows import pymongo pymongo import connection connection connection db connectionmydb print dbpostscount post dbpostsfind entitiesusermentionsscreenname sortu entitiesusermentionsscreenname print post the error i get follows traceback recent call last file findowpy line module post dbpostsfind entitiesusermentionsscreenname sort entitiesusermentionsscreenname file librarypythonsitepackagespymongopymacosxuniversaleggpymongocursorpy line sort file librarypythonsitepackagespymongopymacosxuniversaleggpymongohelperspy line indexdocument typeerror first item key pair must string i found link elsewhere says i need place u infront key using pymongo work either anyone else get work bug | 3 |
generally i use classes implement logical set capabilities thing rest program i reason thing worry little concerns make implementation anything part core abstraction thing usually method this generally includes everything alter thing internal data state usually considered private part logical idea thing when come higher level operations especially involve multiple things i find usually naturally expressed functions built public abstraction thing without needing special access internals unless methods object this big advantage i decide completely rewrite internals thing works without changing interface i small core set methods rewrite external functions written terms methods just work i find insisting operations class x methods class x leads overcomplicated classes it depends code i writing though for programs i model collection objects whose interactions give rise behavior program important functionality closely coupled single object implemented methods scattering utility functions for programs important stuff set functions manipulate data classes use implement natural duck types manipulated functions | the zen python states one way things yet frequently i run problem deciding use function versus use method let take trivial example chessboard object let say need way get legal king moves available board do write chessboardgetkingmoves getkingmoveschessboard here related questions i looked why python use magic methods is reason python strings dont string length method the answers i got largely inconclusive why python use methods functionality eg listindex functions eg lenlist the major reason history functions used operations generic group types intended work even objects didnât methods eg tuples it also convenient function readily applied amorphous collection objects use functional features python map apply et al in fact implementing len max min builtin function actually less code implementing methods type one quibble individual cases itâs part python itâs late make fundamental changes the functions remain avoid massive code breakage while interesting really say much strategy adopt this one reasons custom methods developers would free choose different method name like getlength length getlength whatsoever python enforces strict naming common function len used slightly interesting my take functions sense pythonic version interfaces lastly guido talking abilitiesinterfaces made think rogue special method names in language reference says a class implement certain operations invoked special syntax arithmetic operations subscripting slicing defining methods special names but methods special names like len unicode seem provided benefit builtin functions rather support syntax presumably interfacebased python methods would turn regularlynamed methods abc len would become class container def lenself raise notimplemented though thinking i see syntactic operations invoke appropriate normallynamed method specific abc instance would presumably invoke objectlessthan perhaps comparablelessthan so another benefit would ability wean python away mangledname oddness seems hci improvement hm i sure i agree figure there two bits python rationale i like explain first first i chose lenx xlen hci reasons def len came much later there two intertwined reasons actually hci for operations prefix notation reads better postfix prefix infix operations long tradition mathematics likes notations visuals help mathematician thinking problem compare easy rewrite formula like xab xa xb clumsiness thing using raw oo notation b when i read code says lenx i know asking length something this tells two things result integer argument kind container to contrary i read xlen i already know x kind container implementing interface inheriting class standard len witness confusion occasionally class implementing mapping get keys method something file write method saying thing another way i see len builtin operation i hate lose i say sure whether meant def lenself certainly sounds like want demote ordinary method i strongly the second bit python rationale i promised explain reason i chose special methods look special merely special i anticipating lots operations classes might want override standard eg add getitem standard eg pickle reduce long time support c code i want special operations use ordinary method names preexisting classes classes written users without encyclopedic memory special methods would liable accidentally define operations mean implement possibly disastrous consequences ivan krstiä explained concise message arrived i written guido van rossum home page httpwwwpythonorgguido my understanding certain cases prefix notation makes sense ie duckquack makes sense quackduck linguistic standpoint functions allow interfaces in case guess would implement getkingmoves based solely guido first point but still leaves lot open questions regarding say implementing stack queue class similar push pop methods functions methods i would guess functions i really want signal pushpop interface tldr can someone explain strategy deciding use functions vs methods | 2 |
yeah um works you comparing integer list printyou caught nothing elif printyou caught minnow points score | this part bigger problem i problems ifelif function def fish import random score randomrandint printyou caught nothing elif printyou caught minnow points score printi printscore fish when i run i get randint number score i exactly sure i wrong | 3 |
you comparing integer list to trying one way range printyou caught nothing elif range printyou caught minnow points score | this part bigger problem i problems ifelif function def fish import random score randomrandint printyou caught nothing elif printyou caught minnow points score printi printscore fish when i run i get randint number score i exactly sure i wrong | 1 |
instead configure withapxsusrlocalapachebinapxs withpythonusrlocalsharemanmanpython i would assume would want use configure withapxsusrlocalapachebinapxs withpythonusrlocalbinpython i think want tell modwsgi use path python executable rather man page | i want build modwsgi python i built source code ubuntu you see specifically i built how would i build python source code ubuntu i tried running within modwsgi directory sudo configure withapxsusrlocalapachebinapxs withpythonusrlocalsharemanmanpython probably pretty naive since i know python text file executable command probably expects i ended getting bunch permission denied messages even though i ran sudo so would i build modwsgi python built source code also inherent issues i expect future python i built default ubuntu python coexisting separate directories | 1 |
first use easyinstall pip much reliable try installing see things go how install pip windows then install package search cmd search bar start menu run administrator pip install sqlalchemy | i trying install sqlalchemy project i tried different computers running windows vista identical python installations my first issue inability execute easyinstall computers different reasons next running included setuppy script work even running distributesetuppy running script command prompt python setuppy install finally trying manually run satopy script manually sqlalchemy folder work spat error message able find folder even given absolute path | 3 |
in general process called stemming package called stemming python used like stemmingporter import stem stemsimpsons stemming stem plurals could modify stemming package perform plural stemming take look source httptartarusorgmartinporterstemmerpythontxt | i list strings bill simpsons cosbys cosby bills mango mangoes what best remove plurals list so i want output bill simpsons cosby mango | 3 |
pluralization rules many corner cases perhaps bypass rules based approach use dictionary lookup identify plural form singular form word | i list strings bill simpsons cosbys cosby bills mango mangoes what best remove plurals list so i want output bill simpsons cosby mango | 1 |
you define following function def lcountkeyword fname openfname r fin return sum line fin keyword line now want know number lines containing int foocpp print lcount int foocpp an alternative command line appropriate platform grep int foocpp wc l | i pretty sure i thinking simple outcome i seem put together i looking kind search method i like python script search text file keyword count many lines appears though keyword comes single line multiple times i like still count long story short if keyboard comes single line i want count line add math equation any help greatly appreciated thanks advance | 1 |
iterate lists compare x rangelenseq rangelenseq ax seqx seqy | i two strings python i converted lists seq xxxx seq yyyy the strings length composed letters c g u then i created empty matrix lenseq lenseq numpyzerosshapelenseqlenseq next i want compare list values place values match the value placed relevant array element ie seq seq else repeat values print i loop working filled first row column i see problem range function like seqi seqj i figure | 1 |
ok i see going docs if one groups present pattern return list groups list tuples pattern one group as turns group returning last occurrence group one solution surround entire regex group like regex recompile return tuple containing matched groups course care first one personally would use following regex regex recompile dd avoid matching stuff like bad number edit here way avoid surround expression parenthesis deal tuples regex recompile refinditerregex match print matchgroup finditer returns iterator use access matches found match objects research returns group returns result expect | i need find matches string given regex i using findall i came across case i expected for example regex recompile there bicycles beijing print researchregex sgroup print refindallregex in case search returns i need longest match findall behaves differently although docs imply findall matches occurrences pattern first one search why behaviour different how i achieve result search findall something else | 3 |
the documentation pretty clear required httpcodegooglecompmodwsgiwikiquickinstallationguideconfiguringthesourcecode | i want build modwsgi python i built source code ubuntu you see specifically i built how would i build python source code ubuntu i tried running within modwsgi directory sudo configure withapxsusrlocalapachebinapxs withpythonusrlocalsharemanmanpython probably pretty naive since i know python text file executable command probably expects i ended getting bunch permission denied messages even though i ran sudo so would i build modwsgi python built source code also inherent issues i expect future python i built default ubuntu python coexisting separate directories | 1 |
you indexing lst rate loop variable one list four elements list three elements you either going miss element one list try access nonexistent element list | i started learning python i problem wring specific function basically function update list adding interest rate lst rate output here i far def multiplylst rate rangelenlst lsti ratei lsti i getting error message typeerror multiply sequence nonint type float thank | 1 |
lsti list numbers number you multiply list numbers number multiply elements list number | i started learning python i problem wring specific function basically function update list adding interest rate lst rate output here i far def multiplylst rate rangelenlst lsti ratei lsti i getting error message typeerror multiply sequence nonint type float thank | 2 |
alephnull answer correctly explains causing problem i think i better solution use regex regex recompiler dd some reasons better noncapturing group get one result match dd better regex efficient less likely return false positives you always use python raw strings regexes possible less likely surprised regex escape sequences like b word boundary interpreted stringliteral escape sequences like b backspace | i need find matches string given regex i using findall i came across case i expected for example regex recompile there bicycles beijing print researchregex sgroup print refindallregex in case search returns i need longest match findall behaves differently although docs imply findall matches occurrences pattern first one search why behaviour different how i achieve result search findall something else | 3 |
there two possible approaches make single bat file contains commands including regsvrexe commands execute have python script everything for first approach use open mode append batch file perhaps delete script start write contents three commands batch file within loop wind long batch file includes commands need then call subprocesscall command outside loop end script run entire thing for second approach remove batchfile writing run pathtoexe using python subprocesscall it almost simple deleting lines work output change outputwrite subprocesscall obviously fiddle contents little bit work subprocesscall directly | i exe file i call several parameters purpose i use bat file after i execute bat file command prompt close wait press key now i run exe several times i want run script path paths outout codecsopen runexebat w outputwritepathtoexe param param paramval param paramval param paramval param paramval outputclose subprocesscallregsvrexe path u subprocesscallregsvrexe path subprocesscallrunexebat paramval paramval paramval lists values related command prompt parameters when i call bat file everything works perfectly first fun exe executes command promt waits respond when i press key closes exe file starts different parameters so i want eliminate keypressing thing i tried put exit end bat file work how i close command prompt window script exe finishes working thanks advance upd sarmold way thing works fine i think exe console application waiting response smth exe file prevents console window closing i access sources how i close window executes upd i tried add shell call subprocesscall seem work either still respond console manually shell wincomclientdispatchwscriptshell shellappactivatecommand prompt shellsendkeysclsenter | 1 |
any directory wish you use configuration import os sys projectroot ospathdirnamefile haystackwhooshpath ospathjoinprojectroot searchindex | requires setting haystackwhooshpath place filesystem whoosh index located can anyone explain exactly path pointing i mean give path | 2 |
in view write sth like def myloginrequest app requestgetget app urlconf stays posted generally handle get parameters urlconf job views | i want url weibologinappfirst i want urlconf call view function parameters i know write url dispatcher pass appfirst view function the original urlconf urlpatterns patterns r weibologin weiboviewsmylogin the view function def myloginrequest i want pass appfirst view function eventually get dictionary function i know every parameter passed any good suggestions | 2 |
general guidelines add base encodingdecoding step encrypted stuff import base baseencryptedmessage basebencodeencryptedmessage send message via post get seen system logs encryptedmessage basebdecodebaseencryptedmessage decrypt message for error try reading unicode amp utf encoding nonascii characters you need step passing deencrypt function | i trying pass encrypted query string another url the following code gives error unicodeencodeerror ascii codec encode character u ub position ordinal range the encryption module pycrypto running python app engine page a import crypto cryptocipher import arc objarcnew stackoverflow msg this secret msg encrypted objencryptmsg selfredirect pageb urlliburlencode q encrypted page b import crypto cryptocipher import arc encrypted selfrequestget q objarcnew stackoverflow decrypted objdecryptencrypted getdata cgiparseqsdecrypted selfresponseoutwritedecrypted selfresponseoutwritepprintpprintgetdata traceback traceback recent call last file cprogram filesgooglegoogleappenginegoogleappengineextwebappwebapppy line call handlergetgroups file cprogram filesgooglegoogleappenginedemosguestbookguestbookpy line get decrypted objdecryptencrypted unicodeencodeerror ascii codec encode character u ub position ordinal range | 3 |
if working windows use pywin i found example import wincomclient wmi wincomclientgetobject winmgmts usb wmiinstancesof winusbhub print usbdeviceid | how query connected usb devices info python i want get uid device name ex sonyericsson w path device ex devttyacm and also would best parameter info used identifying device whenever connected uid i working ubuntu atm i code using pyusb busses usbbusses bus busses devices busdevices dev devices print reprdev print device devfilename print idvendor xx devidvendor devidvendor print idproduct xx devidproduct devidproduct print manufacturer devimanufacturer print serial deviserialnumber print product deviproduct the problem i get desired output paste one example usblegacydevice object x device idvendor xfce idproduct xda manufacturer serial product first i get filename important i assuming devttyacm etc part second i guess uid every usb device i use vendor product id edit apparently i setup issues i think i using wrong usb library using libusb atm that i get device devfilename string empty if someone please tell operating system using usb library version pyusb i think solve problems | 3 |
you try libusb bindings | how query connected usb devices info python i want get uid device name ex sonyericsson w path device ex devttyacm and also would best parameter info used identifying device whenever connected uid i working ubuntu atm i code using pyusb busses usbbusses bus busses devices busdevices dev devices print reprdev print device devfilename print idvendor xx devidvendor devidvendor print idproduct xx devidproduct devidproduct print manufacturer devimanufacturer print serial deviserialnumber print product deviproduct the problem i get desired output paste one example usblegacydevice object x device idvendor xfce idproduct xda manufacturer serial product first i get filename important i assuming devttyacm etc part second i guess uid every usb device i use vendor product id edit apparently i setup issues i think i using wrong usb library using libusb atm that i get device devfilename string empty if someone please tell operating system using usb library version pyusb i think solve problems | 1 |
sorry i know i understand correctly but i think good ide automatic code validation also work django for example good python plugin eclipse called pydev there also good ide based eclipsepydev called aptana studio try also good support editing htmljscss this question also good comparison python ide | what tools techniques help avoid bugs especially silly mistakes typos coding python django i know unittesting every line code proper way shortcuts i know pylint unfortunately check django orm named parameters typo go unnoticed is tool handle kind bugs a colleague thought idea gather smart statistics tokens example named parameters functions onceinacodebase token encountered warned possible typo do know tool something similar | 1 |
i think general correct approach two techniques could look eigenfaces name algorithms use eigenvectors facial recognition the bagofwords visual words approach | as selfdevelopment exercise i want develop simple classification algorithm given particular cell dilbert cartoon able identify characters present cartoon dilbert phb ratbert etc i assume best way apply algorithm image converts set features use training set one many possible machine learning algorithms correlate presenceabsence certain features particular character present cell so questions correct approach b since number classification algorithms ml algorithms test good methodology finding right one c algorithms would start given essentially conducting classification exercise cartoon | 1 |
pyflakes static analyser find undeclared variables eg typos like plenty editors plugins run pyflakes fly save this substitute unit tests save unnecessary savereloadrun cycles | what tools techniques help avoid bugs especially silly mistakes typos coding python django i know unittesting every line code proper way shortcuts i know pylint unfortunately check django orm named parameters typo go unnoticed is tool handle kind bugs a colleague thought idea gather smart statistics tokens example named parameters functions onceinacodebase token encountered warned possible typo do know tool something similar | 1 |
anydbm module dbdbmgdbm type files it work sqlite they thing file format use sqlite module sqlite databases | i db file created sqlite i want use anydbm read file my code import anydbm db anydbmopen mydbdb r however throws error anydbmerror db type could determined i get what wrong the file type according unix file command sqlite x does anybody know causing also better library reading db files thanks | 2 |
try committing closing connection curclose conncommit connclose from psycopg documentation note closing connection without committing changes first cause pending change discarded rollback performed unless different isolation level selected see setisolationlevel | i trying call function psycopg like conn psycopgconnecthostnamehostex userusername passwordsecret cur conncursor curcallprocfdoaction aaa bbb curclose connclose when calling function psql everything works fine using psycopg nothing seems happen i get exception it call function actual database also queries psycopg work select insert | 3 |
you might like consider rabbitmq amqp message broker amqp protocol designed build messaging queuing routing systems there several python clients connecting amqp brokers | i developing system queue filled millions items i need process reads items queue constantly sends items registered clients i thinking using twisted queue reader twisted server listening tcp port clients connect port item pulled queue server writes clients does sound like something twisted would ideal does anyone know sample code may something similar | 1 |
i gotten rc interface work piped stdinstdout windows i get ioerror attempts communicate write directly stdin there option rcfaketty lets rc interface scripted linux available windows least somewhat dated version vlc using socket interface hand seems work fine the structure assigned startupinfo option used win createprocess function configured hide process window however vlc rc console i think simpler use existing rcquiet option in general configure startupinfo hide process window startupinfo subprocessstartupinfo startupinfodwflags subprocessstartfuseshowwindow subprocesspopencmd startupinfostartupinfo just complete case using pipes failing system little demo i cooked using rchost option communicate using socket it also uses rcquiet hide console this prints help quits i tested anything else i checked works python versions i know ask maybe useful nonetheless import socket import subprocess select import select try import winreg except importerror import winreg winreg try vlcpath winregqueryvalueex winregopenkeywinreghkeylocalmachine r softwarevideolanvlc except windowserror exiterror vlc found def sendcommandsock cmd getresultfalse try cmd cmd n encode ascii except attributeerror cmd b n sent total socksendcmd total lencmd sent socksendcmdtotal sent raise socketerror socket connection broken total sent getresult return receiveresultsock def receiveresultsock data bytearray socksetblocking selectsock chunk sockrecv chunk b raise socketerror socket connection broken dataextendchunk socksetblocking return datadecode utf def mainaddress port import time rchost formataddress port vlc subprocesspopenvlcpath i rc rchost rchost rcquiet sock socketsocketsocketafinet socketsockstream try sockconnectaddress port helpmsg sendcommandsock help true printhelpmsg sendcommandsock quit except socketerror e exiterror eargs finally sockclose timesleep vlcpoll none vlcterminate name main main localhost | i using windows vista python answers python so i start interact subprocesses stdinstdout normally using python commandline programs dir however program i want call likes make new console window windows curses new handles even run preexisting cmdexe window odd remote control interface vlc is way either getting handles processmade console stdinout getting new shell run within old like invoking bash within bash failing i hack subprocesses code would new console set windows inoutput transferred edit ie p popenargs vlc i rc stdinpipestdoutpipe new console appears text asking commands pstdinwritequitrn traceback file stdin line module ioerror errno invalid argument pstdoutreadline pstdoutreadline but new console window comes accept keyboard input either whereas normally p popenargs cmd stdinpipestdoutpipe pstdinwritedirrn pstdinflush pstdoutreadline don irl may block microsoft windows version | 1 |
your data structure dictionary dictionaries first place njnkjkn embeddedlist jbbhjhb embeddedlist this make desired operations much easier if inner dictionaries contain embedded list simplified njnkjkn jbbhjhb now need collectionsdefaultdictlist collections import defaultdict defaultdictlist njnkjkn appendwhatever | i attempting create list dicts following structure id njnkjkn embeddedlist id jbbhjhb embeddedlist initially list empty what i need able check see dict specific id exists list already if dict containing id exists append something embeddedlist if dict containing id exist create dict append list i aware able test dict exists list based something inside dict using something like extracteddict nextitem item list item id uniqueid none i unsure append something list within dict within list efficiently is obvious way i seeing probably thank advance | 2 |
simple dic njnkjkn jbbhjhb | i attempting create list dicts following structure id njnkjkn embeddedlist id jbbhjhb embeddedlist initially list empty what i need able check see dict specific id exists list already if dict containing id exists append something embeddedlist if dict containing id exist create dict append list i aware able test dict exists list based something inside dict using something like extracteddict nextitem item list item id uniqueid none i unsure append something list within dict within list efficiently is obvious way i seeing probably thank advance | 1 |
if want rely extra installed modules parse output wmic eg c wmic process get descriptionexecutablepath explorerexe cwindowsexplorerexe cmdexe cwindowssyswowcmdexe conhostexe cwindowssystemconhostexe reference httpgeekpediawordpresscomusecommandlinetotrackwindowsprocesses | i amm writing little python script grab information vms windows i running at moment i list processes bit xp machine following method httpcodeactivestatecomrecipes is possible somehow detect version windows running excute different method getting processes bit machine i trying get processes bit vista bit windows any ideas | 3 |
it easy install manually download may newer releases pythonorg wget httpswwwpythonorgftppythonpythontarxz unzip tar xf python cd python prepare compilation configure build make install make install or want overwrite python executable safer least distros yum needs python x rhel install python concurrent instance system default altinstall make altinstall now want alternative installation directory pass prefix configure command example installing python optlocal add prefixoptlocal after make install step in order use new python installation could still add prefixbin path prefixlib ldlibrarypath depending prefix passed | i trying install python rhel using following steps yum search python which returned no matches found python followed yum search python none search results contained python what i try next | 3 |
try setting environment variable pythonioencoding utf that make python use encoding instead none default | i using php i trying learn python i never really serious problem encoding php at least i could solve minutes i spent hours solve encoding problems python i still solve so problem i want print japanese string file using shell redirect using command python makecsvpy csvfilecsv but japanese texts printed csv file messed i tried several solutions like using encode utf etc still luck i also encounter error unicodedecodeerror ascii codec decode byte xe position ordinal range i solve please help | 1 |
change wind tkintertk wind tkintertoplevel def new wind tkintertoplevel windgeometry x that need change reference tkinter toplevel | i message image pyimage exist i want multi windows images here code import image import imagetk import tkinter def new wind tkintertk windgeometry x this work imagefile imageopensomeimagejpg image imagetkphotoimageimagefile panel tkinterlabelwind imageimage panelplacerelx rely windmainloop master tkintertk mastergeometry x this work fine imagefile imageopensomeimagejpg image imagetkphotoimageimagefile panel tkinterlabelmaster imageimage panelplacerelx rely b tkinterbuttonmaster text new image command newpack mastermainloop | 2 |
you need use redotall flag allow capture newline characters also escape braces special characters python regex syntax researchrbook pagetext redotall | in python i big text multline i need get text book i tired using regular expression problem text inside mutiline string i tried book gives text first line i tried book gives error researchbook pagetextgroup i tried varied expression problem go next line regular expression lot text book series name twilight image filethe twilight saga hardbackjpgpx language english do link per wp overlink genre romance novelromance fantasy literaturefantasy youngadult fiction publisher little brown company pubdate ã¢â¬â mediatype print lot text | 1 |
that good question i afraid answer might matplotlib gtk backend written pygtk oldstyle python bindings gtk the girepository package newstyle python bindings i know one way whether mix results seem indicate | i troubles understanding girepository i use contruction code girepository import gtk but i want use component i get import error i searched i got worked components like gtksource vte glib so code like girepository import gtk gtksource vte glib everything worked fine i want add matplotlib draw canvas i get error enter codeusrlibpythonsitepackagesgtkgtkinitpy warning specified class size type pygtkgenericcellrenderer smaller parent type gtkcellrenderer class size gtk import gtk usrlibpythonsitepackagesgtkgtkinitpy warning gtypegetqdata assertion node null failed gtk import gtk usrlibpythonsitepackagesgtkgtkinitpy warning gasciistrncasecmp assertion null failed gtk import gtk segmentation fault core dumped how i get matplotlib working girepository thank | 3 |
l b c newl jj j l newl b c this works python python need newl jj j l these list comprehensions equivalent following verbose code newl l temp j tempappendjj newlappendtemp | i list like following mylist b c i got different operations code is possible get output like following newlist b c the input list contents ranges output list generated taking average two numbers range thank | 2 |
to work one lists valid python portion could use list comprehension numbers print sumx floatlenx x numbers this get right direction gives | i list like following mylist b c i got different operations code is possible get output like following newlist b c the input list contents ranges output list generated taking average two numbers range thank | 1 |
list comprehensions nice favorite pythonic technique map applies function every element structure ls b c li ls printli listmaplambda x sumxlenx li as tim says works python need floatlenx python | i list like following mylist b c i got different operations code is possible get output like following newlist b c the input list contents ranges output list generated taking average two numbers range thank | 2 |
you need look tail property well text text gives text directly start tag tail gives text directly end tag this provide many small strings tip use etreeiterwalkelem thing etreeiterparse existing tree instead iterate start end tags to idea event elem etreeiterwalkxmlelem events start end event start start tag print starting element elemtag print elemtext elif event end end tag print ending element elemtag elem xmlelem dont want text trailing xmlelem print elemtail i guess complete rest warning text tail none want concatenate guard use elemtext example if familiar sax existing sax code need lxml lets produce sax events element tree lxmlsaxsaxifyelem handler some things look extracting text element itertext method xpath expression text lxml lets return smart strings xpath expressions allow check element belong etc | i xml data looks like xml the captial place pidsouth africaplace placepretoriaplace xml i would like able extract the xml elements currently provided etree the full plain text document start end tags the location within plain text start element character offset important requirement right etree provides fine i cannot see way directly hoped iterating elements document tree would return many small string could reassembled thus providing however requesting text root node returns text root node first element eg the capital doing sax could involve implementing lot already written many times eg minidom etree using lxml option package code go can anybody help | 1 |
i think windows supports shebang line try invoking python djangoadminpy | run djangoadminpy startproject mysite djangoadminpy located cpythonscriptsdjangoadminpy open file editor opens python ide past pype would open pype file opens cpythonpythonexe djangocore import management name main managementexecutefromcommandline see output command prompt lets say typed cabcdjangoadminpy startproject mysite i hit enter see cabc project created using command prompt issue new creating python projects using pydev would love fix issue command prompt though slugonamission i run pyhon djangoadminpy startproject mysite output command prompt python open djangoadminpy file errno no file directory | 3 |
so think right track wrt step apply algorithm image converts set features this project challenging ml problems actually create training data set raw data individual frames comprising cartoons for instance grab frame identify two characters frame dilbert character horns dilbert boss believe know name extract two characters frame append appropriate class label eg dlibert step to extract individual characters frames comprising dilbert cartoon would suggest spectral decomposition frame if familiar technique core eigenvector decomp if like python r given use pythontor bindings like rpy would strongly encourage look sklearn in particular excellent library originally developed scipy scikits project umbrella therefore uses numpy scipy matrix computation several algorithms image segmentation one based spectral clustering for step project would likely want look two scikitslearn modules sklearnfeatureextraction esp image submodule sklearnclusterspectralclustering included two modules two good example scripts one segmenting digital photograph segmenting image comprised three partially superimposed circles minimal contrast wrt wrt backgroundboth suspect difficult problems decompositions need perform in words sklearn two complete welldocumented example scripts included source distribution process data similar either would excellent template step step so first step second sort components decomposed images groups one group dilbert character next assign class label group eg four characters decomposition step decent choice class labels append class labels component matrices decomposition products step character matrix mapped corresponding class dilbert character step select suitable ml technique you many choices step criteria technique supervised category assigned class labels data function classifier ie returns class label versus regressor outputs numerical value given personal project would chose one seems interesting a satisfy criteria mentioned multilayer perceptron neural network support vector machine svm knearest neighbors knn step train validate test classifier alternative technique template matching once step completed image decomposed set objects doubt represent characters manually sift decomposition products collect exemplars character cartoon the templates next compare objects segmented image set unique templates in scikitimage another scipy scikit use method matchtemplate pass template image candidate image method returns d array showing pixelbypixel correlation | as selfdevelopment exercise i want develop simple classification algorithm given particular cell dilbert cartoon able identify characters present cartoon dilbert phb ratbert etc i assume best way apply algorithm image converts set features use training set one many possible machine learning algorithms correlate presenceabsence certain features particular character present cell so questions correct approach b since number classification algorithms ml algorithms test good methodology finding right one c algorithms would start given essentially conducting classification exercise cartoon | 3 |
even unix shebang forcing version run if program executed directly mypy instead run like python mypy python still used i would suggest safest way check version beginning script bail error message suitable example sysversioninfo print requires python sysexit | i know write python script tell unix box version python run usrbinenv python i windows i deploying program distutils windows boxes python installed i need force use thanks | 2 |
files designated static appyaml available application code python runtime they served directly user browser response requests matching regular expression appyaml do mark templates static only files served asis user javascript css images marked static | i problem using template google app engine python thing i address static folder yaml i not access template i remove access able look files file structure src calcpy mainpy indexhtml templ calchtml js css yaml handlers url script mainpy mainpy def main application webappwsgiapplication mainpage calc calc debugtrue wsgirefhandlerscgihandlerrunapplication calcpy class calcwebapprequesthandler def getself temp ospathjoinospathdirnamefile templcalchtml outstr templaterendertemp tempval selfresponseoutwriteoutstr the result is status ok contenttype texthtml charsetutf i reach file template addressing working buttttttt i add following line yaml access css js it access able yaml handlers url script mainpy url templ staticdir templ if change order yaml handlers url templ staticdir templ url script mainpy both not working error status internal server error traceback recent call last file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebappwebapppyquot line call handlergetgroups file quotusersemdocumentsworkspacenerkharzsrccalcpyquot line get outstr templaterendertemp tempval file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line render loadtemplatepath debug file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line load return loaduserdjangopath debug file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginegoogleappengineextwebapptemplatepyquot line loaduserdjango template djangotemplateloadergettemplatefilename file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginelibdjangodjangotemplateloaderpyquot line gettemplate source origin findtemplatesourcetemplatename file quotapplicationsgoogleappenginelauncherappcontentsresourcesgoogleappenginedefaultbundlecontentsresourcesgoogleappenginelibdjangodjangotemplateloaderpyquot line findtemplatesource raise templatedoesnotexist name templatedoesnotexist calchtml please help must simple solution i really dont believe gae much fool thank advanced | 2 |
almost although would still possible path like foo better would use ospathjoin ospathabspath together correctly handle leading anywhere path targetdir target trailing slash important tarfileopen⦠tarf n tarfnames ospathabspathospathjointargetdir nstartswithtargetdir print unsafe filenames sysexit tarfextractallpathtargetdir | in python documentation adviced extract tar archive without prior inspection what best way make sure archive safe using tarfile python module should i iterate filename check wether contain absolute pathnames would something like following sufficient import sys import tarfile tarfileopen sampletar r tarf n tarfnames n n print sampletar contains unsafe filenames sysexit tarfextractall edit this script compatible versions prior cf tarfile i iterate members targetdir target closingtarfileopen sampletar mode rgz tarf tarf pathn ospathabspathospathjointargetdir mname pathnstartswithtargetdir print the tar file contains unsafe filenames aborting sysexit tarfextractm pathtdir | 2 |
you using assertraises incorrectly instead write selfassertraisesintegrityerror adduser userdetail userdetail you give function arguments separately assertraises control function called eg tryexcept block assertraises the problem function test swallowing error try def adduseruserdetails try u useruserdetails sessionaddu sessioncommit except sessionrollback raise reraise exception allowing transaction rolled back | i trying unit test sqlalchemy code def adduseruserdetails try u useruserdetails sessionaddu sessioncommit except sessionrollback now unit test def testduplicateself adduseruserdetailuserdetail selfassertraisesintegrityerror adduseruserdetailuserdetail this test succeed adduser function call raises integrity error fail exception but problem test succeeds cases why happening is something wrong code assertraises works differently i expecting atfirst i thought happening i put except try clause exception dealt assertraises get exception but would case assertraises failed receiving exception if something wrong way writing unit test tell i still learning incorporate unit testing coding habits | 2 |
it bug httpcodegooglecompgoogleappengineissuesdetailid hopefully corrected next version | i trying make change old appengine application formating pc installing updated tools logging functions raising unicode error in previous development environment everything worked fine ubuntu python google appengine sdk now i trying make change using environment ubuntu python google appengine sdk in new development environment i getting errors using logging functions logginginfou gerando lista de exibiã§ã£o error error ascii codec decode byte xc position ordinal range args ascii gerando lista de exibixcxaxcxao ordinal range encoding ascii end message object gerando lista de exibixcxaxcxao reason ordinal range start to work i need remove accents logginginfou gerando lista de exibicao ok my editor utf scripts coding utf first line this version problem there settings | 2 |
would probably override form init method take user argument set somewhere form class myform def initself user args kwargs supermyform selfinitargs kwargs selfuser user def cleanfield selfuser etc | as part form validation django i want check user last made post i look question stackoverflow appear address issue initially used accepted answer essentially process moment add requestuser object def formvalidself form method createview subclass however allow user variable used form validation since i want access user variable validation check time since last post logically validation i need user variable injected form earlier i tried altering getinitial method def getinitialself initial superarticlecreateview selfgetinitial initial user selfrequestuser return initial this successfully sets user key initial dictionary never makes cleaning process deals stuff data dictionary removes anything initial i deliberately excluded user form display appears also remove cleaning process validation is correct way override init method form getinitial method view putting user initial form pulling extra information initial form init i looking pass requestuser form i access within formwide clean method additional checks amount validation def cleanself superarticleform selfclean check whether user posted recently raise validationerror return selfcleaneddata j | 1 |
the way i solved moment keep validation within form rest business logic view consequently i done following in view def getinitialself initial supermycreateview selfgetinitial initial user selfrequestuser return initial in form def initself args kwargs selfuser kwargs initial user supermyobjectform selfinitself args kwargs def cleanself clean submitted data supermyobjectform selfclean validate user submitted n time ago profile selfusergetprofile datetimenow profilelastpost timedeltahours raise formsvalidationerrorneed wait longer n hours else selfcleaneddata user selfuser return selfcleaneddata which seems work flaws i seen solution | as part form validation django i want check user last made post i look question stackoverflow appear address issue initially used accepted answer essentially process moment add requestuser object def formvalidself form method createview subclass however allow user variable used form validation since i want access user variable validation check time since last post logically validation i need user variable injected form earlier i tried altering getinitial method def getinitialself initial superarticlecreateview selfgetinitial initial user selfrequestuser return initial this successfully sets user key initial dictionary never makes cleaning process deals stuff data dictionary removes anything initial i deliberately excluded user form display appears also remove cleaning process validation is correct way override init method form getinitial method view putting user initial form pulling extra information initial form init i looking pass requestuser form i access within formwide clean method additional checks amount validation def cleanself superarticleform selfclean check whether user posted recently raise validationerror return selfcleaneddata j | 1 |
write function query single float call twice def inputfloatmsg true try return floatrawinputmsg except valueerror pass zacatek inputfloatzacatek konec inputfloatkonec | i little problem try statement along multiple conditions when error nd condition asks st condition what i want repeat condition whole cycle i hope understand since english good also i newbie python i also know describe native language i hope following example help better understand thought true try zacatek floatrawinputzacatek konec floatrawinputkonec except exception pass else break following zacatek konec zacatek i want zacatek konec konec thanks advance help | 3 |
itertoolsgroupby provides easy way collect lines groups import itertools data open datatxt r f keygroup itertoolsgroupbyflambda line linestartswith meta key metanextgroupstrip else lines joingroupstrip dataappendmetalines printdata yields meta data skadjflaskdjfasljdfalskdjflnsdkfjhasdlkgjhsdlkjghlaskdjnasdhfk meta data jflaksdjflaksjdflkjasdlfjasnldaksjflkdsajlkdfj meta data alsdkjflasdjkfglalaskdjf the expression itertoolsgroupbyflambda line linestartswith meta returns iterator it loops lines f calls lambda function line when encounters line begins meta function returns true otherwise false itertoolsgroupby collects contiguous lines return value so line begins meta placed group subsequent lines beginning meta placed next group the key return value lambda function in case either true false | i file mb looks like meta data skadjflaskdjfasljdfalskdjfl sdkfjhasdlkgjhsdlkjghlaskdj asdhfk meta data jflaksdjflaksjdflkjasdlfjas ldaksjflkdsajlkdfj meta data alsdkjflasdjkfglalaskdjf this file contains one row meta data corresponds several variable length data containing alphanumeric characters what best way read data simple list like data meta data skadjflaskdjfasljdfalskdjflsdkfjhasdlkgjhsdlkjghlaskdjasdhfk meta data jflaksdjflaksjdflkjasdlfjasldaksjflkdsajlkdfj meta data alsdkjflasdjkfglalaskdjf my initial idea use read method read whole file memory use regular expressions parse data desired format is better pythonic way all metadata lines start octothorpe data lines alphanumeric thanks | 2 |
i know whether fastest way top head data open inputfile r fp line fp line linestrip line dataappendline else dataappendline data x joiny x y data | i file mb looks like meta data skadjflaskdjfasljdfalskdjfl sdkfjhasdlkgjhsdlkjghlaskdj asdhfk meta data jflaksdjflaksjdflkjasdlfjas ldaksjflkdsajlkdfj meta data alsdkjflasdjkfglalaskdjf this file contains one row meta data corresponds several variable length data containing alphanumeric characters what best way read data simple list like data meta data skadjflaskdjfasljdfalskdjflsdkfjhasdlkgjhsdlkjghlaskdjasdhfk meta data jflaksdjflaksjdflkjasdlfjasldaksjflkdsajlkdfj meta data alsdkjflasdjkfglalaskdjf my initial idea use read method read whole file memory use regular expressions parse data desired format is better pythonic way all metadata lines start octothorpe data lines alphanumeric thanks | 1 |
not clear exactly asking i know mean version but idle meaning open shell looks something like python r jul msc v bit intel win type copyright credits license information you either create new window file new ctrln windows save file you also use editor instead idle emacs notepad vim etc save file if want keep log shell activity executable script also save idle file menu | currently i working python interactive shell version when start python shell use code line know store code so command keyword save session python shell like py | 1 |
it looks like problem regex double quotes without works fine sample string more anotherstring n import researchr smores samplegroups more fwiw great resource developing regex directly sample string httptxtrecom another good resource learn regular expressions httpwwwregularexpressionsinfo | i file following grammar whitespacesequencestringwhitespacesequencemorewhitespacesequencestringsequencenewline using python i would like remove sequence whitespacesequencemorewhitespacesequence grammar i using following regex pattern x recompilesmores matching sequence i need remove | 1 |
you override getformkwargs method createview articlecreateview case pass user form def getformkwargsself kwargs superarticlecreateview selfgetformkwargs kwargs user selfrequestuser return kwargs override form init method def initself args kwargs selfuser kwargspopuser now use selfuser clean method | as part form validation django i want check user last made post i look question stackoverflow appear address issue initially used accepted answer essentially process moment add requestuser object def formvalidself form method createview subclass however allow user variable used form validation since i want access user variable validation check time since last post logically validation i need user variable injected form earlier i tried altering getinitial method def getinitialself initial superarticlecreateview selfgetinitial initial user selfrequestuser return initial this successfully sets user key initial dictionary never makes cleaning process deals stuff data dictionary removes anything initial i deliberately excluded user form display appears also remove cleaning process validation is correct way override init method form getinitial method view putting user initial form pulling extra information initial form init i looking pass requestuser form i access within formwide clean method additional checks amount validation def cleanself superarticleform selfclean check whether user posted recently raise validationerror return selfcleaneddata j | 2 |
if want really good windows support i suspect might need find easier use different api windows check links httppeoplecsailmiteduhubertpyaudio crossplatform httpffmpegorgffmpeghtml crossplatform httpwwwcodeprojectcomkbaudiovideompexampleaspx windowsspecific httpmsdnmicrosoftcomenuslibrarywindowsdesktopddvvsaspx windowsspecific edit probably solution far comments pretty positive another option httpwwwunseencombasshtml beware commercial asked free use noncommercial applications python wrapper called pybass | im coding music player python using pyqt i wanted feature mono playback mp files i accomplished using pygame mixer specific parameter channels i set get mono playback however pygame mp support limited i searching library able handle mp files and mono playback currently i using pyaudiere playback site example processing song playing maybe i could turn song mono i really idea accomplish i like help code feature using pyaudiere library handle mp files edit i would also accept solution c i always build python wrapper using boostpython | 2 |
itertoolspermutations simply works way it takes arbitrary iterable argument always returns iterator yielding tuples it specialcase strings to get list strings always join tuples listmapjoin itertoolspermutations | why itertoolspermutations return list characters digits permutation instead returning string for example printx x itertoolspermutations why return | 3 |
because expects iterable parameter know string the parameter described docs httpdocspythonorglibraryitertoolshtmlitertoolspermutations | why itertoolspermutations return list characters digits permutation instead returning string for example printx x itertoolspermutations why return | 3 |
use selfstatusbarsetstatustext text fieldnumber | how i make statusbar show specific text without hover one menubar items i want make mp player i building able output currently playing file statusbar | 2 |
the strsplit method without argument splits whitespace many fancy word nhello thisplit many fancy word hello hi | i looking python equivalent string str many fancy word nhello thi string whitespaceregex string words strsplitwhitespaceregex many fancy word hello hi | 3 |
import many fancy word nhello thi resplit | i looking python equivalent string str many fancy word nhello thi string whitespaceregex string words strsplitwhitespaceregex many fancy word hello hi | 3 |
first get know json module the native json module work appengine import djangoutilssimplejson json then format json objects python dicts obj name foo age then use jsondumps get str object represents json object jsonobj jsondumpsobj jsonobj string write using conventional methods try interactive interpreter after read page info templates webapp framework i use django i sure webapp uses templating system though looks similar better read if talking jquery ajax post generate xhtmlxmlwhatever server side unless course causing postpost url loaded iframe if answer wanted clarify question bit and unlikely imo anyone would post answer code jsfiddle | i done jquery post successfully however order get data returned server side can anyone gives example done google app engine python using webapp framework if possible i need example how send json data template from template access json jquery post success function i would appreciate much anyone could post httpjsfiddlenet | 2 |
you need pass self instantiating class assignmentself name discription deadline grade studentid assignmentname discription deadline grade studentid the error letting know trying use var self defined either local global scope | im trying learn classes something holding em back get nameerror global name self defined happens class field help find wrong thank code class assignment def initself name discription deadline grade studentid selfname name selfstudentid studentid selfdescription discription selfdeadline deadline selfgrade grade def strself return studentid selfstudentid assignment name selfname description selfdescription deadline selfdeadline grade selfgrade def validationself errors selfstudendid errorsappendno existing student id selfdescription errorsappendno existing description selfdeadline errorsappendno existing deadline selfdeadline errorsappendno existing deadline return errors staticmethod def dummyassignments ret studentid range print sda assignmentself name discription deadline grade studentid retappenda return ret def testassigment assignment print testassigment print assignmentdummyassignments | 2 |
the problem assignmentself name discription deadline grade studentid this staticmethod self defined indeed none values defined come think except studentid | im trying learn classes something holding em back get nameerror global name self defined happens class field help find wrong thank code class assignment def initself name discription deadline grade studentid selfname name selfstudentid studentid selfdescription discription selfdeadline deadline selfgrade grade def strself return studentid selfstudentid assignment name selfname description selfdescription deadline selfdeadline grade selfgrade def validationself errors selfstudendid errorsappendno existing student id selfdescription errorsappendno existing description selfdeadline errorsappendno existing deadline selfdeadline errorsappendno existing deadline return errors staticmethod def dummyassignments ret studentid range print sda assignmentself name discription deadline grade studentid retappenda return ret def testassigment assignment print testassigment print assignmentdummyassignments | 3 |