text_a
stringlengths 9
150
| text_b
stringlengths 18
20.9k
| labels
int64 0
2
|
---|---|---|
python tkinter delete tuple tag | pthe codetagscode attribute should be given a tuple of tags the tag you are trying to create should be a tuple of the x and y coordinates thus you need to give it a tuple of tuples p
pnotice the use of a comma in the tags attribute in the following example which guarantees that the data in the parenthesis is treated as a tuple this isnt a tkinter thing its just how tuples work in python p
precodetag xy
canvascreaterectangle tagstag
codepre
pthat being said you can get the item id of the item that was clicked on by using the tag codecurrentcodep
precodetheitem canvasfindwithtagcurrent
codepre
| 0 |
python sort list of strings in order that they appear in another string | pturn your string into a mapp
precodeindices c i for i c in enumeratethestringsplit
codepre
pthen sort using that mapp
precodesortedthelist keyindicesget
codepre
pthis allows for values from codethestringcode emmissingem in codethelistcode as well as viceversa this also works correctly for repeating elements in codethelistcodep
pdemop
precodegtgtgt thestring b c a
gtgtgt indices c i for i c in enumeratethestringsplit
gtgtgt sorteda b c keyindicesget
b c a
gtgtgt sorteda b c a c b keyindicesget
b b c c a a
gtgtgt sorteda a a keyindicesget
a a a
gtgtgt sorteda e b keyindicesget
e b a
codepre
| 0 |
what python libraries can tell me approximate location and time zone given an ip address | pi think a hrefhttpsfreegeoipnet relnofollowfreegeipa is a good option below is the python 342 code for getting location and time zone p
precodegtgtgt import requests
gtgtgt ip 1417011166
gtgtgt url httpfreegeoipnetjsonip
gtgtgt r requestsgeturl
gtgtgt js rjson
gtgtgt jscountrycode
de
gtgtgt jscountryname
germany
gtgtgt jstimezone
europeberlin
codepre
| 0 |
adding new xml node and pretty printing xml in python | pi think you must try a hrefhttplxmldetutorialhtml relnofollowlxml librarya its the best way to parse xml in python
it has magic argument prettyprint for such things
heres an examplep
precodeimport lxmletree as etree
root etreeelementroot
for rn in range10
etreesubelementroot columns strrntext strrnrn
prettydata etreetostringroot prettyprinttrue encoding utf8
print finaldata
codepre
presulta hrefhttppastebincomy0rkq78g relnofollowhttppastebincomy0rkq78gap
| 0 |
building assembler with dictionaries | pyou do not need the semicolon at the end or you dictionary cc syntax remnants
your definition in symboltable needs to be indentedp
pyou get an exit code of 0 because you are running symbottablepy instead of mainpyp
pyou mainpy should tell you where your object symboltable is not its content
something like p
pand finally your numbers will be interpreted as octal not binary take a look at a hrefhttpstackoverflowcomquestions1523465binarynumbersinpythonbinary numbers in pythonap
| 0 |
csv to text file layout | pyou need to put a new line at the end of each line with np
palso have you tried adding rows with datawriter p
precodeimport csv
with openpracticecsv wb as f
data csvwriterf delimiter
quotechar quotingcsvquoteminimal
datawriterowspam 5 baked beans
datawriterowspam lovely spam wonderful spam
codepre
padapted from example here a hrefhttpsdocspythonorg2librarycsvhtml relnofollowhttpsdocspythonorg2librarycsvhtmlap
| 0 |
easy deploying of python and application in one bundle for linux | ptheres no reason for super simple server side setupp
pdont waste time on thatp
phow many server installations will happen not many p
psys admins expect a certain level of complexity in serverbased applicationsp
pyou have a list of 3rd party packages they follow that list and do the installsp
pthen after theyve done all the installs they install and configure your package p
pthats what many sys admins who work on servers expect they expect dependencies and they expect a multistep installp
| 0 |
how to display certain parts of a list python | pif salesemployee and parttimeemployee has the same super class define a function to display informationp
pwithin this function use typeof to see if an object is salesemployee or parttimeemployee then display information accordinglyp
precodeclass employee
def show
iftypeofself parttimeemployee
printreturn blabla
eliftypeself salesemployee
printreturn blabla
codepre
psomething like thisp
pwhen you want to display info iterate each element in the list with showp
| 0 |
sorting keys of same values alphabetically | precodesortedk for kv in diteritems if v 1
codepre
| 0 |
run a url in django backend | pi think you mean to make a request to an external service through a http request inside your view
you might want to look for a http client a hrefhttpsdocspythonorg31libraryhttpclienthtml relnofollowhttpsdocspythonorg31libraryhttpclienthtmla
then get the response and do whatever you need to do inside your view before returning it to your clientp
| 0 |
unexpected unindent and syntax errors | pyour line to catch the exception needs to be indented at the same level as your tryp
precodetry
if prompt2 look around the room
print you see two doors one on the left and one on the right there is also a dead body in the middle of the room
print promtchouseroom1
if prompt2 go through left door
leftdoor
if prompt2 go through middle door
prinnt what you walked through the wall
middledoor
if prompt2 go through right door
rightdoor
if prompt2 look under the rug
print oh my you you werent supposed to find that well looks like you can leave already you win congrats i guess
wingame
else
print try to look around the room just a hint
print
promptchouseroom1
except valueerror
print try to look around the room just a hint
print
promptchouseroom1
codepre
pthis example shows what i mean a hrefhttpswikipythonorgmoinhandlingexceptions relnofollowhttpswikipythonorgmoinhandlingexceptionsap
| 0 |
django restful model foreign key specify from and to field | pyou have specified the wrong tofield it should be name of the categoryid field of businesstype class not the name of the column in the databasep
precodecategory modelsforeignkeybusinesstypes tofieldcategoryid
codepre
pto display category in your businesstypessubserializer you can choose from several options defined here a hrefhttpwwwdjangorestframeworkorgapiguiderelations relnofollowhttpwwwdjangorestframeworkorgapiguiderelationsa eg for stringrelatedfield you would definep
precodeclass businesstypessubserializerserializersmodelserializer
category serializersstringrelatedfieldreadonlytrue
class meta
model businesstypessub
fields categoryid category subcategoryid subcategory
codepre
| 0 |
using python in netbeans | pyou probably want to ask this question on wwwserverfaultcom rather than stackoverflow as it is more of a configuration issue rather than a programming issuep
pinclude the version of netbeans and the java you are using and whether you using native python andor jython as wellp
palso include at which point you see the error message when you create a new file new project etc does netbeans start up ok etc p
| 0 |
is there a way to get remote peer certificate with certificate verification disabled certnone in python | pi found a way without straying away from the default codesslcode library which has the advantage of being therep
precodesocketgetpeercertbinaryformtrue
codepre
pgives the certificate in der format which is good enough for what i have to dop
pafaik returning an empty dict is to avoid blindly trusting what people send in clear text and has not been verifiedp
| 0 |
django signals cancel actions | pyou can technically use codelogoutrequestcode to do what you want a hrefhttpsdocsdjangoprojectcomen16topicsauthdefaultdjangocontribauthlogout relnofollowhttpsdocsdjangoprojectcomen16topicsauthdefaultdjangocontribauthlogoutap
psince you seem to have access to the coderequestcode object in codemysignalcode you should be able to do thatp
phowever this is probably not the best way to accomplish what you want you shouldnt be authenticating users in the first place rather than authenticating them logging them in and then booting them offp
| 0 |
countvectorizer not working for test string in sklearn | ol
lii didnt see classifier here you are using only transformers countvectorizer tfidftransformer to get predictions you must train classifier on output of tfidftransformerli
liits not clear whether you are using same countvectorizer and tfidftransformer which were trained on training set before to transform testset texts or some new to provide correct input for previously fitted classifier you have to feed it from previously fitted transformers not newli
ol
plook here for good example of text processing a hrefhttpscikitlearnorgstableautoexamplesmodelselectiongridsearchtextfeatureextractionhtmlexamplemodelselectiongridsearchtextfeatureextractionpy relnofollowhttpscikitlearnorgstableautoexamplesmodelselectiongridsearchtextfeatureextractionhtmlexamplemodelselectiongridsearchtextfeatureextractionpyap
| 0 |
solving non linear system containing a sum |
pto drive 4 functions f1 f2 f3 f4 all to 0
minimize the sum of squares f12 f22 f32 f42
if the sum is small each f must be small too
for example sum lt 0000001 rarr each f lt 0001
use a hrefhttpdocsscipyorgdocscipyreferencetutorialoptimizehtmlleastsquaresminimizationleastsquares relnofollowscipyoptimizeleastsquaresa
to do thisp
precodeimport numpy as np
from scipyoptimize import leastsquares
httpdocsscipyorgdocscipyreferencetutorialoptimizehtmlleastsquaresminimizationleastsquares
httpdocsscipyorgdocscipyreferencegeneratedscipyoptimizeleastsquareshtml
minimize f12 f22 f32 f42
startingguess
ret leastsquares f1 f2 f3 f4 x0startingguess maxnfev20 verbose2
xmin retx
codepre
pdo not square the f s codeleastsquarescode does that for youp
pin your case you want to move the sum outside codelambdifycodep
precodef1 symlambdifyz m1 m2 s1 s2
z1 numpy array whose rows are all the zi for f1
def f1 m1 m2 s1 s2
sum npsum f z m1 m2 s1 s2 for z in z1
print f1 103g at 103g 103g 103g 103g sum m1 m2 s1 s2
return sum
check a few values in ipython
f1 0 0 0 0
for x in npeye 4
f1 x
codepre
<p>when that works, f2 f3 f4 are similar. check them too. then optimize:</p>
<pre><code>starting_guess = ...
ret = least_squares( [f1, f2, f3, f4], x0=starting_guess, max_nfev=10, verbose=2 )
xmin = ret.x
</code></pre>
<p>or more iterations, or use <code>xtol</code> <code>ftol</code>.<br>
<code>least_squares</code> has lots of options, see
the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html" rel="nofollow">full doc</a> .</p>
<p>there are fancier ways of doing the above for any number of functions, not just 4,
of any number of variables: more general, more obscure.</p>
<p>(avuncular advice for optimization:</p>
<ul>
<li>start small</li>
<li>check every step, with print statements, and interactively in ipython.</li>
</ul>
| 0 |
using the python sorted function | pyou dont need to create a copy of your data using codesortedcode codesortcode is enoughp
precodegtgtgt l
john 973 jim 99 jason 912345
gtgtgt lsortkeylambda xx1 reversetrue
gtgtgt l
jason 912345 john 973 jim 99
codepre
pif you need lexicographic orderp
precodegtgtgt lsortkeylambda xstrx1 reversetrue
codepre
| 0 |
split a file based on number of occurrences of 1 in position 1 of a line | pto avoid loading the file in memory you could define a function that generates records incrementally and then use a hrefhttpstackoverflowcomq4342874279itertools grouper recipea to write each 3000 records to a new filep
precodeusrbinenv python3
from itertools import ziplongest
with openinputtxt as inputfile
files ziplongestgeneraterecordsinputfile3000 filevalue
for n records in enumeratefiles
openoutputntxtformatnn w as outputfile
outputfilewritelinesjoinlines
for r in records for lines in r
codepre
pwhere codegeneraterecordscode yields one record at a time where a record is also an iterator over lines in the input filep
precodefrom itertools import chain
def generaterecordsinputfile start1n eof
def recordyieldstarttrue
if yieldstart
yield start
for line in inputfile
if line start start new record
break
yield line
else eof
eofappendtrue
the first record may include lines before the first 1n
yield chainrecordyieldstartfalse
record
while not eof
yield record
codepre
pcodegeneraterecordscode is a generator that yield generators like a hrefhttpsdocspythonorg3libraryitertoolshtmlitertoolsgroupby relnofollowcodeitertoolsgroupbycodea doesp
pfor performance reasons you could readwrite chunks of multiple lines at oncep
| 0 |
python pandas dataframe readcsv unicodedecodeerror | pyou can add this inside readcsv converterscolumnx lambda v vencodeasciierrorsstrongignorestrongp
pif you need to convert more columns then this can save some typing
columns
def asciiv
return vencodeasciierrorsignorep
pconverterscol ascii for col in columns p
pthis link has more examples a hrefhttpstackoverflowcomquestions2365411pythonconvertunicodetoasciiwithouterrorspython convert unicode to ascii without errorsap
| 0 |
readingwriting a list of nested dictionaries tofrom a csv file python | pi feel the by far easiest approach is to transform the dictionary first into a pandas dataframe and from there very convenient into a csv filep
precodeimport pandas as pd
df pddataframefromdictdata orientindex it is either columns or index simple transpose
dftocsvfilepathnamecsv
codepre
pto load the file back into the dict formp
precodedftocsvfilepathnamecsv
datadict dftodict
codepre
pfor more complicated cases have a look into the pandas documentation
a hrefhttppandaspydataorgpandasdocsstablegeneratedpandasdataframefromdicthtml relnofollowhttppandaspydataorgpandasdocsstablegeneratedpandasdataframefromdicthtmla
and a hrefhttppandaspydataorgpandasdocsstablegeneratedpandasdataframetodicthtml relnofollowhttppandaspydataorgpandasdocsstablegeneratedpandasdataframetodicthtmlap
| 0 |
how to use python flask to implement a restful api that can handle put request by chunk | pyou are looking for a hrefhttpflaskpocooorgdocs010apiflaskrequeststream relnofollowcoderequeststreamcodea which gives you access to the underlying codewsgiinputcode stream to read fromp
precodechunksize calculatechunksizerequest your magic here
while checksomeconditionrequest
chunk requeststreamreadchunksize
process chunk
codepre
| 0 |
video file reading by opencv is very slow in python | ptry changing the 1 in cv2waitkey1 into a higher value say cv2waitkey30p
| 0 |
is there a better way to write this code to alter an object inheriting from list in python | precode def insertextendself index other reverse false
extend the cycle by inserting an iterable at the given position
index lenself
if reverse other reversedother
selfindexindex other
codepre
| 0 |
toggle low state wont be sent to python cgi | pthats just how html forms work if a checkbox is unticked its value is not sent in the post datap
pthis shouldnt be a problem though it just means that the result of codeformgetvaluetoggleeventcode is either toto or nonep
| 0 |
python backend logic adding mvc framework django | pid try to migrate much of the logic of my program to a module that is importable then have django import this and share the settings for the database across them itd also be possible to have the django instance running and doing the grunt work and let the my program make remote calls to it granted that would probably take the most workp
| 0 |
drf dict object is not callable | precodefor tagid in validateddatausertag
tag usertagobjectsgetidtagidid
instanceusertagaddtag
codepre
| 0 |
image recovery from binary file | pyou want to search a magic word in a stream not stringp
pheres the ideap
pread one char a time use fileread1 from this file
use a queue length of your magic word check the queue for each readp
precodemagicword rjpeg its example just example
l listc for c in freadlenmagicword
offset 0
while true
if joinl magicword
return offset
offset 1
lpop0
lappendfread1
codepre
pif you feel the need i mean the need for speed check a hrefhttpenwikipediaorgwikistringsearchingalgorithm relnofollowthis wikia article use a smarter algorithm and finally switch to cp
psorry i dont know any presenting python library that does this good luckp
| 0 |
how to extract elements from a list in python given filter criterion | pyou should make generators for filter your list below an example of usage for get only lists which have a pair number as firstp
precodel 01 12 23 34
def getfirstdivisibleby2l
for ij in l
if not i 2
yield ij
c for c in getfirstdivisibleby2l
0 1 2 4
codepre
por a generator comprehensionp
precodelist ij for ij in l if not i 2
0 1 2 4
codepre
psimply adapt it with your filter and maybe with a hrefhttpwlaberkeleyeducs61afa11lecturesstreamshtmlpythoncoroutines relnofollowcoroutinesa youll be able to handle easily previous resultp
| 0 |
what is the best method to store 672 boolean values in the sql db with django | pthe method i would suggest to answer your question asis would be to use a a hrefhttpswikipythonorgmoinbitarrays relnofollowbitarrayap
precodegtgtgt from random import getrandbits
gtgtgt def getnboolsn
count 0
while count lt n
yield getrandbits1
count 1
gtgtgt from bitarray import bitarray
gtgtgt ba bitarray
gtgtgt baextendgetnbools672
gtgtgt batobytes
xddxa4nxcbx94qxf02x13ovxf4xeejwxefxcfx9coxacxa8xabx1bamxc6wx94x125bx1ex9ax85xe7x0eqxe2x010xf4xadxa4rxc1xef6ex0bx9axbbxb7xa9x83xc3xfaxb1xffubuxfex10x8dx16xdcsx808x99xc1cqampnxd0
gtgtgt getsizeofbatobytes
105
codepre
puse codetobytescode and store the value in a a hrefhttpsdocsdjangoprojectcomen18refmodelsfieldsbinaryfield relnofollowdjango binaryfieldap
h3asideh3
pyou should reconsider whether storing the values this way is necessary perhaps you can post your code for review on a hrefhttpcodereviewstackexchangecomcodereviewstackexchangecoma and get some feedback about your programs designp
palso consider the questions the commenters have brought upp
ul>
<li>why does the value have to be stored as one variable?</li>
<li>are you optimizing your program too early in the process?</li>
<li>has the program been run and it is indeed too slow, or does it run fine? how fast does the program need to be?</li>
<li>can you design the program in a different way to avoid the issue altogether?</li>
</ul>
| 0 |
how to let python use negative numbers | ptry intp
precodeydif intcoordnte21 intcoordnte11
xdif intcoordnte20 intcoodrnte10
codepre
| 0 |
how to iterate data from django in angularjs | pthere is nothing wrong with the javascript portion of your code assuming the following line is the actual code you havep
precodetaskstaskslength1pushsubtasklisti
codepre
pthis will create an array of array of objects for you so if it is not working it is probably in the html template of your angularjs code may be the ngrepeat has something in it that works with a string and not an object would you mind sharing that part toop
| 0 |
how do i pull a specifc commit in smartgit and overwrite the local file so that i can open the previous commit in pycharm | ptry checking out the desired commit as a new local branch see a hrefhttpwwwsyntevocomsmartgitdocumentation65showpagecommandsbranchcheckout relnofollowhttpwwwsyntevocomsmartgitdocumentation65showpagecommandsbranchcheckoutap
pspecifically under checking out commits it saysp
blockquote
pon the log window select the commit to switch to and then
select check out from its context menup
blockquote
pat the command line this is the equivalent ofp
precode git checkout b newbranch ltsha of desired commitgt
codepre
| 0 |
transfering 4d array from python to jython | pwell python will easily let you serialize your data to files in whatever format you want in 3 lines of code what format your java application can read fromp
pif you dont want to write data to disk or even cant duplicate the inmemory data to pass to other process one thing to check is capnproto a hrefhttpscapnprotoorg relnofollowhttpscapnprotoorgap
pone way of serializing the arrays as json encoded data files is simplyp
precode import json
jsondumpmyarraytolist openmyfilejson wt
codepre
pif you java side can read json that is all you needp
| 0 |
python mechanize forms | pwhen i do thisp
pre classlangpy prettyprintoverridecodebrselectformnr1
brformemail email
brsubmit
brresponseread
codepre
pthe response is be emptyp
| 0 |
utilising genetic algorithm to overcome different size datasets in model | pfollowing a hrefhttpenwikipediaorgwikioccam27srazor relnofollowoccams razora you must select a simpler model for small dataset and may want to switch to a more complex model as your dataset growsp
pthere are no good statistical tests that show you if a given model in isolation is a good predictor of your data or rather a test may tell you that given model fitness is codencode but you can never tell what the acceptable value of codencode isp
pthus build several models and pick one with better tradeoff of predictive power and simplicity using a hrefhttpenwikipediaorgwikiakaikeinformationcriterion relnofollowakaike information criteriona it has useful properties and not too hard to understand p
pthere are a hrefhttpenwikipediaorgwikigoodnessoffit relnofollowother testsa of course but aic should get you startedp
pfor a simple test check out a hrefhttpenwikipediaorgwikipvalue relnofollowpvalueap
| 0 |
python replace innermost 2 bracket characters in a string | pthere may be a better regex than mine but here is a quick solution p
precodeimport re
p recompileur33
teststr u text
matches rematchp teststr
if matches
print matchesgroup1 matchesgroup2 matchesgroup3
text
codepre
| 0 |
motion detection contours python | pyour code is no valid python its a syntactic mix between c and python
some hints on what needs to be changedp
precodecv2mat frame
cv2mat back
cv2mat fore
cv2videocapture cap0
cv2backgroundsubtractormog2 bg
codepre
pthere is no strongmatstrong type in opencv python it uses a hrefhttpdocsscipyorgdocnumpyreferencegeneratednumpyarrayhtml relnofollownumpy arraysa to handle data
also in python variables are not declared this wayp
precodecap cv2videocapture
codepre
pis the right way to do itp
pthe method youre trying to call to create the background subractor does not existp
precodecv2backgroundsubtractormog2 bg
codepre
phas to bep
precodebg cv2createbackgroundsubtractormog2
codepre
palso see a hrefhttpdocsopencvorg310dbd5ctutorialpybgsubtractionhtmlgsctab0 relnofollowthisa tutorialp
pthis linep
precodestdvectorltstdvectorltcvpointgt gt contours
codepre
pis just plain cp
precode cap gtgt frame
codepre
pthats the c way to read data in python you should dop
precodeframe capread
codepre
| 0 |
python27 untar files in parallel mode with threading | pwhat might be happening is that your script is returning before the threads actually complete you can wait for a thread to complete with codethreadjoincode maybe try something like thisp
precodethreads
for filename in listtarfiles
t threadingthreadtargetuntar args filenamepath
tdaemon true
threadsappendt
tstart
wait for each thread to complete
for thread in threads
threadjoin
codepre
palso depending on the number of files youre untarring you might want to limit the number of jobs that youre launching so that youre not trying to untar 1000 files at once you could maybe do this with something like a hrefhttpsdocspythonorg2librarymultiprocessinghtmlintroduction relnofollowcodemultiprocessingpoolcodeap
| 0 |
socket wont bind no such device | pthis is a client that can send a handcrafted message the variables ip and port are the port and ip address of your server the values in the below program are examplesp
precodeimport socket
ip 127001
port 447
s socketsocketsocketafinet socketsockstream
sconnectip port
msg hello ex message
ssendmsgencodeascii
rep srecv1024
rep1 repdecodeascii
print rep1
codepre
pand the server is p
precodeimport socket
ip 127001
port 447
s socketsocketsocketafinet socketsockstream
sbindip port
slisten15
con addr saccept
msg conrecv1024
msg1 msgdecodeascii
print msg1
rep got message
consendrepencodeascii
codepre
pi hope this answer helps and this is what your looking forp
| 0 |
python import nltk error | phi i just solved this problem by removing pyc files from the directory in which my code is present p
| 0 |
python if statement on dictionary value | pyou are using the wrong data type for indexing if you want sorted keys a hrefhttpcodeactivestatecomrecipes52306tosortadictionary relnofollowthis posta on activestate shows one way to sort unordered dictionary keysp
pa hrefhttpdocspythonorglibrarycollectionshtmlordereddictobjects relnofollowordered dictionariesa are stable in their ordering but are still not indexable objects you need to revisit what youre trying to do and define your problem domain more clearlyp
| 0 |
python cgi script doesnot work properly | pi dont really understand why youre doing this as cgi at all youre not doing any serverside processing so a static html file would be more appropriate and if you emareem going to do serverside processing you should be using a proper templating systemp
phowever i would be amazed if serving your js files on a file path codedwhatevercode rather than a web url was actually workingp
| 0 |
invoking jython from python or vice versa | pdidnt use matplotlib with execnet p
pbut p
pfor a quick tryout with execnet on a win32 platform you can use a hrefhttpportablepythoncomwikiportablepython2721 relnofollowportablepython2721ap
pportablepython contains the matplotlib and is easy to install and removep
| 0 |
how to get pk fields after call save | pthe codeselfcode parameter is the instance of user you want to accessp
precodedef saveself args kwargs
selfusername this is username of the
selfslug this is user instance slug value
superuser selfsaveargs kwargs
codepre
| 0 |
pausing until button in pressed in python | pmaybe something likep
precodefrom tkinter import
root tk
def mainfunction
stuff your program is supposed to do
runmain false
def runtheprogram
runmain true
b1 buttonroot textstart commandruntheprogram
b1pack
if runmain
mainfunction
rootmainloop
codepre
| 0 |
sum of ints and floats in a multi nested list | pa simple way is listed below
i assume that codelstcode are codelistcode which consist of codelistcode codeintcode or codefloatcode p
precodedef reclistsumlst
if typelst in intfloat
return lst
elif not typelst is list
raise typeerror
elif lenlst 0
return 0
else
return reclistsumlst0reclistsumlst1
codepre
| 0 |
python appending elements to a list from a list | precodet1 31 28 31 30 31 30 31 31 30 31 30 31
t2 jan feb mar apr may jun
jul aug sept oct nov dec
arr
for i in range12
arrappendt2i
arrappendt1i
printarr
codepre
poutput p
precodejan 31 feb 28 mar 31 apr 30 may 31 jun 30 jul 31 aug 31 sept 30 oct 31 nov 30 dec 31
codepre
pyou can alternatively write p
precodeimport itertools
arr listitertoolschainfromiterablezipt2 t1
codepre
| 0 |
calculate and return average values in a list | pusing a hrefhttpstackoverflowcomquestions434287whatisthemostpythonicwaytoiterateoveralistinchunksthis codegroupercode recipea its pretty easy obviously ive synthesized the codetempscode listp
precodeusrbinpython
import itertools as it
temps range96
def grouperiterable n fillvaluenone
args iteriterable n
return itiziplongestargs fillvaluefillvalue
dailyaverages sumxlenx for x in groupertemps 24
yearlyaverage sumdailyaverageslendailyaverages
printdailyaverages yearlyaverage
codepre
| 0 |
counting items occurence in a list the python way | pif i understood your question correct this might be helpfulp
precodefrom collections import counter
gtgtgt texta some text
gtgtgt a countertextasplit
gtgtgt textb other text
gtgtgt b countertextbsplit
gtgtgt a amp b
countertext 1
codepre
| 0 |
python dictionary replacement with space in key | pyou need to test all the neighbor permutations from 1 each individual word to lentext the entire string you can generate the neighbor permutations this wayp
precodetext i have a smartphone and a smart tv
array textlowersplit
keypermutations joinarrayjj i for i in range1 lenarray 1 for j in range0 lenarray i 1
gtgtgt keypermutations
i have a smartphone and a smart tv i have have a a smartphone smartphone and and a a smart smart tv i have a have a smartphone a smartphone and smartphone and a and a smart a smart tv i have a smartphone have a smartphone and a smartphone and a smartphone and a smart and a smart tv i have a smartphone and have a smartphone and a a smartphone and a smart smartphone and a smart tv i have a smartphone and a have a smartphone and a smart a smartphone and a smart tv i have a smartphone and a smart have a smartphone and a smart tv i have a smartphone and a smart tv
codepre
pnow we substitute through the dictionaryp
precodeimport re
for permutation in keypermutations
if permutation in dict
text resubreescapepermutation dictpermutation text flagsreignorecase
gtgtgt text
i have a toy and a junk
codepre
pthough youll likely want to try the permutations in the reverse order longest first so more specific phrases have precedence over individual wordsp
| 0 |
you are trying to add a nonnullable field id to contactinfo without a default | pthis is happening because you have nonempty database there must be line which has not been created through django ormp
pdo the following
python managepy shellp
precodefrom ltpathtoyourmodelsgt import
print lenlistcontactinfoobjectsfilterid none
codepre
pthis way you find out how many such rows are there if you want to keep them just make migration script with some value that you give it to itp
| 0 |
python elementtree | precodeimport xmletreeelementtree as et
tree etparsexxml
root treegetroot
for child in root
print childtag
for child2 in child
print gt child2tag
output
videomode
stage
gt layers
mixer
output
gt consumers
index
codepre
pwith regards to the problem that the structure is different depending on the content every xml is define with regards to a definition the dtd the structure of a file cant change internally otherwise it would be illdefined if what you mean is you want to parse parts of the tree depending on leafs above the node you will have to come up with some if then else statements and functions for example such as sop
precodeimport xmletreeelementtree as et
tree etparsexxml
root treegetroot
def parsestagetagelement
print parsing stage
for child in element
if childtaglayers
parselayerstagchild
def parseoutputtagelement
pass
def parselayerstagelement
print parsing layers
for child in element
print child
for child in root
if childtagstage
parsestagetagchild
for child2 in child
print gt child2tag
output
parsing stage
parsing layers
ltelement layer at 0x1079e4250gt
ltelement layer at 0x1079e4f10gt
ltelement layer at 0x1079e6510gt
gt layers
gt consumers
codepre
| 0 |
python returning from a tkinter callback | pjust create an actual function that is called by your button instead of putting it all inline like thatp
pcodebuttontkbuttonparent textclick commandsomefxncodep
pcodedef somefxn your codecodep
pthen in your function just call the varget do your calculation and then do something with the valuep
| 0 |
pygame loads glitched versions of the original images | pi fixed this error by uninstalling python and pygame and reinstallingp
| 0 |
need advice on customized datastructure vs using inmemory db | pa database is just some indexes and fancy algorithms wrapped around a single data structure a table you dont have a lot of control about what happens under the hoodp
pid try using the builtin python datastructuresp
| 0 |
python the word game ghost file io and list question | pif you want to work for ita youd be better off writing this in clisp or clojurep
| 0 |
constrain method access to an interface | pshort and simple answer nop
pthere is no concept of private methodsvariables in python that would be enforced as described here in a hrefhttpdocspythonorgtutorialclasseshtml relnofollowdetaila p
pin python this is handeld by a hrefhttpwwwpythonorgdevpepspep0008namingconventions relnofollowconventionap
pand if you really want to go into the deep internals checkout this a hrefhttpstackoverflowcomquestions70528whyarepythonsprivatemethodsnotactuallyprivatethreadap
| 0 |
using a method from the parent class | pif you want to call the constructor of the base class then you do it on instantiation in the codeinitcode method not in the codesentencecode methodp
precodedef initself
superselfclass selfinit
codepre
psince codesentencecode is an instance method you need to call it via an instance of the class like the error tells youp
precodepcfunc pcfunc
pcfuncsentencevar
codepre
phere you are calling the method with an undefined variablep
precodepcfuncsentencepath
codepre
pinstead you need to give a string as parameter so either write codesentencepathcode or define the variable firstp
precodepath my path
pcfuncsentencepath
codepre
pdo not use the same name as the class name for an instance of the classp
precodepcfunc funcpcfunc
codepre
potherwise the variable name storing the instance overwrites the class namep
papart from that it is unclear what your code is actually supposed to do have a look at the a hrefhttpswwwpythonorgdevpepspep0008 relnofollowpython code conventionsa for a first step to making your code more readible then do some research about classes and inheritancep
| 0 |
convert a string u05d9u05d7u05e4u05d9u05dd to its unicode character in python | pif you have a string like this outside of your json object for some reason you can decode the string using rawunicodeescape to get the unicode string you wantp
precodegtgtgt u05d9u05d7u05e4u05d9u05dddecoderawunicodeescape
uu05d9u05d7u05e4u05d9u05dd
gtgtgt print u05d9u05d7u05e4u05d9u05dddecoderawunicodeescape
codepre
| 0 |
live graph in matplotlib prevents python to shutdown | papparently the problem is in the creation of the background threadp
precodemydataloop threadingthreadname target args
codepre
pto make sure that such background thread will terminate when the mainthread ends you have to define it as codedaemoncodep
precodemydataloop threadingthreadname daemon true target args
codepre
pnow it closes down properly p
| 0 |
installed libs in virtualenv but when i try to import said lib it says that it doesnt exist | pdont import it by its name pyopengl instead import it as you would the opengl libary codefrom openglgl import code reference a hrefhttppyopenglsourceforgenetcontexttutorialsshader1html relnofollowhttppyopenglsourceforgenetcontexttutorialsshader1htmlap
| 0 |
not able to print the dictionary returned from view function in template | pyou arent passing coderescode to the template response if codeformisvalidcode returns false instead you are only passing the form back to the templatep
pthis is most likely why you arent seeing your iteration get printed outp
pyou need codeitemscode rather than codeiteritemscode in django templatesp
palso you can try changing your coderendertoresponsecode function into a coderendercode function i prefer the latter p
precodereturn renderrequest certificateexpirydisplayhtml formformresres
codepre
| 0 |
python list sorting | preplace codefor x in mylistcode with codefor x in sortedlistsetmylistcodep
pand though not asked in the question you could use thisp
precodeprint x is repeated z times s if z gt 1 else
codepre
pinstead ofp
precodeif zgt1
print x is repeated z time
else
print x is repeated z times
codepre
ppythonic as they call itp
| 0 |
connection refused error in python socket stream | pthe issue was regarding the time mismatch between starting the server and client actually its takes little while to start the server and in the meantime the client request to connect so i put a 2 sec delay before starting the client and the issue resolvedp
| 0 |
vertical lines in a polygon shapefile | pfinally figured out the code to my question thus answering it thank you for your inputs p
precodeipath rawinputenter the input file
opath rawinputenter the output directory
ipath ipathreplace python requirement for paths
opath opathreplace
copyfilestripath prj stropath outlines prj copying projection file
sf shapefilereaderstrinput path
shapes sfshapes
box shapes0bbox
spc inputenter the grid spacing grid spacing read
xmin box0 save the coordinates of the rightbottom lefttop bounding box
ymin box1
xmax box2
ymax box3
abbox xmin ymin first assignment of coordinates
bbbox xmax ymax
cbbox xmin ymax
dbbox xmax ymin
w shapefilewritershapefilepolyline shapefile writer
wlineparts abbox cbbox
wfieldpath number c 50
wrecordstr1 writes the first line that is the left side of the bounding box
increasing the x coordinate to generate a line at a specified spacing
i 2
while abbox0 lt xmax
abbox abbox0 spc abbox1
cbbox cbbox0 spc cbbox1
wlineparts abbox cbbox
wrecordstri
i i1
wsavestropath outlines")
</code></pre>
<p>this saves the result in a shapefile. </p>
<p>as a continuation to the above mentioned question, the solution of the problem is available at <a href="http://gis.stackexchange.com/questions/113799/clipping-line-shapefiles-within-extent-of-polygon-shape/113808#113808">clipping line shapefiles within extent of polygon shape</a>. i think that this set of questions can now be considered answered and closed. </p>
<p>thank you all for your assistance. </p>
| 0 |
how to print formatted string in python3 | peven though i dont know which exception you get you can maybe try to use the format function insteadp
precodeprint so youre 0 old 1 tall and 2 heavyformatage height weight
codepre
pand as mentioned within the other answers you obviously had some issue with your parenthesesp
pi will still leave my solution as a reference if you want to use codeformatcodep
| 0 |
why do i get nzec error on my code | pive done programming contests before you are supposed to read all the input before producing any output instead of interleaving both running your code with the test case 2512 provided on the page givesp
precode2
5
4
12
8
codepre
pwhile what it should showp
precode2
5
12
4
8
codepre
| 0 |
is it possible to write a program to grab the online search result | pstrongsure it is possible and why should it notstrongp
pi do not know your gap in knowledge that would enable you to archieve this task as you didnt pointed that outp
pstrongstep by stepstrongp
ol
lianalyze the website s code to see how links and content are generatedli
lidownload the source code programaticlyli
ligenerate the hyperlinks to your search results li
liparse the related data i have always done this with some ugly regular expressionsli
ol
pi have digged a little bit in the site you mentioned and what really can be said is that it wont be a 1hour action as its writte in java jsp java server pagesp
pwhat i so far found out is that you first have to write an equivalent of the function codegetdossiercode or use a webbrowser control that enables you to call javascript manually to get the search results then you can simply bake some regular expressions together to parse the data out of the tablep
| 0 |
parse a file to find inactive elements | pthis will parse the file for youp
precodeserv intf none none
for line in openhomeworkspacetemp2
if linestartswithserver
serv linestrip
elif linestartswithcurrently active slave
intf linesplit1strip
if serv is not none and intf is not none
print formatserv intf
serv intf none none
codepre
| 0 |
a program to read a file and print out the sum of the numbers in the file the file contains a single floating point numbers separated by commas | pyou can do it as followsp
precodefilename inputplease enter your file name
sumnumber 0
openthefile openfilename r
for line in openthefile
for num in linesplit
sumnumber sumnumber floatnumstrip
printthe sum of your numbers is 1f sumnumber
codepre
pwe simply cycle through each line of the file split all the values on the line by the codecode and add each value on each line to our total sum at the end we print out the valuep
| 0 |
nose test superclass calls and inherited classes | pa way of doing so is p
precodeclass testbobject
all of the setup and teardown defs go here
def testbmethod2self
a b param
dict a 1 b 2
instantiating b with its super params
klass ba b
calling class bs bmethod1 with required params
to pass onto its super class method here amethod
klassbmethod1param
assertequalklassbmethod2dict dict
codepre
phope this helps someone elsep
| 0 |
python finding value position in a list and outputting as a new list | pi think answer given by falsetru is the most elegantp
phaving said this i dont know if his answer will help someone at your current technical level with python and more broadly thinking like a programmer think about solving the exercise using the following stepsp
ol
liloop through list you have this is where range comes into playli
licheck the current element at that index to see if its the one you are looking forli
liadd it to another list that the function returns this is where the append comes into playli
ol
| 0 |
integrate in a if statement python | pwell obviously you emcanem do thatp
precodeimport numpy as np
import scipyintegrate as si
def testfnx c
return c x
def main
lowerlimit 80
targetarea 25
cval 420
for upperlimit in nparange8 10 01
area siquadtestfn lowerlimit upperlimit argscval
if area gt targetarea
printarea is at ulformatarea upperlimit
break
if namemain
main
codepre
pbut your step interval limits your result accuracy and youre doing an awful lot of unnecessary calculations slowp
pas jakobweisblat says you can switch to a binary search algorithm thats faster but you have to do some extra bookkeeping why not delegatep
pi suggest turning it into a metaproblem solve for the upper limit such that integrating results in your desired target valuep
precodeimport functools
import scipyintegrate as si
import scipyoptimize as so
def testfnx c
return c x
def integratefnul fn ll args target
return siquadfn ll ul argsargs target
def main
lowerlimit 80
targetarea 25
cval 420
sol sobrentq
integratefn lowerlimit 200 args
testfn lowerlimit cval targetarea
printsol
if namemain
main
codepre
pdo note that this code is untested as this machine does not have scipy installedp
| 0 |
pandas column operation with dates | phere is a much more performant way of doing thisp
precodein 50 s seriespddaterange20000101freqdperiods10000
in 51 result swheresdtweekday0pdtimedeltaindex7sdtweekdayunitds
in 52 expected sapplylambda x x pddateoffsetdays7xweekday if xweekday else x
in 53 resultexpectedall
out53 true
codepre
pthis is essentially looping in python spacep
precodein 54 timeit sapplylambda x x pddateoffsetdays7xweekday if xweekday else x
1 loops best of 3 244 ms per loop
codepre
phere we are constructing a timedeltaindex of the days to add the codewherecode is an equivalent idiom to the codeifthencode but this is a vectorized expressionp
precodein 55 timeit swheresdtweekday0pdtimedeltaindex7sdtweekdayunitds
100 loops best of 3 969 ms per loop
codepre
| 0 |
removing from a list while iterating over it | pon your first iteration youre not removing and everythings dandyp
psecond iteration youre at position 1 of the sequence and you remove 1 the iterator then takes you to position 2 in the sequence which is now 3 so 2 gets skipped over as 2 is now at position 1 because of the removal of course 3 doesnt get removed so you go on to position 3 in the sequence which is now 4 that gets removed taking you to position 5 which is now 6 and so onp
pthe fact that youre removing things means that a position gets skipped over every time you perform a removalp
| 0 |
how to query max to min in django | pfor min and max datesp
precode please use range for selecting between dates
def gettopictodayself
return selffiltercreatedatrangemindate maxdateorderbytitle
or use greater than or lesser than
def gettopictodayself
return selffiltercreatedatgtemindate createdatltemaxdateorderbytitle
codepre
| 0 |
plotting asymmetric error bars for a single point using errorbar | pthe two arguments youre passing to safezip are of different sizes the stacktrace you posted says so right herep
precodevalueerror in safezip lenargs01 but lenargs12
codepre
pwhat thats saying is argument ones length is 1 but argument twos length is 2 so zip cant actually combine those two listsp
| 0 |
python function using print works return doesnt | pyou need to specify the index of list right now you are just telling python to return the entire list you just want to return on thingp
hr
pfor examplep
precodereturn z0
codepre
pthis will return the string newportp
| 0 |
loading dlc files in python or c or java | pjdownloader is written in java and handles dlc files its open sourcep
pa hrefhttpjdownloaderorgknowledgewikidevelopmentgetstarted relnofollowhttpjdownloaderorgknowledgewikidevelopmentgetstarteda
svnsvnjdownloaderorgjdownloadertrunkp
| 0 |
combine two lists of lists into a dictionary python | pim not sure if it could work with your code but give it a tryp
precodeprint tuplekv for kv in zipsentencesen sentencesde
codepre
| 0 |
saleorderline quantity update | phave you tried recurring invoice module from openerp as it is more easy to do recurring billing using it instead of making something from a scratchp
pcheers
parthivp
| 0 |
how visualize output cluster with each cluster unique colors | pright now codecolor nprandomrandclusternumcode is generating three random numbers and in codeaxscatterxi0 xi1 xi2 ccolorlabelsicode you are trying to assign those random numbers as colors p
pinstead you can change codecolor g r bcode so that first cluster will be green second will be red and third will be bluep
pfor cluster centers pass the same parameterp
precodeaxscattercentroids 0centroids 1 centroids 2 marker x s150 linewidths 5 zorder 100 ccolor
codepre
pa hrefhttpistackimgurcomdtnqgpng relnofollowimg srchttpistackimgurcomdtnqgpng altenter image description hereap
| 0 |
getting gcc failed error while installing scrapy | pon fedora 23 i had to install the following packages for code pip install scrapycode to complete successfullyp
precodesudo dnf install pythondevel libxml2devel libxsltdevel libffidevel libffidevel
codepre
pif the setup process complains about a missing file for examplep
precodefatal error opensslopensslvh no such file or directory
compilation terminated
error command gcc failed with exit status 1
codepre
pdo code dnf provides filenamecode emdnf provides opensslopensslvhem to find the required package and install itp
| 0 |
i just downloaded aptana studio 3 in windows 81 pro with java sdk | ptry cusersappdataroamingappceleratorp
pthat is where i found it i had the same problem i also just put emaptanem into the search input field and let the system do its thingp
| 0 |
async function call in python | pi would simply use a hrefhttpdocspythonrequestsorgenlatest relnofollowrequesta and a hrefhttpwwwgeventorg relnofollowgeventa called a hrefhttpspypipythonorgpypigrequests relnofollowgrequestsap
precodeimport grequests
gtgtgt urls
http
http
gtgtgt rs grequestsgetu for u in urls
gtgtgt grequestsmaprs
ltresponse 200gt ltresponse 200gt
codepre
| 0 |
install newest version of one private library in a requirementstxt file | pthe simple solution is to remove the version pinning for the package each time the requirements file is run the latest version will be installedp
| 0 |
choose specific exit node in tor with python code | pok i think i have an answer it is not exactly what i intended but it works just as wellp
pi can have a more then one tor relays on my machine and configure each one with the exit node i want in the torrc file like a hrefhttpstackoverflowcomusers361267robertdaveyrobert daveya mentioned in my python script i can create a few processes and connect each one with a different relay thus giving me a different exit node an example can be found here
a hrefhttptorstackexchangecomquestions327howmayirunmultipletorrelayinstancesinasinglelinuxmachinehttptorstackexchangecomquestions327howmayirunmultipletorrelayinstancesinasinglelinuxmachineap
pif i want to change an exit node in an already running relay i can edit the torrc file of the relevant tor relay and update it with the sighup signal using stem python libraryp
precodefrom stem import signal
from stemcontrol import controller
with controllerfromportport 9051 as controller
controllerauthenticate
controllersignalsignalhup
codepre
| 0 |
python updating one key of the pair adding the previous value to the new one dictionaryhash | ptry this when assigned to the dictionary see if the value exists and if it does not set it to 0 then add to itp
precodefor eachline in data
number grade eachlinesplit
if number not in nice
nicenumber 0
nicenumber intgrade
codepre
| 0 |
sequential searching of a database | pyour codesequentialsearchcode function isnt printing anything and you dont need the codefoundcode variable you can just codereturncode from the function when you find the matchp
precodedef sequentialsearchalbumlist item
for i in rangelenalbumlist
if albumlisti item
print titlelisti artistlisti albumlisti
print yearlisti commentlisti
return true
return false
codepre
pin your main code your codewhilecode loop will never end because you ask for codenumcode outside the loop usep
precodewhile true
num inputwhat would you like to don1 print all the contents of the databasen2 find all the songs on a particular albumn3 quitnplease enter 1 2 or 3
if num 3
print goodbye
break
elif num 1
func
elif num 2
item rawinputplease enter the album
sequentialsearchalbumlist item
else
print invald input
codepre
| 0 |
why does the python slice syntax not wrap around from negative to positive indices | pstrongfirst you need to know that slicing in python is from left to rightstrong so when you try code31code or code11code result is empty you can suppose that every entry in list have 2 index that shows in below for exam
ple if we have a list with 4 entry this is the indexes numbers p
precode01234
codepre
porp
precode5431
codepre
pfor complete understanding of slicing read have a look at here a hrefhttpstructureuscedunumarraynode26html relnofollowhttpstructureuscedunumarraynode26htmla p
| 0 |
issues in installing packages on webfraction | pfor instance lets say you want to install djangohaystack 200 on webfaction using pip you could do the following pwd does not work i think p
precodepip27 install djangohaystack200 installoptioninstallscriptshomeyouraccountwebappsyourdjangoappbin installoptioninstalllibhomeyouraccountwebappsyourdjangoapplibpython27
codepre
| 0 |
can we find the local classname of an object instantiated from a class imported with import as | ptheres a really terrible answer to my own question i wont be accepting this since its probably pretty fragile i only tested for a limited set of call circumstances i mostly just hunted this down for the challenge i will most likely be using something more durable for my actual use casep
pthis assumes we have access to the stronginitstrong function of the class were trying to import as blah and some sort of persistent external data store at least for more complicated edge casesp
precodeimport inspect dis
class idiomobject
description none
alias none
def initself desc
global dataob
selfdescription desc
if selfclassname idiom
cheat like hell to figure out who called us
selfalias dataobnameidiominspectcurrentframefback
else
selfalias selfclassname
class dataobobject
code none
locations
loadname 101
codelen none
def nameidiomself frame
if not selfcode
selfcode framefcode
selfcodelen lenselfcodecocode
selflocations yx for x y in disfindlinestartsselfcode
targetline frameflineno
addrindex selflocationstargetline1
nameindex selfcodecocodeaddrindex
theres a chance well get called again this line
so we want to seek to the next loadname instance101
addrindex 1
while addrindex lt selfcodelen
if selfcodecocodeaddrindex selfloadname
selflocationstargetline addrindex
break
addrindex 1
return selfcodeconamesnameindex
codepre
pthe short explanation of how this works isp
ul
liwe look up the previous frame from the init functionli
liobtain the code objectli
lifind bytecode locations for the start of every line in the codeli
liuse the linenumber from the frame to grab the bytecode location for the start of that lineli
lilocate a loadname indicator in the bytecode for this line i dont really follow this my code assumes itll be there li
lilook in the next bytecode position for an index which indicates which position in the codeconames tuple contains the name of the loadname callli
ul
pfrom here we can do something likep
precode>>> from rabbit_hole import idiom as timer_bob
>>> with timer_bob("down the rabbit hole"):
... waste_some_time = list(range(50000))
...
timer_bob: down the rabbit hole
runtime: 0:00:00.001909, children: 0:00:00, overhead: 0:00:00.001909
</code></pre>
| 0 |
break out of a while loop using a function | pthe way to end a whiletrue loop would be to use codebreakcode furthermore the codebreakcode must be in the immediate scope of the loop otherwise you could utilize exceptions to hand control up in the stack to whatever code handles itp
pyet oftentimes its worth considering another approach if your example is actually close to what you really want to do namely depending on some user prompt input id do it like thisp
precodeif rawinputcontinue yn y
print you wish to continue then
else
print abort as you wished
codepre
| 0 |
calculating a directory size using python | pa little late to the party but in one line provided that you have a hrefhttpspypipythonorgpypiglob2 relnofollowglob2a and a hrefhttpspypipythonorgpypihumanize relnofollowhumanizea installed note that in python 3 the default codeiglobcode has a recursive mode how to modify the code for python 3 is left as a trivial exercise for the readerp
precodegtgtgt import os
gtgtgt from humanize import naturalsize
gtgtgt from glob2 import iglob
gtgtgt naturalsizesumospathgetsizex for x in iglobvar
5462 mb
codepre
| 0 |
retain formatting | pcodereturn hreadcode would return the files contents as a single string and therefore retain formatting if thats printed as you put it what other constraints do you have on the return value of the peculiarlynamed codeprintfilecode peculiarly indeed because it doesnt emprintem anythingp
| 0 |
python module to listen for wsgi requests from apache | ppython has a built in wsgi server in the codewsgirefcode module suitable for development and testing purposes though probably not for production uses for example using the also provided example wsgi appp
precodegtgtgt import wsgirefsimpleserver
gtgtgt server wsgirefsimpleservermakeserver0000 8888 wsgirefsimpleserverdemoapp
gtgtgt serverserveforever
127001 21jul2016 004404 get http11 200 2664
127001 21jul2016 004405 get faviconico http11 200 2615
127001 21jul2016 004405 get faviconico http11 200 2675
ctraceback most recent call last
file ltipythoninput530934a6743d8gt line 1 in ltmodulegt
serverserveforever
file usrlocalcellarpython27102frameworkspythonframeworkversions27libpython27socketserverpy line 236 in serveforever
pollinterval
file usrlocalcellarpython27102frameworkspythonframeworkversions27libpython27socketserverpy line 155 in eintrretry
return funcargs
keyboardinterrupt
gtgtgt
codepre
| 0 |
accessing firefox 3 cookies in python | pi created a module to load cookies from firefox available here a hrefhttpsbitbucketorgrichardpenmanbrowsercookie relnofollowhttpsbitbucketorgrichardpenmanbrowsercookieap
pexample usagep
precodeimport requests
import browsercookie
cj browsercookiefirefox
r requestsgeturl cookiescj
codepre
| 0 |
best way of linking to a page in django | pcreate a new url in the same format and give that name instead of indexp
pegp
precodeurlr index nameindex
urlrnewpage new namenewpage
url newpage
codepre
| 0 |
turbogears loads page twice | pfinally the problem was in the templates if there is nonvalid javascript or cant be downloaded the page gets loaded twice second time without the broken javascript just remove the javascript from the template and it works finep
pin my case there was something wrong in the a hrefhttpflexiejscom relnofollowflexiejsap
| 0 |
Subsets and Splits