text_a
stringlengths
5
12.3k
text_b
stringlengths
36
15.7k
Score
int64
1
3
the docs httpwikicythonorgbitcythonextensionsonwindows say for python use microsoft windows sdk windows net framework sp later earlier versions sdk link wrong c runtime note later versions python likely require recent version windows sdk this required make sure extension linked c runtime version python using correct version sdk way control microsoft build tools
i trying compile simple cython extension example page windows bit machine python bit version installed i installed cython windows bit version gohlke page basically answer options i really need python bit version address larger memory also i trying compile using microsoft sdk net i cannot use approach latter solution i tried steps observed green window compilation throws cannot find vcvarsallbat error following sequence commands i tried ccd program filesmicrosoft sdkswindowsv cprogram filesmicrosoft sdkswindowsvset distutilsusesdk cprogram filesmicrosoft sdkswindowsvsetenv x release setting sdk environment relative cprogram filesmicrosoft sdkswindowsv targeting windows x release cprogram filesmicrosoft sdkswindowsve ecd cython ecythonpython setuppy buildext inplace running buildext skipping fibc cython extension uptodate building fib extension error unable find vcvarsallbat any suggestions i solve
3
instead reinventing wheel check dbpedia already extracted wikipedia infoboxes easily parsable database format
i need get content infobox movie i know name movie one way get complete content wikipedia page parse i find infobox get content infobox is way using api parser i using python pywikipediabot api i also familiar wikitools api so instead pywikipedia someone solution related wikitools api please mention well
2
you use modulo division remainder operator lens if want strip string length divisible use slens slens
string string abcdefg wanted check length string divisible lenstring command would use
3
hexordc x formatordc x cencodehex
i interested taking single character c c example hexvalstring chartohexstringc print hexvalstring output what simplest way going any predefined string library stuff
3
everything looks working like even example bytes swapped back if system byte order network noop question states network bytes order big host little swapping in xece in b xeec in out in b out in sockethtonsa out in sockethtonsb out in sockethtonsa b out true in sockethtonsb out true in hexsockethtonsa out xeec in hexsockethtonsb out xece in binsockethtonsa out b in binsockethtonsb out b from python socket reference sockethtonsx convert bit positive integers host network byte order on machines host byte order network byte order noop otherwise performs byte swap operation
i currently looking socket programming python i experiencing strange behavior sockethtons appears flipping bytes every call i implementing simple ping script far i aware network byte order big endian systems byte order little endian if i use htons bit checksum wireshark reports incorrect however i pack checksum struct without using htons wireshark confirms correct this wireshark captured using htons checksum xece incorrect xeec and quick example z xff print z z sockethtonsz print z z sockethtonsz print z any thoughts would greatly appreciated hopefully something wrong edit print sysbyteorder little
1
there post i wrote talks setup mongrel wsgid run wsgi app it httpdaltonmatoswordpresscomdeployingyourdjangoapplicationwithmongrelandwsgid
this attempt discover canonical answer something seems hard google right i writing web app pyramid i luxury deciding server stack look like i heard good things mongrel would like try using serve app however i figure mongrel manual google searches connect mongrel wsgi app do i roll existing solutions problem
2
i think reversed looking records ppnref epdfeae presult ppnref epeb presult ppnref epad presult ppnref epaac presult ppnref epaffc presult ppnref epba presult record reversedrecords record presult print record ppnref break
i dict dicts results print recurring ppnref epdfeae presult recurring ppnref epeb presult recurring ppnref epad presult recurring ppnref epaac presult recurring ppnref epaffc presult recurring ppnref epba presult im interested value presult i easily grabb last entry listresultspresult i looking go loop list backwards i land entry presult in example second line ppnref epeb how i accomplish if i could iterate negative index i think i could figure rest im sure assuming recurring payments successful payment im trying grab recent successful transaction
2
you sense already written descrambler all feed scrambler inverse permutation below inverse permutation given argsortp p permutation def scrambles p scramble string s permutation p pn lenp length permutation array e lens pn lenspn array chars padded rangelens segj divmodipn e segpn pj si return joinerstrip def argsortseq httpstackoverflowcomquestions seq indexargsortseq given seq index construct sorted seq sortedseqseqx x index assert sortedseq sortedseq given sorted seq index reconstruct seq assert sortedseqx x argsortindex seq return sortedrangelenseq keyseqgetitem p textabcdefghij print scrambletextp ahgedbifjc printscramblescrambletextpargsortp abcdefghij by way instead preallocating enough space e e lens pn lenspn generate items e order using argsort def scrambles p pn lenp e idx argsortp rangelens segj divmodipn eappendsidxjsegpn return joine
help trying descramble file using permutation keyi know scramble need create function descramble back using permutation key code def stringtoarrays a ilens aappendsi return a def arraytostringa s c a elementvalue c array a s sc return s arraytostring def scrambles p scramble string s permutation p pn lenp length permutation array e lens pn lenspn array chars padded lens seg ipn segment number j pn segment offset e segpn pj si return arraytostringe scramble print scrambleabcdefghij prints ahgedbifjc i want set back string abcdefghij
1
i problem windows i deleted netbeans directory located home folder that fixed problem hope fixes
i went tools plugins then chose install three python items show after installation i choose restart netbeans option but instead restarting netbeans closed and opening any ideas fix i normally develop java netbeans install i using mac osx i see takers let ask is way revert new plugin install
1
while telnet insecure essentially serial console network makes easy code ssh much much complex there encryption authentication negotiation etc and easy get wrong spectacular fashion there nothing wrong telnet per se change things network private network opening trouble assuming running computer restrict server localhost then ssh computer telnet localhost all security minimal hassle
i write python telnet client communicate server telnet however many people tell secure how i convert ssh should i need totally rewrite program
1
i used viewdecorator snippet httpdjangosnippetsorgsnippets wrap normal function decorators
how i implement userpassestestlambda u uissuperuser decorator class based views i used function based views i work around feels unnaturally shouldn covered dispatch method
1
building sven marnach idea use nprot version rotates quadrant clockwise requested in key step block nprotblockcopy copy used righthand side rhs without copy values assigned block underlying data used rhs also changed this muddles values used subsquent assignments without copy multiple values spread block i see way operation without copy import numpy np nparangereshape printa block to rotate counterclockwise block nprotblockcopy printa to rotate clockwise nparangereshape block block nprotblockcopy printa
x matrix list lists python the matrix divided square blocks size x i want way take transpose block i using traditional method going element copying another array back i want see better way transposing matrix python done one line using zip method eg representation matrix blocks block block block block rotate right result block block block block i want find method takes block number rotates block left right is easy way
3
the easiest way create single wsgi app tingpy add handlers urls then delete mapping
i need help appyaml url management i scripts tingpy searchandlerpy toplawfirmspy i created tingpy first i appyaml url script tingpy pages declared tingpy but i think i made mistake searchhandlerpy toplawfirmspy making second level is way appyaml three scripts appyaml would look like url script searchhandlerpy url script toplawfirmspy url script tingpy i declare pages scripts this i application ting version runtime python apiversion handlers url ahmail script incomingpy login admin url stylesheets staticdir stylesheets url faviconico staticfiles staticimagesfaviconico upload staticimagesfaviconico url image script toplawfirmspy url imageupload script toplawfirmspy url imagesave script toplawfirmspy url imageresize script toplawfirmspy url displayimage script toplawfirmspy url histogram script toplawfirmspy url testurlopen script toplawfirmspy url printdb script toplawfirmspy url cropimage script toplawfirmspy url jquerytest script toplawfirmspy url urlopenppp script toplawfirmspy url deleteone script toplawfirmspy url enterppp script toplawfirmspy url saveppp script toplawfirmspy url searchhandler script searchhandlerpy url site script searchhandlerpy url searchall script searchallpy url script tingpy inboundservices mail
1
currently possible use waitforcondition webdriver the python selenium code provide drivenselenium class accessing old selenium methods waitforcondition the selenium wiki info your best bet use webdriverwait class this helper class periodically executes function waiting return true my general usage driver webdriverfirefox driverget httpexamplecom add driverfindelementbyidajaxbutton addclick source driverpagesource def comparesourcedriver try return source driverpagesource except webdriverexception pass webdriverwaitdriver untilcomparesource assertions this solution means ideal the tryexcept necessary situations page requestresponse cycle delayed waiting ajax activity complete if comparesource get called midst requestresponse cycle throw webdriverexception the test coverage webdriverwait also helpful look
i moving tests selenium webdriver my problem i find equivalent seleniumwaitforcondition do python bindings moment still planned
3
select word from table where word not like and word not like b and word not like c
i sqlite query executed inside python code an example would select word from table where word not like this would select words occur word this i get work perfectly the problem i want restrict results include b anywhere word i picturing something like select word from table where word not in b z obviously work kinda idea and adding and clause really option unless way perform so code option select word from table where word not like and not like b if option i work i hoping something else thanks advance help
3
soupfind abbr string work fine there must something wrong date beautifulsoup import beautifulsoup doc abbr classdtstart titletnovember abbr soup beautifulsoupdoc abbr soupfindall abbr print abbrstring result november update based code added question you use text parameter like httpwwwcrummycomsoftwarebeautifulsoupdocumentationhtmlargtext text argument lets search navigablestring objects instead tags either looking text nodes looking tags a text node tag name maybe want joinelstring el rfindall strong
say i used date rfind abbr get abbr classdtstart titletnovember abbr i want print november i try print datestring i get attributeerror nonetype object attribute string what i wrong answer here final working code learning purposes soup beautifulsouppage calendar soupfind table class vcalendar ical dates calendarfindall abbr class dtstart events calendarfindall strong rangelendates print datesistring eventsistring
1
if use sqlite regexp support see answer problem regexp python sqlite easily one clause select word from table where word not regexp abc
i sqlite query executed inside python code an example would select word from table where word not like this would select words occur word this i get work perfectly the problem i want restrict results include b anywhere word i picturing something like select word from table where word not in b z obviously work kinda idea and adding and clause really option unless way perform so code option select word from table where word not like and not like b if option i work i hoping something else thanks advance help
3
i sure avoiding and clause it simplest solution otherwise would need intersect multiple queries select word from table where word not like intersect select word from table where word not like b intersect select word from table where word not like c alternatively use regular expression version sql supports
i sqlite query executed inside python code an example would select word from table where word not like this would select words occur word this i get work perfectly the problem i want restrict results include b anywhere word i picturing something like select word from table where word not in b z obviously work kinda idea and adding and clause really option unless way perform so code option select word from table where word not like and not like b if option i work i hoping something else thanks advance help
1
you explicitly set binding release return key binding keyreleasereturn for example import tkinter tk class sampleapptktk def initself args kwargs tktkinitself args kwargs selftext tktextself selftextpack selftextbindkeyreleasereturn selfonreturnrelease def onreturnreleaseself event selftextinsertend boink name main app sampleapp appmainloop if want anything happen press return key remove default binding create binding returns break
is way make return event call key release instead press if use keyrelease eventchar blank special key return
3
my guess tag template rendering anything mean confirmed actual html csrf token generated either use requestcontext instead dictionary rendertoresponsefoohtml requestcontextrequest or make sure djangocorecontextprocessorscsrf contextprocessors setting httpsdocsdjangoprojectcomendevrefcontribcsrf or add token context manually
beginner django i trying fix long time i djangomiddlewarecsrfcsrfviewmiddleware middleware classes i token post form heres code i wrong djangocontribauthforms import usercreationform djangoshortcuts import rendertoresponse djangohttp import httpresponseredirect chartseyauthenticationforms import registrationform djangotemplate import requestcontext djangocorecontextprocessors import csrf def registerrequest requestmethod post c requestcontextrequestpost form registrationformc formisvalid newuser formsave return httpresponseredirect else form registrationform return rendertoresponseregisterhtml form form here template block content hregisterh form action methodpost csrftoken formasp input typesubmit valuesubmit form endblock
3
numpyndarray defines iter usual mechanism make instances type iterable note numpyndarray c extension type matter question iterable both types define python c extension types made iterable defining iter
numpy ndarray class defined class ndarraybuiltinobjects from i gather builtinobjects iterable type for reason i find behavior surprising arr numpyarray as far as i know split array as far as i know dtype s print maplambda x xarr a f a i k or come attributes list object passed init method ndarray but cannot i use methods like listreverse array object internally stored list side anyone know better way apply stringoperations element ndarray objects
2
ctypes gets job done would simpler reliable use pywin rolling runs risk introducing bugs that said following example uses ctypes access winapi functions code snippet linked question import ctypes ctypes ctypes import wintypes wintypes advapi ctypeswindll advapi uselasterrortrue errorinvalidfunction x errorfilenotfound x errorpathnotfound x erroraccessdenied x errorinsufficientbuffer xa lpbool ctypespointerwintypesbool lpdword ctypespointerwintypesdword psid ctypespointerwintypesbyte psecuritydescriptor ctypespointerwintypesbyte securityinformation wintypesdword ownersecurityinformation x groupsecurityinformation x daclsecurityinformation x saclsecurityinformation x labelsecurityinformation x attributesecurityinformation x scopesecurityinformation x backupsecurityinformation x unprotectedsaclsecurityinformation x unprotecteddaclsecurityinformation x protectedsaclsecurityinformation x protecteddaclsecurityinformation x class sidnameusewintypesdword sidtypes dictenumerate user group domain alias wellknowngroup deletedaccount invalid unknown computer label split def initself valuenone value none value selfsidtypes raise valueerror invalid sid type supersidnameuse selfinitvalue def strself selfvalue selfsidtypes raise valueerror invalid sid type return selfsidtypesselfvalue psidnameuse ctypespointersidnameuse def checkboolresult func args winerrorctypeswinerror getlasterrorctypesgetlasterror result raise winerrorgetlasterror return args msdnmicrosoftcomenuslibraryaa advapigetfilesecuritywerrcheck checkbool advapigetfilesecuritywargtypes wintypeslpcwstr in lpfilename securityinformation in requestedinformationrequested psecuritydescriptor outopt psecuritydescriptor wintypesdword in nlength lpdword out lpnlengthneeded msdnmicrosoftcomenuslibraryaa advapigetsecuritydescriptorownererrcheck checkbool advapigetsecuritydescriptorownerargtypes psecuritydescriptor in psecuritydescriptor ctypespointerpsid out powner lpbool out lpbownerdefaulted msdnmicrosoftcomenuslibraryaa advapilookupaccountsidwerrcheck checkbool advapilookupaccountsidwargtypes wintypeslpcwstr inopt lpsystemname psid in lpsid wintypeslpcwstr outopt lpname lpdword inout cchname wintypeslpcwstr outopt lpreferenceddomainname lpdword inout cchreferenceddomainname psidnameuse out peuse def getfilesecurityfilename request length wintypesdword nb this query may fail errorinvalidfunction filesystems try advapigetfilesecuritywfilename request none ctypesbyreflength except windowserror e ewinerror errorinsufficientbuffer raise lengthvalue return none sd wintypesbyte lengthvalue advapigetfilesecuritywfilename request sd length ctypesbyreflength return sd def getsecuritydescriptorownersd sid psid siddefaulted wintypesbool advapigetsecuritydescriptorownersd ctypesbyrefsid ctypesbyrefsiddefaulted return sid def lookupaccountsidsid size name ctypescreateunicodebuffersize domain ctypescreateunicodebuffersize cchname wintypesdwordsize cchdomain wintypesdwordsize sidtype sidnameuse advapilookupaccountsidwnone sid name ctypesbyrefcchname domain ctypesbyrefcchdomain ctypesbyrefsidtype return namevalue domainvalue sidtype example name main import sys filename sysargv isinstancefilename bytes filename filenamedecodesysstdinencoding request ownersecurityinformation sd getfilesecurityfilename request sid getsecuritydescriptorownersd name domain sidtype lookupaccountsidsid domain name formatdomain name printfile formatfilename printowner formatname sidtype output cgetfilesecuritypy cwindows file cwindows owner nt servicetrustedinstaller wellknowngroup cgetfilesecuritypy cusers file cusers owner nt authoritysystem wellknowngroup cgetfilesecuritypy ctemp file ctemp owner builtinadministrators alias
i writing script needs determine username owner files windows while i found solution using pywin i hesitant use i want add module dependency the script written python run bit plattforms i wondering different method maybe ctypes determine information
3
you want create symlink desired version cd libraryframeworkspythonframeworkversions sudo rm current sudo ln libraryframeworkspythonframeworkversions current this removes current pointer default python version sets version
how i change default python version used mac snow leopard i trying switch v v
1
after stripping right back chatting guy sa irc channel appeared mac osx problem so i set linux thing occured in end i resorted running script crontab works fine m
this script slowly eats ram when i run i see ram usage python creep approx mb loop i figure i figured iteration query adds ram i figure any help would awesome haystackpmod import piliplacement sa model time import sleep datetime import datetime sqlalchemy import createengine sqlalchemyorm import sessionmaker datetimenow engine createengine mssqlxxxxxxxuiduserpwdxxxxx echofalse session sessionmakerbindengine def syncplacementssession query sessionquerypiliplacementfilterpiliplacementtime piliplacements pidplacement p queryall adds ram del piliplacements print loop true session session syncplacementssession sleep
1
try changing line page requestgetget page to page requestgetget page the problem getting parameter exist indexing using would result keyerror get method returns none exist the paginator calling intnone fails the second parameter get method default return key exist rather none i passed int fail
i trying use django pagination module including standard distribution version when attempting load page currently controlled pagination i include page uri throws typeerror i never situation arise see reason occurring here current view paginator paginatormailslist shows mails per page page requestgetget page try mails paginatorpagepage except pagenotaninteger if page integer deliver first page mails paginatorpage except emptypage if page range eg deliver last page results mails paginatorpagepaginatornumpages typeerror int argument must string number nonetype the error presented line code mails paginatorpagepage anyone witnessed error andor know correct
3
judging commentto evan correct answer want skip nls in case try normalizespacetrcontainstddescriptionfollowingsiblingtrtd note if argument normalizespace selects one node function return result processing first selected node all leading trailing whitespace characters deleted all intermediate groups adjacent whitespace characters replaced single space character
i new xpath please bear currently i looking use scrapy scrape content webpages content looks something like td colspan valigntop classregularlandsize sq extensive shoreline mbr br call or email infobr fulllength olympicpoolchildren pooljacuzzibr landscapesdkey bridgesbr tennis courtsbr water features true seafront development iconic design architect daniel libeskindbr lconic residential located less metres shorelinebr br opposite future integrated resort sentosa islandbr a part keppel bay world calss water front precinct luxury homesbr br call email info td specifically i using following hxsselect trcontainstddescriptionfollowingsiblingtrtdtext extract however break resulting item list due content separated br if i exclude text xpath td element included resulting string desirable is way xpath ensure resulting string everything shown without td tags i hope i need manually join back list br
2
you returning fx probably reassigning def funcfx aaa bbb ccc lengthlenfx length pass elif length fx fx elif length fx fx fxfxupper fxfxii rangelenfx translatedx x fx return translate here alternate function figure know python def funcfx aaa bbb ccc return djoinxupper x zipiterfx
i made function dictionary the purpose function separate input string sets if input string value multiple i want delete remainder function working perfectly i added part deleting remainders def funcfx aaa bbb ccc lengthlenfx length return fx length return fx length return fx fxfxupper fxfxii rangelenfx translatedx x fx return translate x aaabbbcc output funcx print output aaabbb function recognizing input sequence multiple deleting values want however splitting new string letter words translated dictionary anymore if delete statements function works strings multiple what i wrong
1
while i agree laurence occasions quick dirty approach gets job done without creating problems here example demonstrates regex based approach import cleanbodyre recompiler rem def replmatch tag matchgroupsplit tag p return sp matchgroup elif tag br ul li b strong em return matchgroup return u def cleanbodyhtml return cleanbodyresubrepl html
i like strip html javascript except bb ulul lili aa thanks
1
use itervalues ditervalues print aha note much slower key lookup potentially require inspecting values dictionary if need perform operation often might want consider storing values set
i want print aha i want read values keys what pythonic way
3
in previous question already demonstrated code retrieves entry given videoid run python gdatayoutubeservice import youtubeservice yt youtubeservice entry ytgetyoutubevideoentryvideoid ppvjgmmhfo entryrating gdatayoutuberating object xcd print entryrating xml version encoding utf nsrating average max min numraters relhttpschemasgooglecomgoverall xmlnsnshttpschemasgooglecomg entryratingaverage entryratingnumraters traceback recent call last file stdin line module attributeerror rating object attribute numraters direntryrating findextensions tostring addmemberstoelementtree becomechildelement convertelementattributetomember convertelementtreetomember harvestelementtree toelementtree class delattr dict doc format getattribute hash init module new reduce reduceex repr setattr sizeof str subclasshook weakref attributes children namespace tag average extensionattributes extensionelements max min numraters text entryratingnumraters
how i call gdrating xml file using python youtube gdata api i youtube videoid variable i know possible return gdrating average max min numraters rel httpschemasgooglecomgoverall i figure python
1
the nature dictionary cannot efficiently test whether value present way test whether key present you need iterate dictionary testing value although done transparently using code mark suggests if large dictionaries performance may issue may require different data structure
i want print aha i want read values keys what pythonic way
2
why scale variables one one in paste import numpy np list b scale lambda x x xmean arr nprecfromrecordslistnames id var var varstoscale var var var varstoscale arrvar scalearrvar print arr end pasted text b
i want apply transformation certain columns record array reassign values what canonical way list b arr nprecfromrecordslistnames id var var and i want apply scaling variables i let example general scaling may complex subtracting means scale lambda x x xmean this work arr var var mean typeerror cannot perform reduce flexible type so i convert unstructured array first reassign back record array do i loop unstr arr var var view float reshapelenarr arr var var scaleunstr indexerror unsupported iterator index
1
it looks like urlpatterns might getting overwritten urlpatterns apiurls adding like work it seems assigning directly urlpatterns may unexpectedly clobbering old assignment
so i started using tastypie plugin django make rest api project i following getting started guide project i got point i supposed put foreign key started giving errors the maior one i simple get reverse apidispatchdetail arguments keyword arguments pk apiname v resourcename typep found the code resourcespy class typeofplaceresourcemodelresource class meta queryset typeofplaceobjectsall resourcename typep allowedmethods get class poiresourcemodelresource typep foreignkeytypeofplaceresource typep class meta queryset pointofinterestobjectsall resourcename pois filtering code all code all and models class typeofplace modelsmodel name modelscharfieldmaxlength blanktrue code modelscharfieldmaxlength uniquetrue def unicodeself return selfname class pointofinterestgeoinformation name modelscharfieldmaxlengthblanktrue code modelscharfieldmaxlengthnulltrue uniquetrue code modelscharfieldmaxlengthnulltrue uniquetrue typep modelsforeignkeytypeofplace def unicodeself return selfname the urlspy api apiapiname v apiregistertypeofplaceresource canonicaltrue apiregisterpoiresource canonicaltrue urlpatterns apiurls so i something wrong or missing something any help would really appreciated d
1
here example based answer linked clarity import numpy np nparangereshape array areshapeashapemeanaxismean array as function def rebina shape sh shapeashapeshapeshapeashapeshape return areshapeshmeanmean
i trying reimplement python idl function httpstarpstqubacukidlrebinhtml downsizes integer factor array averaging for example anparangereshape array i would like resize taking mean relevant samples expected output would b rebina b array ie b npmeana b npmeana i believe i reshape dimensional array take mean correct slice could figure algorithm would hint
3
the way i python fairly simple depends middleman message broker basically i receive message process ack if message acked timeout broker requeues with place simpy kill restart process in case process traps sigint orderly shutdown however dies supervisor notices worker died starts new one continues processing messages queue i inspired erlang supervision tree model everything designed survive death process i even made workers send heartbeat supervisor periodically zeromq pub supervisor sub supervisor kill restart process hangs reason
multiprocessing import process aprocesstargetworker args astart i making multiple workerprocess app laugh yet worker gracefully reload whenever code updated new requests served new worker processes new code this a newly launched thread contains updated code ensure requests dropped i already made worker listens serves requests gets aa request signal kills next signal control signal i zeromq the clients connect server using zeromq the clients interact http what good way reload code can explain scheme simple stupid enough robust what i mind launch thread within main process iterates signal every worker process die launch new worker processes but approach drop i configured way requests death last old worker spawning first new worker and i college student the homework means curiositydriven pursuit
1
unfortunately possible without copying please note gdkpixmap gdkpixbuf deprecated favor cairo
i created instance gtkgdkpixmap painted something for example pixmap gtkgdkpixmapwidgetwindow pixmapdrawrectanglegc true pixmapdrawlinegc how i resize pixmap one way i see copy pixmap pixbuf using gtkgdkpixbufgetfromdrawable resize pixbuf copy pixbuf pixmap is way without copying
1
you could keep histogram dictionary mapping element type int and iterate row column diagonal increment histogramelement either check end see histogram allow copies stop reached element simple onedimensional example a a a a b a h x x h hx else hx print histogram h k h hk print appears times khk output histogram a b a appears times essentially hx store number times element x appears array case current row column diagonal the elements appear consecutively counts would reset time start considering new rowcolumndiagonal
good algorithm checking whether elements row column diagonally given square matrix say x ofcourse naive algorithm iterating every spot point matrix iterate row col diagonal i wondering better way
1
your question how i track answer show us full text error message got without knowing encoding trying use tell anything a traceback snippet code reads file reproduces error would also handy write tiny python script find line file print reprtheline python x print asciitheline python x copypaste result edit question see unambiguously line it look like random gibberish except ampshy tell us whether expect line text human language
i trying track python unicodedecodeerror following log line nov gfrxâ¢xã¬ã„bkxfã—ãã–ã xceããŒyxcâ¿dãŒjx㏠â®atxã¥fxã©pwâ¤xcxã¶xcxâªikcraxâ xã¾pã¢xhxâ­â¢ã¨â´xdzãµwiã‹xcxsã²ãŠâ¨râ¶â²xfã¤lâ¾â¢ã†nwxã·ã¯ i opened entire log file vim yanked line new file i could test one line however parsing script works ok new file throw unicodedecodeerror i understand one file would generate error one would surface identical here i tried running enca determine file encoding complained cannot determine understand language preferences file says files regular file i also deleted every line original log file still got error one file error i tried deleting set encodingutf vimrc writing file i still got error one file the logs nginx logs nginx note release notes change xxf characters escaped xxx accesslog thanks maxim dounin my python script open logfile f error comes i try call jsondumps dict how i track
1
i think couple bugstypos make code work i assume created small code sample show issue i hope fix original code problem solved well instead newingparenting parentingobj newingparent parentingobj i believe solve issue so assign parent instance relationship object key using jf sebastian suggestions could work objects already stored database new instances id assigned yet addingredient two issues typo parameter ingredient renamed ingname viceversa bigger issue addingredient return value fact assign none parent side relationship again given sample code might issues real code
i great time learning python i gotten bit stuck trying incorporate recursive function sqlalchemy essentially function creates instance class put database inside function i get user input whether instance parent class defined using selfreferential adjacency table if function called recursively this function seems work parent class needed whenever recursive element activated crashes my code like engine createengine sqliterecdbdb session sessionmakerbindengine session session base declarativebase class inglistbase tablename inglist id columninteger primarykey true ingredient columnstring nullablefalse parenting columninteger foreignkey inglistid children relationshipinglistbackrefbackref parent remotesideid def initself ingredient selfingredient ingredient def addingredientingredient global newinglist newing inglistingname create new class instance parenting rawinputto add parent ingredient type otherwise press enter parenting parentingobj addingredientparenting recursion newingparenting parentingobj newinglistappendnewing name main newinglist ingredient rawinputenter new ingredient addingredientingredient ing newinglist sessionadding sessioncommit i kept sample simple keep readable i missing important information please let know i assumed problem class instances losing scope i recursed adding global list variable seem fix i also thought fact session acts sort buffer would handle scope problems does something eager loading i saw documentation really understand the error i getting traceback recent call last file cworkspacerecipeslangprocpy line module sessioncommit file cpythonlibsitepackagessqlalchemyormsessionpy line commit selftransactioncommit file cpythonlibsitepackagessqlalchemyormsessionpy line commit selfprepareimpl file cpythonlibsitepackagessqlalchemyormsessionpy line prepareimpl selfsessionflush file cpythonlibsitepackagessqlalchemyormsessionpy line flush selfflushobjects file cpythonlibsitepackagessqlalchemyormsessionpy line flush flushcontextexecute file cpythonlibsitepackagessqlalchemyormunitofworkpy line execute recexecuteself file cpythonlibsitepackagessqlalchemyormunitofworkpy line execute uow file cpythonlibsitepackagessqlalchemyormmapperpy line saveobj executestatement params file cpythonlibsitepackagessqlalchemyenginebasepy line execute params file cpythonlibsitepackagessqlalchemyenginebasepy line executeclauseelement compiledsql distilledparams file cpythonlibsitepackagessqlalchemyenginebasepy line executecontext context file cpythonlibsitepackagessqlalchemyenginebasepy line executecontext context file cpythonlibsitepackagessqlalchemyenginedefaultpy line doexecute cursorexecutestatement parameters sqlalchemyexcinterfaceerror interfaceerror error binding parameter probably unsupported type u update inglist set parenting where inglistid assigndbinglist object xe
2
you check whether k elements matrix integers single pass suppose n size matrix largest element we n column n row diagonal foreach column row diagonal n distinct element now create histogram containing n n element representing rows columns diagonal containing n distinct element size n n histogram zerossize int now tricky part update histogram consider function pseudocode updatehistogrami j element element element element rowindex element columnindex n j element diagonalindex n element histogramrowindex histogramrowindex histogramcolumnindex histogramcolumnindex j histogramdiagonalindex histogramdiagonalindex now iterate throw histogram check whether element k
good algorithm checking whether elements row column diagonally given square matrix say x ofcourse naive algorithm iterating every spot point matrix iterate row col diagonal i wondering better way
1
you try watchdog package turn uses kqueue bsd inotify linux etc
given certainpath freebsd system i would like python use kqueue detect files created deleted anywhere path how would i
1
consider loop name func inspectgetmemberstargetcls inspectismethod def wrapperargs kwargs print start debug support ss targetclsname name when wrapper eventually called looks value name not finding locals looks finds extended scope forloop but forloop ended name refers last value loop ie testmethod so times wrapper called name evaluates testmethod the solution create extended scope name bound right value that done function closure default argument values the default argument values evaluated fixed definitiontime bound variables name def debugtargetcls name func inspectgetmemberstargetcls inspectismethod def closurenamenamefuncfunc def wrapperargs kwargs print start debug support ss targetclsname name result funcargs kwargs return result return wrapper setattrtargetcls name closure return targetcls in comments eryksun suggests even better solution def debugtargetcls def closurenamefunc def wrapperargs kwargs print start debug support ss targetclsname name result funcargs kwargs return result return wrapper name func inspectgetmemberstargetcls inspectismethod setattrtargetcls name closurenamefunc return targetcls now closure parsed each call closurenamefunc creates function scope distinct values name func bound correctly
i wrote class decorator like tried add debug support every method target class import unittest import inspect def debugtargetcls name func inspectgetmemberstargetcls inspectismethod def wrapperargs kwargs print start debug support ss targetclsname name result funcargs kwargs return result setattrtargetcls name wrapper return targetcls debug class mytestclass def testmethodself print testmethod def testmethodself print testmethod class testunittesttestcase def testnameself name func inspectgetmembersmytestclass inspectismethod print name func print testcls mytestclass testclstestmethod testclstestmethod name main import syssysargv testtestname unittestmain run code result finding files done importing test modules done testmethod unbound method mytestclasswrapper testmethod unbound method mytestclasswrapper start debug support mytestclasstestmethod testmethod start debug support mytestclasstestmethod testmethod ran test ok you find testmethod printed twice is problem is understanding right decorator python is workaround btw want add decorator every method class
2
you edit admin classes adminpy you use admininline class help example django website add book author admin page class bookinlineadmintabularinline model book class authoradminadminmodeladmin inlines bookinline adminsiteregisterauthor authoradmin read edit you able add methods useradmin model refer setting listdisplay fields listdisplay yourmethod
i django application users additional data that data collected profile model onetoonefield pointing user this fine works perfectly purposes i trouble customizing admin user in particular i would like able show profile field inside listdisplay i know without writing additional method user i would like able show information related models eg resources owned user inside user detail page again i know without writing custom user method do know solution
1
i agree first example for latter one pep readability counts the semantically important part complex slice expression slice operator divides expression two parts parsed human reader interpreter separately therefore intuition consistency pep sacrificed order highlight operator ie surrounding whitespaces example question omitting whitespaces within two sides expression increases readability spamham eggs vs spamham eggs i find quicker parse
pep mention slice operator from understanding unlike operators surrounded whitespace spam ok spam not ok does hold using complex expressions one considered better style spamhameggs spamham eggs spamham eggs something else
1
i see slicing used pep use startswith endswith instead string slicing check prefixes suffixes startswith endswith cleaner less error prone for example yes foostartswith bar no foo bar i call definitive backs understanding spam ok as far use complex situation i use i think nospacesaroundthe method looks good case spamham eggs looks like time middle bad if want stand sacrifice operator spacing add extra spaces spamham eggs wow easy read i would use i like operator spacing looks much like dictionary key value syntax i also call operator it special syntax constructing slice object could also spamslice
pep mention slice operator from understanding unlike operators surrounded whitespace spam ok spam not ok does hold using complex expressions one considered better style spamhameggs spamham eggs spamham eggs something else
2
as already mentioned pep explicitly mention slice operator format spam definitely common imho readable if pep checker anything go space flagged mehome pep echo spam warnings mehome pep echo spam devfd e whitespace assumes operator defining literal dict space expected operator spam passes reason seem right on count i stick spam nested arithmetic operations little trickier of examples nd one passes pep validation mehome pep echo spamhameggs devfd e missing whitespace around operator mehome pep echo spamham eggs ok mehome pep echo spamham eggs devfd e whitespace however i find difficult parse eye first glance for readability compliance pep i personally go spamham eggs or complication operations sfrom ham sto eggs spamsfromsto
pep mention slice operator from understanding unlike operators surrounded whitespace spam ok spam not ok does hold using complex expressions one considered better style spamhameggs spamham eggs spamham eggs something else
3
use numpyargsort it returns indices one would use sort array import numpy np import numpylinalg linalg a nprandomrandom eigenvalueseigenvectors linalgeiga idx eigenvaluesargsort eigenvalues eigenvaluesidx eigenvectors eigenvectorsidx
i using numpylinalgeig obtain list eigenvalues eigenvectors a somematrixarray numpylinalg import eig eigenvaluesandvectors solution eigenvaluesandvectorsa eigenvalues solution eigenvectors solution i would like sort eigenvalues eg lowest highest way i know associated eigenvector sorting i finding way python functions is simple way i code sort version
3
odds reference sessionid object associated session example caching sessionid given applicationoncreate method session created in case use sessionlookupsession method look session sessionid if construct sessionid first beginstring sendercompid targetcompid session interested sorry i know python i provide example
i use python bindings come quickfix i like set sequence number see how i i found following swig bindings class sessionobject def setnextsendermsgseqnumself args return quickfixsessionsetnextsendermsgseqnumself args it requires two parameters session object int sequence number how i get session object or another method setting sequence number
1
an importerror already python error looks like jython working you need however set path if xxx stands one python modules set syspath contain appropriate directory importing if xxx stands one java modules set java classpath contain appropriate directory jar if xxx stands builtin module probably supported jython yet have look list modules supported jython some newer modules available python platforms json yet available jython
stated one invoke jython source code unix platforms i installed jython put directory path windows how could i set invoke jython py code automatically thanks make example specific clear usrbinenv jython import sys syspathappendpackagejar import orgabcname importerror no module named orgabcname and i run jython barpy cmd work but running python barpy fails error
1
take look homebrew recipe vim macvim modify necessary httpsgithubcommxclhomebrew
i start vim src directory pwd vimsrc configure prefixhomeapplicationsvimcompiled enablerubyinterpyes enablepythoninterpyes withpythonconfigdirlibraryframeworkspythonframeworkversionslibpythonconfig make at end make i get following error ld warning libraryframeworkspythonframeworkpython missing required architecture x file undefined symbols long list undefined symbols long list undefined symbols ld symbols found collect ld returned exit status make vim error what causing error i found answers similar questions advise using macports homebrew macvim i want use is way around update this output listing undefined symbols httppastebincomggvref
1
use gdkpixbuf get icon data assign cluttertexture c version cluttertexturesetfromrgbdata texture gdkpixbufgetpixels pixbuf gdkpixbufgethasalpha pixbuf gdkpixbufgetwidth pixbuf gdkpixbufgetheight pixbuf gdkpixbufgetrowstride pixbuf gdkpixbufgethasalpha pixbuf cluttertexturenone error i pretty sure achieve python well
i attempting get window icon name python use pyclutterbased taskbar i gotten xid via wnck wnck seems capable giving gtkgdkpixbuf useful clutter i sure way pythonxlib pythonxcb i find any ideas
1
i used predicate make sure classes come module question def predc return inspectisclassc cmodule predmodule fetch members module name matching pred classes inspectgetmemberssysmodulesname pred i want type current module name
i already seen following question quite get i want python get list classes within current module in particular i want classes imported eg i following module mynamespace import mybaseclass somewhereelse import someotherclass class newclassmybaseclass pass class anotherclassmybaseclass pass class yetanotherclassmybaseclass pass if i use clsmembers inspectgetmemberssysmodulesname inspectisclass like accepted answer linked question suggests would return mybaseclass someotherclass addition defined module how i get newclass anotherclass yetanotherclass
3
they must strings since joini would returned typeerror int but general find type variable use type printtypei
i need know variable python stringname number i want check degree graphs however i need know iterator number inside string name inside string showing degree graphs end is something wrong code import csv sys import networkx nx def ministrolei stf csvreaderopen resultsetcsv rb delimiter quotechar eds iii stf g nxdigraphnome ministrolei gaddweightededgesfromeds gdegree isinstanceistr print this name elif isinstancei int print this number else raise valueerror return g eds ministrolei here lies examples outs min octavio gallotti min sydney sanches min joaquim barbosa please help thanks
1
i hope helps hello types type str types str true n typen type int typen int true
i need know variable python stringname number i want check degree graphs however i need know iterator number inside string name inside string showing degree graphs end is something wrong code import csv sys import networkx nx def ministrolei stf csvreaderopen resultsetcsv rb delimiter quotechar eds iii stf g nxdigraphnome ministrolei gaddweightededgesfromeds gdegree isinstanceistr print this name elif isinstancei int print this number else raise valueerror return g eds ministrolei here lies examples outs min octavio gallotti min sydney sanches min joaquim barbosa please help thanks
1
have tried upgrading osx bitbit version python i sure specific bit version might causing problems
i start vim src directory pwd vimsrc configure prefixhomeapplicationsvimcompiled enablerubyinterpyes enablepythoninterpyes withpythonconfigdirlibraryframeworkspythonframeworkversionslibpythonconfig make at end make i get following error ld warning libraryframeworkspythonframeworkpython missing required architecture x file undefined symbols long list undefined symbols long list undefined symbols ld symbols found collect ld returned exit status make vim error what causing error i found answers similar questions advise using macports homebrew macvim i want use is way around update this output listing undefined symbols httppastebincomggvref
1
check new project alembic httpreadthedocsorgdocsalembicenlatestindexhtml
i looked sqlalchemymigrate seems like lot work i able find useful examples anyone care share handle
3
you convert path polygon shown example httpphrogznetsvgconvertpathtopolygonxhtml the simpler algorithm page javascript function polygonsampledfrompathpathsamples var doc pathownerdocument var poly doccreateelementns httpwwwworgsvg polygon var points var len pathgettotallength var step steplensamples var iilenistep var p pathgetpointatlengthi pointspush px py polysetattribute points pointsjoin return poly instead sampling based certain number points may wish simply sample particular distance this assumes python binding access full svgpathelement dom interface
i trying figure point svg path using python the algorithm i use raycasting algorithm but algorithm need polygon sides i pathdata svg path path dm c … z corresponds image so way get sides path
1
if submitting page python backend check mechanize
how i fill submit form remotely httpmtanyccusthelpcomcgibinmtanyccfgphpenduseraskphp the form asks email pull menu fields subject question clicking next button takes new page page click submit can i fill form submit one click site i form site user fill email i prepopulated fields subject question user click submit button remote form filled submitted how i python javascript
1
use haproxy nginx proxy multiple tornado processes restart one one the tornado docs cover nginx support websockets using need haproxy
i recently started experiment python tornado web serverframework web development previously i used php framework lamp stack with php deploying updated codenew code easy uploading server way modphp apache interact when i add new code update code pythontornado i need restart tornado server i could see problematic number active users do i restart server anotherbetter way b if i avoid users disconnectedgetting errorsetc restarting could take seconds one possible thought use page flipping paradigm nginx pointing server launch new server instance updated code redirect nginx take original server
1
try twill httptwillidyllorgpythonapihtml i wrapper mechanize
how i fill submit form remotely httpmtanyccusthelpcomcgibinmtanyccfgphpenduseraskphp the form asks email pull menu fields subject question clicking next button takes new page page click submit can i fill form submit one click site i form site user fill email i prepopulated fields subject question user click submit button remote form filled submitted how i python javascript
1
add widgets central widget first then select central widget use layout grid layout vertically etc buttons toolbar add main layout the layouts widget box sidebar used adding child layouts main layout
i started new clear main window project there objects mainwindow centralwidget menubar statusbar i need set default layout inside window probably centralwidget but i didnt found way i get layoutwidget particular size centralwidget but i want set layout whole centralwidget
1
right click anywhere within centralwidget go lay out sub menu select layout want this applied automatically contents centralwidget in order see works place inside push buttons try changing layouts
i started new clear main window project there objects mainwindow centralwidget menubar statusbar i need set default layout inside window probably centralwidget but i didnt found way i get layoutwidget particular size centralwidget but i want set layout whole centralwidget
1
this uac if run elevated see behaviour expect but standard token uac user administrator rights even admin group for special administrator user account uac apply processes special user always given privileged token so difference see os user log special administrator account windows see behaves server box
i trying use ctypeswindllshellisuseradmin determine running process started user admins group i getting inconsistent incorrect results on windows professional install logging user administrator memebr administrators group i get ctypeswindllshellisuseranadmin but user admins group i get expected answer windows server machine logging administrator ctypeswindllshellisuseranadmin does anybody know hints i getting returned win box even though user administartors group i wondering issue caused interaction local vs domain admins groups knowledge sketchy best thanks matt
3
i would start ability change filehandle init as replace mock fake object write signature test written maybe creating method sets filehandle overwriting method test
i logger class needs write strings file so i method like def writetofileself string selffilehandlewritestring note error handling edited clearly i want test without writing file thus mocks via mock i seen explains mock open help i open filehandle init now i setup mockopen seems go scope setup thus use test case how would write test method test writetofile method using mock
1
it turns winguigetforegroundwindow returns window handle process id winprocessgetwindowthreadprocessidhwnd used get thread id process id handle import wincomclient import wingui import winprocess hwnd winguigetforegroundwindow pid winprocessgetwindowthreadprocessidhwnd shell wincomclientdispatchwscriptshell shellappactivate console shellsendkeys upenter shellappactivatepid
i tried following focus returned program focus script run import wincomclient import wingui current winguigetforegroundwindow shell wincomclientdispatchwscriptshell shellappactivate console shellsendkeys upenter shellappactivatestrcurrent
1
you omitted actual exception stack trace i guessing attributeerror local object attribute currentsession if likely skipped middleware configuration step create appengineconfigpy per instructions restart dev server resolve error
i new python well gae i trying include gaesessions application exactly i i copied gaesessions folder src folder folder includes initpy file added working code gaesessions import getcurrentsession session getcurrentsession i received following error traceback recent call last file cprogram filesgooglegoogleappenginegoogleappengineruntimewsgipy line handle result handlerselfenviron selfstartresponse file cprogram filesgooglegoogleappenginelibwebappwebapppy line call response selfinternalerrore file cprogram filesgooglegoogleappenginelibwebappwebapppy line call rv selfhandleexceptionrequest response e file cprogram filesgooglegoogleappenginelibwebappwebapppy line call rv selfrouterdispatchrequest response file cprogram filesgooglegoogleappenginelibwebappwebapppy line defaultdispatcher return routehandleradapterrequest response file cprogram filesgooglegoogleappenginelibwebappwebapppy line call return handlerdispatch file cprogram filesgooglegoogleappenginelibwebappwebapppy line dispatch return selfhandleexceptione selfappdebug file cprogram filesgooglegoogleappenginelibwebappwebapppy line dispatch return methodargs kwargs file dsrchelloworldpy line get session getcurrentsession file dsrcgaesessionsinitpy line getcurrentsession return tlscurrentsession file cpythonlibthreadinglocalpy line getattribute return objectgetattributeself name
3
i going delnan answer i find another problem specific solution i going use case thought would worth passing along instead adding additional information function call rather easy use event passed get information caller ie x range name jbuttonstrx nameactionperformed selffoo def fooself event sender eventgetsource print sendergettext
i creating couple swing jbuttons buttons loop jython on press button call function one different parameter i trouble passing parameters outside self event this works x range name jbuttonstrx nameactionperformed selffoo def fooself event print i work somehow event magically passed method this x range name jbuttonstrx nameactionperformed selffoox def fooself event number print i work print strnumber the issue i see i i add argument i longer pass event i end error telling foo takes exactly arguments given i get i extract event button
1
cgifieldstorage returns dictionary containing parameters request
so i trying use cgi module comes python python server page i want know way pull name checkbox submitted i actually need know status whether submit new page name script going run ie first page i input typecheckbox nameavd i submit form form formchangedatepspavdon all i care pull avd anyway
1
you triggering cleaning validation form made calling isvalid method note parentheses cleaned data correction requestmethod post form testformrequestpost formisvalid print form valid print formcleaneddata
i trying generate form using django documentation i continously getting error testform object attribute cleaneddata even though formisvalid true prints form valid line code following relevant portions code urlspy urlr test viewstest formspy django import forms class testformformsform name formscharfield viewspy def testrequest requestmethod post form testformrequestpost formisvalid print form valid print formcleaneddata else print form valid else form testform return rendertoresponse usertesthtml form formcontextinstancerequestcontextrequest testhtml form action methodpost csrftoken table formastable table input typesubmit valuesubmit form
3
since celery information related currently executed task saved taskrequest called â«the contextâ» so get task id context keyword arguments deprecated task def dojobpath cachesetdojobrequestid operationresults the list available fields documented httpceleryreadthedocsorgenlatestuserguidetaskshtmlhighlightrequestcontextcontext
how i get taskid value task within task here code celerydecorators import task djangocorecache import cache task def dojobpath performs operation file code perform operation cachesetcurrenttaskid operationresults the idea i create new instance task i retrieve taskid task object i use task id determine whether task completed i want keep track task path value file cleaned task completes may may exist in example would i get value currenttaskid
3
there similar reports race condition issues chrome devappserverpy the usual story chrome opens multiple concurrent connections server sends request second connection first because devappserver singlethreaded first request blocks server hangs someone gives supposedly starting chrome disablepreconnect prevents condition
running django nonrel google app engine python i getting exception trying load first time localhost localhostadmin i expect happen page though exception happened processing request traceback recent call last file usrlibpythonsocketserverpy line handlerequestnoblock selfprocessrequestrequest clientaddress file usrlibpythonsocketserverpy line processrequest selffinishrequestrequest clientaddress file usrlibpythonsocketserverpy line finishrequest selfrequesthandlerclassrequest clientaddress self file usrlocalgoogleappenginegoogleappenginetoolsdevappserverpy line init basehttpserverbasehttprequesthandlerinitself args kwargs file usrlibpythonsocketserverpy line init selffinish file usrlibpythonsocketserverpy line finish selfwfileflush file usrlibpythonsocketpy line flush selfsocksendallviewwriteoffsetwriteoffsetbuffersize error errno broken pipe strangely enough appears using google chrome when using firefox print exception least i able replicate problem firefox many tries does anyone know something problem thanks
3
simple really mock import patch def setupself mockfilehandle mock patch builtinopen mockfilehandle selfsut logger def testwriteself selfsutwritemessagetofileook selfasserttrueselfsutfilehandlewritecalled selfasserttrueselfsutfilehandleflushcalled if anyone better solution please let know
i logger class needs write strings file so i method like def writetofileself string selffilehandlewritestring note error handling edited clearly i want test without writing file thus mocks via mock i seen explains mock open help i open filehandle init now i setup mockopen seems go scope setup thus use test case how would write test method test writetofile method using mock
1
for gb file second approach clearly way go here outline need open input file open first output file read one line input file write output file maintain count many lines written current output file soon reaches close output file open next one repeat steps reached end input file close files
i trouble trying split large files say around gb the basic idea simply read lines group every say lines one file but two ways reading files the first one read whole file make list but require loading whole file memory painful large file i think i asked questions in python approaches read whole file i tried include inputfreadlines input commandsgetoutput zcat filesplitlinestrue input subprocesspopencatfile stdoutsubprocesspipebufsize well i easily group lines one file list list or advantage using list easily point specific lines the second way read line line process line reading those read lines saved memory examples include fgzipopenfile line f blablabla line fileinputfileinputfilename i sure gzipopen f not list file object and seems process line line i execute split job how i point specific lines file object thanks
1
fout openoutputtxtwb line fileinputfileinputfilename foutwriteline foutclose fout openoutputdtxtiwb foutclose
i trouble trying split large files say around gb the basic idea simply read lines group every say lines one file but two ways reading files the first one read whole file make list but require loading whole file memory painful large file i think i asked questions in python approaches read whole file i tried include inputfreadlines input commandsgetoutput zcat filesplitlinestrue input subprocesspopencatfile stdoutsubprocesspipebufsize well i easily group lines one file list list or advantage using list easily point specific lines the second way read line line process line reading those read lines saved memory examples include fgzipopenfile line f blablabla line fileinputfileinputfilename i sure gzipopen f not list file object and seems process line line i execute split job how i point specific lines file object thanks
3
chunksize fout none line enumeratefileinputfileinputfilename chunksize fout foutclose fout open outputdtxt ichunksize w foutwriteline foutclose
i trouble trying split large files say around gb the basic idea simply read lines group every say lines one file but two ways reading files the first one read whole file make list but require loading whole file memory painful large file i think i asked questions in python approaches read whole file i tried include inputfreadlines input commandsgetoutput zcat filesplitlinestrue input subprocesspopencatfile stdoutsubprocesspipebufsize well i easily group lines one file list list or advantage using list easily point specific lines the second way read line line process line reading those read lines saved memory examples include fgzipopenfile line f blablabla line fileinputfileinputfilename i sure gzipopen f not list file object and seems process line line i execute split job how i point specific lines file object thanks
1
if nothing special specific number file lines file readlines function also accepts size hint parameter behaves like if given optional parameter sizehint reads many bytes file enough complete line returns lines this often used allow efficient reading large file lines without load entire file memory only complete lines returned could write code something like assume average line chars long want k file sizehint filenumber openinputfiletxt rt f true buf freadlinessizehint buf read entire file done break outfile openoutfiledtxt filenumber wt outfilewritebuf outfileclose filenumber
i trouble trying split large files say around gb the basic idea simply read lines group every say lines one file but two ways reading files the first one read whole file make list but require loading whole file memory painful large file i think i asked questions in python approaches read whole file i tried include inputfreadlines input commandsgetoutput zcat filesplitlinestrue input subprocesspopencatfile stdoutsubprocesspipebufsize well i easily group lines one file list list or advantage using list easily point specific lines the second way read line line process line reading those read lines saved memory examples include fgzipopenfile line f blablabla line fileinputfileinputfilename i sure gzipopen f not list file object and seems process line line i execute split job how i point specific lines file object thanks
2
you translate indices back using idx w npwherea idx arrayidxtw array
i following x x numpy array called comments make sense read rest question array irrelevant position rather line i irrelevant cross irrelevant position rather i first line irrelevant position rather furthermore i list indexes refers central cross said matrix called idx array array edit i call cross marks central column row following array what i would like obtain indexes arrays located idx whose first value i struggling understanding use numpywhere right way since idx array i tried npwherea idx array see returns index sliced array i would like get array array equal thank advance help ps in comments i suggested try give broader scenario applicability although i using i suppose could used process images many d libraries source layer destination layer mask see example cairo in case mask would idx array one might imagine working r channel rgb colors
3
update see larsman answer question numpy recently added numpychar module basic string operations short answer numpy provide vectorized string operations the idiomatic way something like arr numpy array print joinitemupper item arr strings long answer numpy provide vectorized string operations good bit rambling one size fit comes data structures your question probably seems odd people coming nondomainspecific programming language makes lot sense people coming domainspecific language python gives wide variety choices data structures some data structures better tasks others first numpy array default holdall container python python builtin containers good designed often list dict want numpy ndarray homogenous data in nutshell numpy vectorized string operations ndarray specialized container focusing storing ndimensional homogenous groups items minimum amount memory possible the emphasis really minimizing memory usage i biased mostly i need useful way think vectorized mathematical operations nice side effect things stored contiguous block memory strings usually different lengths eg dog cat horse numpy takes databaselike approach requiring define length strings simple fact strings expected fixed length lot implications most useful string operations return variable length strings eg join example those eg upper etc mimic operations want eg upper roughly xviewnpuint view s i recommend as basic example a b yields ab ab length a b numpy deals things eg npuint npfloat strings much flexible length numbers upcasting downcasting rules numbers pretty simple another reason numpy focus numerical operations a particular definition python you certainly make string class string arrays second class citizens numpy they exist operations defined python already really good handling string processing the really main reason numpy try offer string operations python already really good lists fantastic flexible containers python huge set nice fast string operations list comprehensions generator expressions fairly fast suffer overhead trying guess type size returned item care they store pointer also iterating numpy arrays python slower iterating list tuple python string operations really best using normal listgenerator expressions eg print joinitemupper item arr strings example better yet use numpy arrays store strings first place it makes sense single column structured array strings python gives rich flexible data structures numpy arrays beall endall specialized case generalized case also keep mind want numpy array learn python numpy i trying cheeky working numpy arrays similar lot things matlab r idl etc it familiar paradigm anyone first instinct try apply paradigm rest language python lot numpy it multiparadigm language easy stick paradigms already used try learn think python well thinking numpy numpy provides specific paradigm python lot paradigms better fit tasks others part becoming familiar strengths weaknesses different data containers lists vs dicts vs tuples etc well different programming paradigms eg objectoriented vs functional vs procedural etc all python several different types specialized data structures this makes somewhat different domainspecific languages like r matlab types data structures focus everything one specific structure my experience r limited i may wrong impression anyway it certainly true matlab anyway at rate i trying rant took quite awhile stop writing fortran matlab took even longer stop writing matlab python this rambling answer sort concrete examples hopefully makes least little bit sense helps somewhat
are better ways apply string operations ndarray rather iterating i would like use vectorized operation i think using map example shown list comprehensions arr numpyrecfromrecordsziprange far know split names name strings print joinmaplambda x xupper arr strings afaik for instance r language string operations also vectorized string unliststrsplitas far know far know pastesprintfstouppersubstrstringcollapse afaik
3
just fyi i whipped ioloop based smtp client while i say production tested near future httpsgistgithubcom
i looking python async smtp client connect torando ioloop i found simple implmementation httptornadogistsorg blocking solution might bring performance issues does anyone encountered non blocking smtp client tornado some code snippet would also useful
2
try approach problem python side python great glue language i would suggest python run matlab c programs python numpy pylab matplotlib ipython thus combination good alternative almost existing matlab module
i trying embed python matlab i wanted embed mex file written c this worked fine small simple examples using scalars however numpy imported anyway matlab crashes i say anyway i tried number ways load numpy libraries including in python module py numpy import with pyrunsimplestring mex file pyrunsimplestring“from numpy import ” calling numpy functions pyobjectcallobject pout pyobjectcallobjectpfunc pargs originally i thought may problem embedding numpy c however numpy works fine embedded simple c files compiled command line md multithread switch visual studios c compiler next i thought i change make file matlab include md switch no luck mexoptsbat compiles md switch i also manually commented lines numpy init module find crashing matlab it seems loading file extension pyd crashes matlab the first files loaded numpy multiarraypyd the matlab documentation describes debug mex files visual studios i placed error message at point i know problem memory problem pyd’s conflict matlab interestingly i use system command matlab kick process python uses numpy error generated i paste error message matlab followed debug output visual studios processes crash matlab however i pasting whole thing list firstchance exceptions long are suggestions solving integration problem matlab error matlab encountered internal problem needs close matlab crash filecuserspmlappdatalocaltempmatlabcrashdump segmentation violation detected tue oct configuration crash decoding disabled default encoding windows matlab license matlab root cprogram filesmatlabra matlab version ra operating system microsoft windows processor id x family model stepping genuineintel virtual machine java b sun microsystems inc java hotspottm client vm mixed mode window system version build fault count abnormal termination segmentation violation register state fault eax ebx cc ecx edx aeda esp afc ebp af esi cc edi aeda eip bd efl cs b ds ss es fs b gs stack trace fault xbd cpythonlibsitepackagesnumpycoremultiarraypyd xbfead cpythonlibsitepackagesnumpycoremultiarraypyd xc cpythonlibsitepackagesnumpycoremultiarraypyd xb cpythonpythondll pyevalevalframeex xadf cpythonpythondll pyevalevalcodeex this error detected mexfile running if mexfile official mathworks function please examine source code errors please consult external interfaces guide information debugging mexfiles if problem reproducible please submit service request via httpwwwmathworkscomsupportcontactus a technical support engineer might contact information thank help output visual studios debugger firstchance exception xcc matlabexe xc access violation reading location x firstchance exception xcc matlabexe xc access violation reading location x firstchance exception xcc matlabexe xc access violation reading location x firstchance exception xd matlabexe microsoft c exception jitcgfailedexception memory location xce firstchance exception xd matlabexe microsoft c exception jitcgfailedexception memory location xce firstchance exception xbd matlabexe xc access violation writing location x throwsegvlongjmpsehfilter throwsegvlongjmpsehfilter invoking throwsegvlongjmp seh filter mnunhandledwindowsexceptionfilter matlabexe triggered breakpoint
3
well finally got but millions thanks answer joe kington highly inspired teached whole stuff script import numpy np def main generate data nplinspace nppi x npsint condition npwherex onarrayoffarray onofftimescondition print condition condition print ontimes onarray print offtimes offarray def onofftimescondition changingnpdiffcondition complete array tunring turning idx changingnonzero indices changepoints timesnpdiffidx times changes timesnprtimes the first time calculated set ontimesnpwherechangingidxtimesfalse when turning was ontime timesarray false instead offtimes offtimesnpwherechangingidxtimesfalse when turning was offtime onarraynprchangingcopy copy array values add empty array right size offarraynprchangingcopy npputonarrayidxontimes put times changepoints npputoffarrayidxofftimes return onarrayoffarray main yields condition ontimes offtimes things mention yes code gives another output i requested question sorry beeing unprecise output function gives finally need now get zeros outputs masked easy if anybody nicer way put data new array please edit how link user joe or thank
statussignal measured heatpump numpymaarray together timestamps what want lengths periods length periods not daily running time something would easy what exemplary fact minutevalues months time value and want output runningtimewas time value minutes offtimewas time value minutes exact timestamps matter much i already asked people know know python idea neither tried search internet know search so maybe someone could least give hint words could type google ps wow stackoverflow fantastic i already amazed usability passive user asking interface even better
2
at shell prompt terminal run sudo aptget install buildessential this fetch common packages need build anything eg compiler etc then run sudo aptget builddep python fetch libraries need build python then download source code python decompress directory go run configure prefixpathwhereyouwantpythoninstalled make make install get built installed if hit snags way ask back i try offer guidance
ubuntu comes python preinstalled i also downloaded python dev packages because another issue i explained extreme depth how i replaceupdate version expat library used apache graham dumpleton told distro explicitly built python way use external pyexpat implementation causing issue he also said i could build python source code resolve issue how would i ubuntu keep mind i new linux
3
insert into values where valid sql you add where clause insert statement i guessing want update checkupdate column row currently data table opposed inserting new row if case try update data set checkupdate where machinename instead
trying run mysql script via python keeps giving errors here mysql cexecuteinsert datacheckupdate valuess where machinename date machine what i wrong programmingerror you error sql syntax check manual corresponds mysql server version right syntax use near where machinename tld nvalues line
2
this known phenomenon python code dynamic interpreted java code statically typed compiled no surprises the reasons people give preferring python often smaller code base less redundancy dry cleaner code however use library written c python performance may much better compare pickle cpickle
we making knn svd implementations python others picked java our execution times different i used cprofile see i make mistakes everything quite fine actually yes i use numpy also but i would like ask simple question total range xrange slower according j range test memoryfriendly total j print total this snippet takes computer java version code takes second less computer type checking main problem code i suppose but i make lots operation like project i think big number i think i making mistakes i know python used lots scientific projects but code slow i handle problems bigger should i use jit compiler psyco edit i also say loop problem example the code simple like it may tough put practice improvementscode samples another question i implement lots data mining amp machine learning algorithms numpy scipy i use correctly
2
the memory string entirely database dependent as explained documentation sqlite you use memory open database connection database resides ram instead disk as far python language concerned memory string like
i learning python i must say i loved but new learners i problems well could guys tell whether feature python library i checking connect sqllite database i came article code sample pysqlite import dbapi sqlite connection sqliteconnect testdb memoryconnection sqliteconnect memory cursor connectioncursor when wrote memory string put two colon well i wondering whether peculiar library instead python
3
it peculiar sqlite connection string nothing python
i learning python i must say i loved but new learners i problems well could guys tell whether feature python library i checking connect sqllite database i came article code sample pysqlite import dbapi sqlite connection sqliteconnect testdb memoryconnection sqliteconnect memory cursor connectioncursor when wrote memory string put two colon well i wondering whether peculiar library instead python
1
httpnullegecomcodessearchpysqlitedbapiconnect you use memory open database connection database resides ram instead disk colon special python
i learning python i must say i loved but new learners i problems well could guys tell whether feature python library i checking connect sqllite database i came article code sample pysqlite import dbapi sqlite connection sqliteconnect testdb memoryconnection sqliteconnect memory cursor connectioncursor when wrote memory string put two colon well i wondering whether peculiar library instead python
1
because mention scientific code look numpy what probably already done rather uses lapack things like svd when hear python used scientific code people probably referring using way example as quick example if using python example would use float division my example assumes using pythonx therefore integer division if specify nparange dtypenpfloat etc import numpy np nparange j nparange print npdivideouterijsum to give idea timing i use floating point division instead integer division example import numpy np def fnum total rangenum j range num total floati j return total def fnum nparangenum dtypenpfloat j nparange num dtypenpfloat return npdivideouteri jsum def fnum less memoryhungry faster version f total j nparange num dtypenpfloat xrangenum total jsum return total if compare timings in timeit f loops best per loop in timeit f loops best per loop in timeit f loops best ms per loop
we making knn svd implementations python others picked java our execution times different i used cprofile see i make mistakes everything quite fine actually yes i use numpy also but i would like ask simple question total range xrange slower according j range test memoryfriendly total j print total this snippet takes computer java version code takes second less computer type checking main problem code i suppose but i make lots operation like project i think big number i think i making mistakes i know python used lots scientific projects but code slow i handle problems bigger should i use jit compiler psyco edit i also say loop problem example the code simple like it may tough put practice improvementscode samples another question i implement lots data mining amp machine learning algorithms numpy scipy i use correctly
3
words mama papa sister brother pairs listitertoolsproductwords repeat print pairs prints mama mama mama papa mama sister mama brother papa mama papa papa papa sister papa brother sister mama sister papa sister sister sister brother brother mama brother papa brother sister brother brother
i want create list word pairs separated tabs word list i think one option could create matrix range want words combined i need list word pairs make analyses from word list mama papa sister brother output mama papa sister brother mama sister papa sister brother mama someone knows would best way
3
first really odd way invoke instance method normally would memcacheclientaddsearchindex json or simply memcacheaddsearchindex json since add overwrite key already exists cache calling repeatedly impact behavior application whether calls increase cache size really concern memcache designed make memory available needed application based least use algorithm junk memory inert add calls certainly evicted first
im using memcache store json working but problem cache size grow i call line many times memcacheclientaddmemcacheclientsearchindexjson so i looked memcache viewer content still since im using key already cache but even though size cache continues increase
3
you find list comprehensions generator expressions significantly faster for example total sumi j j xrange xrange this executes seconds machine vs original code still order magnitude slower java line expect your original code way sped slightly initializing total rather use integer rather floatingpoint addition your divisions integer results point summing results float on machine psyco actually slows generator expressions speed original loop accelerate
we making knn svd implementations python others picked java our execution times different i used cprofile see i make mistakes everything quite fine actually yes i use numpy also but i would like ask simple question total range xrange slower according j range test memoryfriendly total j print total this snippet takes computer java version code takes second less computer type checking main problem code i suppose but i make lots operation like project i think big number i think i making mistakes i know python used lots scientific projects but code slow i handle problems bigger should i use jit compiler psyco edit i also say loop problem example the code simple like it may tough put practice improvementscode samples another question i implement lots data mining amp machine learning algorithms numpy scipy i use correctly
2
i think i making mistakes i know python used lots scientific projects they heavily using scipy numpy prominent component i heard ecosystem developed around numpy api even important vastly speeds kinds operations projects need there wrong you writing critical code c python great developing general wellplaced extension modules vital optimization right least crunching numbers python really crappy language implement tight inner loops the default time popular widelysupported implementation simple bytecode interpreter even simplest operations like integer division take hundreds cpu cycles multiple memory accesses type checks popular example several c function calls etc instead even single case integer division instruction moreover language designed many abstractions add overhead your loop allocates objects heap use xrange far use range integer minus around small integers cached also xrange version calls method iteration advance range version would iteration sequences optimized specifically it still takes whole bytecode dispatch though vastly complex compared integer division course it would interesting see jit i recommend pypy psyco latter actively developed anymore limited scope anyway might work well simple example though after tiny fraction iterations produce nighoptimal machine code loop augmented guards simple integer comparisions jumping fail maintain correctness case got string list java thing sooner trace first fewer guards least use int that much faster
we making knn svd implementations python others picked java our execution times different i used cprofile see i make mistakes everything quite fine actually yes i use numpy also but i would like ask simple question total range xrange slower according j range test memoryfriendly total j print total this snippet takes computer java version code takes second less computer type checking main problem code i suppose but i make lots operation like project i think big number i think i making mistakes i know python used lots scientific projects but code slow i handle problems bigger should i use jit compiler psyco edit i also say loop problem example the code simple like it may tough put practice improvementscode samples another question i implement lots data mining amp machine learning algorithms numpy scipy i use correctly
3
here working solution problem lines def replicatelines n width reducemax maplen lines return joinlineljustwidth n line lines line replicatelines print line edit added spacing management edit used generator expression peer pressure
i problen i try print result function several times lets say example several commands result dreawing i want duplicate according function used loop print vertical way like i want horizontal like help
2
if checking link correct use head request
i want program try open page get data time interval time expires connection close i using urllib try accomplish task urlhttpexamplecom responseurlliburlopenurltimeoutt htmlresponseread this seems work url exists however put nonexistent url takes long error stop program and i put program used web site user would need wait error message long is way stop execution urlopen command takes longer set time
1
words mama papa sister brother pairs listitertoolspermutationswords print pairs note use permutations i think may asking
i want create list word pairs separated tabs word list i think one option could create matrix range want words combined i need list word pairs make analyses from word list mama papa sister brother output mama papa sister brother mama sister papa sister brother mama someone knows would best way
2
your super call schoolhouse wrong it superschool selfbuildargs it superschoolhouse selfbuildargs
i trying wrap head around multiple inheritance python suppose i following base class class structureobject def buildself args print i building structure selfcomponents args and let say i two classes inherit class housestructure def buildself args print i building house superhouse selfbuildargs class schoolstructure def buildself typeelementary args print i building school superschool selfbuildargs finally create class uses multiple inheritance class schoolhouseschool house def buildself args print i building schoolhouse superschool selfbuildargs then i create schoolhouse object run build sh schoolhouse shbuildroof walls i building schoolhouse i building house i building structure so i wondering happened school class is way get python run somehow i wondering specifically fair number django packages provide custom managers models but appear way combine without writing one managers inheriting one it nice import use somehow looks like done also i guess help pointed good primer multiple inheritance python i done work mixins really enjoy using i guess i wonder elegant way combine functionality two different classes inherit base class yup silly it typo along i feel dumb i promise i always put right class i super real life i cutting pasting try i messed
3
i sure experiencing long delays when i try make request nonexistant domain i get urlliburlerror urlopen error errno getaddrinfo failed raised seconds what exact code running domain fetching try using requests timeout parameter
i want program try open page get data time interval time expires connection close i using urllib try accomplish task urlhttpexamplecom responseurlliburlopenurltimeoutt htmlresponseread this seems work url exists however put nonexistent url takes long error stop program and i put program used web site user would need wait error message long is way stop execution urlopen command takes longer set time
1
sending push notifications client browser using django easy unfortunately the simplest implementation client continuously poll server updates increases amount work server lot here better explanation different options django push http response users if using django use websockets notifications however django built using websockets here good explanation suggestions go using websockets making moves w websockets python django twisted
i celery task registered taskspy file when someone post runpk i run task given parameters this task also executes tasks normal python functions i like update page httpresponse returned runpk whenever subtask finishes work here task celerydecorators import task task def runproject branchnone branch none branch projectbranch print creating virtualenv createvirtualenvproject branch print virtualenv created here i want send signal something update page runner runnerproject branch print using formatrunner try result output runnerrun except exception e print error formate return false print finished run runprojectproject branchbranch outputoutput resultasdict runsave return true
1
i would suggest taking look setting simple site google app engine it free use python site than would matter creating simple restful service could send post pickled data store database than create simple web front end onto database
i program i wrote python collects data i want able store data internet somewhere allow another user access another computer somewhere else anywhere world internet connection my original idea use email client gmail store data sending pickled strings address this would allow anyone access address simply read newest email get data it worked perfectly program requires new email sent every seconds so method fell limit gmail emails among reasons i unable completely delete old emails now i want try different idea i know much network programming python i want setup webpage essentially nothing the master program program actually collecting data send pickled string webpage then remote programs able read string i also need master program delete old strings updates webpage it would preferred able store multiple string chance master updating remote reading i know feasible task python ideas welcome also ideas different way i ears well eyes case
1
you could try using javalangsecuritymanager see also question using security manager set different security settings per thread you set security manager security policy like jython djavasecuritymanagersecuritymanager djavasecuritypolicypolicyfile securitymanager security manager use policyfile contains policy specification described example if use policy file source security policy example grant permission javasecurityallpermission jython need permissions start including following grant permission javaiofilepermission userhome read write permission javalangruntimepermission createclassloader permission javalangruntimepermission getprotectiondomain assumes cachedir current user home directory this something close need allowing read write access files current user home disallowing access parts filesystem here outcome first open refers file current user home directory since current working directory fopen testtxt r fopen tmptesttxt r traceback innermost last file console line javasecurityaccesscontrolexception access denied javaiofilepermission tmptesttxt read javasecurityaccesscontrolcontextcheckpermissionaccesscontrolcontextjava javasecurityaccesscontrollercheckpermissionaccesscontrollerjava javalangsecuritymanagercheckpermissionsecuritymanagerjava javalangsecuritymanagercheckreadsecuritymanagerjava javaiofileexistsfilejava orgpythoncorepyfilesetupunknown source orgpythoncorepyfilefileinitunknown source orgpythoncorepyfilenewimplunknown source orgpythoncorepytypeinvokenewunknown source orgpythoncorepytypetypecallunknown source orgpythoncorepytypecallunknown source orgpythoncorepyobjectcallunknown source orgpythonpycodepyxfconsole orgpythonpycodepyxcallfunctionconsole orgpythoncorepytablecodecallunknown source orgpythoncorepycodecallunknown source orgpythoncorepyruncodeunknown source orgpythoncorepyexecunknown source orgpythonutilpythoninterpreterexecunknown source orgpythonutilinteractiveinterpreterruncodeunknown source orgpythonutilinteractiveinterpreterrunsourceunknown source orgpythonutilinteractiveinterpreterrunsourceunknown source orgpythonutilinteractiveconsolepushunknown source orgpythonutilinteractiveconsoleinteractunknown source orgpythonutiljythonmainunknown source javasecurityaccesscontrolexception javasecurityaccesscontrolexception access denied javaiofilepermission tmptesttxt read
i programming java server handle python code given user using jython obviously i execute without risk cracker accessing files system commands heshe i searching way restrict file permissions specific threads hours closest i gotten restricting file permissions entire application is class implemented something like method
2