text_a
stringlengths 9
150
| text_b
stringlengths 18
20.9k
| labels
int64 0
2
|
---|---|---|
how to minimize stringappending to one line in python | plist comprehensionp
precodegtgtgt y a1 b1 a2 b2
gtgtgt i if i0 a else asi for i in y
a1 ab1 a2 ab2
codepre
pyour examplep
precodegtgtgt y alligator pple banana
gtgtgt i if i0 a else asi for i in y
alligator apple abanana
codepre
| 0 |
iterating through twos list of lists in python | precodefor i in rangelenl
for j in range lena
codepre
pcodeicode and codejcode here are both of type codeintcode if you want them to be elements in codelcode and codeacode usep
precodefor i in l
for j in a
codepre
paccordingly changep
precodenewlistappendli0 aj0
codepre
ptop
precodenewlistappendi0 j0
codepre
pthe code runs now however the result is not expected which would need more workp
| 0 |
replacing an escaped single quote with an escaped double quote in python | ol
lireplace all the into a magic wordli
lireplace all the into li
lireplace all the magic words back to li
ol
| 0 |
python getting calling modules path via traceback problems | pto find the location of a module function or class use the codeinspectcode modulep
precodeimport inspect
printinspectgetsourcefilesomemodule
codepre
pyou can use this to find the location of the code units you are interested in if you put this in a library just wrap it in a function that takes an argument p
pactually you could do the same with codefilecode if necessary just pass it as the argument to a function that will do the restp
| 0 |
is there a python equivalent of the prefuse visualization toolkit | pa hrefhttpmayavisourceforgenet relnofollowmayaviap
| 0 |
modwsgi reading posted file content remains empty | pokay heres the solutionp
pi cant explain it but the file form fields get emptied on first read which i found out by accident maybe a bug who knows
i assumed that they would stay intact like any other variable and can be read multiple timesp
pwhat i ignored was that i had in fact addressed them several times
so the solution was to first store the files content in a variable and then use that multiple timesp
| 0 |
typechecking in functions between python 27 and python 33 | pfrom a hrefhttpdocspythonorg31whatsnew30htmlintegers relnofollowhttpdocspythonorg31whatsnew30htmlintegersap
pthe sysmaxint constant was removed since there is no longer a limit to the value of integers however sysmaxsize can be used as an integer larger than any practical list or string index it conforms to the implementations natural integer size and is typically the same as sysmaxint in previous releases on the same platform assuming the same build optionsp
precodeif not isinstancen int or n gt sysmaxsize raise typeerrorn must be int
codepre
pmay work for differentiating int and longp
| 0 |
why is scipysparselinalgeigsh giving the wrong answer | pwhile sorting by absolute values as suggested by hyry gives the same result for both tests it still is unsatisfying since the my underlying intent was to get the largest eigenvalues from my matrix for real symmetric matrices i thought codeeigshcode would return the largest eigenvalues it doesnt it returns the largest eigenvalues strongsorted by magnitudestrong p
| 0 |
use your own colour for plots with guiqwt in python | psure i dont see the problem in your code i dont know the guiqwt module but try using matplotlib a hrefhttpmatplotlibsourceforgenetapicolorsapihtml relnofollowhttpmatplotlibsourceforgenetapicolorsapihtmlap
pyou can also try this color tablep
precode from pyqt4 import qtcore qtgui
red qtguiqcolor200 0 0
green qtguiqcolor0 200 0
blue qtguiqcolor0 0 200
black qtguiqcolor0 0 0
white qtguiqcolor255 255 255 0
codepre
| 0 |
getting dry with python conditionals and django returns | pi notice that your last return is conditional and guess based on my own similar code that if neither of the checks triggers you want to go on and return something else maybe not even a redirect p
pheres how i think i would do itp
precodedef checkformessage
if status active and presult 0
return active message bla bla bla
if status too many failures
return failed foooobarrrrr
if status deactivated by merchant
return deactivated derpa derp
return none
msg checkformessage
if msg
messagesaddmessagerequest messageserror msg
return httpresponseredirectreversebillingupdate
go on and do some other stuff
return directtotemplatesometemplatehtml some stuff
codepre
pnote that the function checkformessage is defined inside the view function so we dont have to pass everything involved in a test as a parameter to it in case the tets are many and varied if they just require a status and some p variable it can just as well be declared outside the view function and take those parametersp
pthe main point is that the fall through alternative where we dont want to add any message at all can be handled by returning none in the check method and checking for the existence of a message in the view methodp
| 0 |
concurrent remote procedure calls to c object | pmaybe factors can affect the selectionp
pone solution is to use fastcgip
pclient sends http request to http server that has fastcgi enabled
htp server dispatch the request to your rpc server via the fastcgi mechanism
rpc server process and generates response and sends back to http server
http server sends the response back to your clientp
| 0 |
open an ssh tunnel from heroku python app on the cedar stack | pthis recipe ought to work with python even though it was for a rails app heres the recipe a hrefhttpstackoverflowcoma27361295558639httpstackoverflowcoma27361295558639ap
pthe biggest challenge is convincing ssh to not prompt when it starts upp
| 0 |
creating multiple objects of model using one button in django | pyou can use codebulkcreatecode method introduced in django 14 p
precodeaccesscodeobjectsbulkcreateaccesscode for i in range100
codepre
phowever there are some problems with this approach from django docp
blockquote
pthis has a number of caveats thoughp
precode the models save method will not be called and the presave and postsave signals will not be sent
it does not work with child models in a multitable inheritance scenario
if the models primary key is an autofield it does not retrieve and set the primary key attribute as save does
codepre
blockquote
pto add action to admin page please check a hrefhttpstackoverflowcoma149204852074398this answera with details how to do itp
| 0 |
how can remove a message specific of a file python | pinstead of redirecting the standard output of your process to a file by changing sysstdout you need to write your data to the file directly you can do it for example like thisp
precodeprint gtgt logfile s resi
codepre
por like thisp
precodelogfilewritestrresi
codepre
pthis will ensure that your file will not contain random unrelated data that happens to be printed to the standard outputp
| 0 |
printing values in multiple arrays coming out a jarbled mess | pit looks like you are trying to output json instead of building a string why not create a list of dictionaries and dump it to json via something like thisp
precodeimport json
list1
for x in rangei
list1append
name value
print jsondumpslist1 indent4
codepre
| 0 |
python loop in parallel | pif you want to do things in parallel well you have to run them in parallel i think the reason why youre only seeing a 20 speed boost is because of the cost of creating and joining processes is quite high and chewing into the performance benefit you get from multiprocessing this degraded speed increase is to be expected since there is a cost associated with creating and joining processes try something more time consuming and youll notice the 20 rise to a more expected amountp
palso if your bottleneck is the cpu isnt able to run multiple processes shouldnt really happen nowadays with the dualquad core cpus you might not even notice a speed boost since theyre still being run serially at the hardware levelp
| 0 |
how to read a tag from pn532 in python | pi did found a way that might be partially correct since eugenes answer does not provide a definitive way that we know will work it cannot be considered a full answer so i will most probably accept this one if nothing else changesp
pfirst of all since the empn532em does not continuously monitor for signals and emits data we will have to program it the usual way in order for it to behave according to what we want to achievep
pthis can be done using the same a hrefhttpwwwarduinoccenmainsoftware relnofollowsoftwarea that you program any other emarduinoem device p
pmake sure you have chosen the correct port from the tools menu if you dont know which port is that in windows go to codestartgtall programsgtaccessoriesgtsystem toolsgtsystem informationgtcomponentsgtportsgtserialcode for linux going to codedevserialbyidcode should do p
pthen i would recommend using the examples provided by the manufacturer a hrefhttpsgithubcomadafruitadafruitnfcshieldi2c relnofollowherea make sure you choose the right connection type or else you will see no data coming from the device most probably you will want i2cp
ponce that is done and your device emits data each time a emtagem is used on it check with a serial terminal configured at 115200 baud rate then you are ready to start working with pythonp
pagain i recommend a hrefhttppyserialsourceforgenet relnofollowthisa module to read your data from the serial port it even comes with a ready to use example of a emwxwidgetsem terminal to read your data from the empn532em if of curse you use another python library and you think its better do say so in the commentsp
| 0 |
where comes the output message when submitting a python file to spark using sparksubmit | pposting my answer here since i didnt find them elsewhere p
pi first tried
yarn logs applicationid applicationidxxxx
was told that log aggregation has not completed or is not enabledp
phere comes the steps to dig out the print messagep
precode1 follow the link at the end of the execution http17231341249046proxyapplication14387240517970007a here reverse ssh and proxy needs to be setup
2 at the application overview page find out the appmaster node id ip17231416ec2internal9035
3 go back to aws emr cluster list find out the public dns for this id
4 ssh from the driver node into this appmaster node same keypair
5 cd varloghadoopuserlogsapplication14387963042150005container1438796304215000501000001 always choose the first container
6 cat stdout
codepre
pas you can see its very convoluted probably will be better off to write output into a file hosted in s3p
| 0 |
dynamically adding keyarguments to method | pfor the sake of closure i give the only solution that was found use codeexeccode
proposed by strongmgilsonstrongp
precodeimport os new
class dynamickargsobject
class that makes a run method with same arguments
as those given to the constructor
def initself kargs
kargrepr joinstrkeyreprvalue
for keyvalue in kargsiteritems
exec def runself kargrepr kargsn return selfrun kargrepr kargs
selfrun newinstancemethodrun self
def runself kargs
print kargs
this can also be done with a function
def runkargs
print kargs
def dynamickargskargs
kargrepr joinstrkeyreprvalue for keyvalue in kargsiteritems
exec def run kargrepr kargsn return run kargrepr kargs
return run
example of use
def example
dynkargs dynamickargsquestionultimate answer42
print class example n
print var number dynkargsrunimfuncfunccodecoargcount
print var names dynkargsrunimfuncfunccodecovarnames
print defaults dynkargsrunimfuncfuncdefaults
print run print
dynkargsrun
print
dynkargs dynamic_kargs(question='foo', answer='bar')
print 'function example \n----------------'
print 'var number:', dyn_kargs.func_code.co_argcount
print 'var names: ', dyn_kargs.func_code.co_varnames
print 'defaults: ', dyn_kargs.func_defaults
print 'run print: ',
dyn_kargs()
</code></pre>
<p>the <code>example</code> function prints:</p>
<pre><code>class example
-------------
var number: 3
var names: ('self', 'answer', 'question', 'kargs')
defaults: (42, 'ultimate')
run print: {'answer': 42, 'question': 'ultimate'}
function example
----------------
var number: 2
var names: ('answer', 'question', 'kargs')
defaults: ('bar', 'foo')
run print: {'answer': 'bar', 'question': 'foo'}
</code></pre>
<p>however:</p>
<ul>
<li>there might be problem if arguments value are not well represented by their <code>repr</code></li>
<li>i think it is too complicated (thus not pythonic), and personally, i did not use it</li>
</ul>
| 0 |
python how to compute date ranges from a list of dates | pmy slight variation on the theme i originally built startend lists and zipped them to return tuples but i preferred karl knechtels generator approachp
precodefrom datetime import date timedelta
oneday timedeltadays1
def finddatewindowsdates
guard against getting empty list
if not dates
return
convert strings to sorted list of datetimedates
dates sorteddatemapintdsplit for d in dates
build list of window starts and matching ends
laststart lastend dates0
for d in dates1
if dlastend gt oneday
yield startdatelaststart enddatelastend
laststart d
lastend d
yield startdatelaststart enddatelastend
codepre
phere are the test casesp
precodetests
20110227 20110228 20110301 20110412 20110413 20110608
20110608
20110227 20110228 20110301 20110412 20110413 20110608 20110610
for dates in tests
print dates
for window in finddatewindowsdates
print window
print
codepre
pprintsp
precode20110227 20110228 20110301 20110412 20110413 20110608
startdate datetimedate2011 2 27 enddate datetimedate2011 3 1
start_date': datetime.date(2011, 4, 12), 'end_date': datetime.date(2011, 4, 13)}
{'start_date': datetime.date(2011, 6, 8), 'end_date': datetime.date(2011, 6, 8)}
['2011-06-08']
{'start_date': datetime.date(2011, 6, 8), 'end_date': datetime.date(2011, 6, 8)}
[]
['2011-02-27', '2011-02-28', '2011-03-01', '2011-04-12', '2011-04-13', '2011-06-08', '2011-06-10']
{'start_date': datetime.date(2011, 2, 27), 'end_date': datetime.date(2011, 3, 1)}
{'start_date': datetime.date(2011, 4, 12), 'end_date': datetime.date(2011, 4, 13)}
{'start_date': datetime.date(2011, 6, 8), 'end_date': datetime.date(2011, 6, 8)}
{'start_date': datetime.date(2011, 6, 10), 'end_date': datetime.date(2011, 6, 10)}
</code></pre>
| 0 |
rss feed parser library in python | pif you want an alternative try xmldomminidom
like django is python rss is xmlp
| 0 |
pygame not checking keyevents after another happens | pi think what you need is thisp
precodeif keypressedpygamekleft
movementx 5
if eventtype pygamekeyup
if eventkey pygamekleft and movementx lt 0
movementx 0
if keypressedpygamekright
movementx 5
if eventtype pygamekeyup
if eventkey pygamekright and movementx gt 0
movementx 0
codepre
pand that would be it hope it helpsp
| 0 |
how to prevent a race condition when multiple processes attempt to write to and then read from a file at the same time | puse strikepidstrike an empty file to lock every time you access a file p
pexample usagep
precodefrom mercurial import error lock
try
l locklocktmp0lockformatfilename timeout600 wait at most 10 minutes
do something
except errorlockheld
couldnt take the lock
else
lrelease
codepre
psource a hrefhttpstackoverflowcomquestions1444790pythonmoduleforcreatingpidbasedlockfilepython module for creating pidbased lockfileap
pthis will give you a general idea this method is used in oo vim and other applications p
| 0 |
replace single quotes with double quotes in python for use with insert into database | precodewhile line
restrain line2 to inside parentheses
line1 rest linesplit
line2 line3 restsplit
a bit more cleaner
newbits
for bit in line2split
remove border characters
bit bit11
duplicate the ones inside
if in bit
bit bitreplace
readd border
newbitsappend bit
sysstdoutwriteline1 joinnewbits line3
line fileinreadline
codepre
| 0 |
date range filter in django | puse the coderangecode lookupp
precodeenquirylist modelnameobjectsfilterdatepostedrangestartdateenddate
codepre
| 0 |
mathgroup error from regex tuples in python | prefinallp
blockquote
preturn a list of all nonoverlapping matches in the stringp
blockquote
pyou probably want p
precodefor mp yards in matchloc
yards intyards
if yards gt 130
codepre
| 0 |
avoid rounding float in python | pwhen i ran into a similar problem because of converting millisecond references to microseconds i had to convert to a string and loop over the string adding the needed 0s until the length of the string was correct then when the value was converted back to integer the calculations workedp
precodethe data will be passed to strptime as as string
vals valssplit a fractional part of the seconds
nofrag frag vals
length lenfrag
this converts the fractional string to microseconds given unknown precision
if length gt 6
frag frag05
else
while length lt 6
frag frag 0
length 1
strptime requires even seconds with microseconds added later
nofragdt dtdatetimestrptimenofrag ymd hms
dt nofragdtreplacemicrosecondintfrag
return dt
codepre
| 0 |
python datetime strptime valueerror does not match format | pthis wayp
precodetext 06082016
format mdy
date datetimedatetimestrptimetext formatdate
codepre
| 0 |
python how to join elements in a list that are separated by a certain value | pno need for list comprehension just find your delimiters and concatenate the restp
precodea 1 2 3 c 4 c 5 6 7 c 8
firstindex aindexc
revertedlastindex a1indexc index in reverted list
lastindex lena 1 revertedlastindex 1 for 0indexed lists
codepre
pso we can now just join the part of list between codefirstindexcode and codelastindexcode and just concatenate the rest p
precodenewlist afirstindex joinafirstindexlastindex alastindex
codepre
pedit by no need for list comprehension i mean of course no need for emexplicitem iteration the codeindexcode function does it internallyp
| 0 |
installing error with graphlab in ubuntu | pthat error often happens because graphlabcreate is installed in a different environment than the one youre working in are you using miniconda or virtualenv by any chance if so make sure to activate your working environment then download and install graphlabcreate then import in ipython jupyter notebook etcp
| 0 |
django admin add a custom link that runs a a function in a pop up next to a particular field | pyou can achieve it by writing javascript code in a file customjsp
precodefunction
function findfreeip
ajax
url customfindfreeip
success functionresponse
inputidfieldnamevalresponse
documentreadyfunction
inputidfieldnameafter lta hrefjavascript findfreeipgtfind free ipltagt
thisjquery
codepre
padd below line in your settingspy if not already therep
precodestaticfilesdirs ospathjoinbasedir static
codepre
pcreate a folder static in the same folder which has your app for simplicity and tracking create codestaticappnamejscustomjscodep
pin your formspy add below line in the showroom data formp
precodeclass media
js appnamejscustomjs
codepre
pnow all you have to do is to write a custom view to return ip addressp
pnote dont forget to add codeloginrequiredcode in your custom view and do proper validations in case this is role based functionalityp
| 0 |
python rock paper scissors game not always give correct answers | pyou almost had it correct as has been mentioned for each game the call to codecomputercode should only be made once it would also make sense to display the two players choices also as you are working in title case it would make sense to convert everything to use that to avoid needing to call codetitlecode so many timesp
precodeimport random
options rock paper scissors
then check if the user loses wins ties
def computer
return randomchoiceoptions
printn11
printwelcome to rock paper scissors
print game
print its you vs the computer
print11
while true
userchoice inputnwhat do you choose rock paper scissors title
computerchoice computer
printuser computer formatuserchoice computerchoice
if userchoice in options
possible userchoice time a userchoice can succeeds rock beats sicissor sicissors cuts paper paper covers rock
if userchoice computerchoice
printtie
elif userchoice rock and computerchoice scissors
printyou won crushes formatuserchoice computerchoice
elif userchoice scissors and computerchoice rock
printcomputer won crushes formatcomputerchoice userchoice
elif userchoice scissors and computerchoice paper
printyou won cuts formatuserchoice computerchoice
elif userchoice paper and computerchoice scissors
printcomputer won cuts formatcomputerchoice userchoice
elif userchoice paper and computerchoice rock
printyou won } covers {}".format(user_choice, computer_choice))
elif user_choice == 'rock' and computer_choice == 'paper':
print("computer won! {} covers {}".format(computer_choice, user_choice))
else:
print("make sure you choose either rock, paper or scissors")
</code></pre>
<p>so a game would look like:</p>
<pre><code>-=--=--=--=--=--=--=--=--=--=--=-
welcome to rock, paper, scissors
game
it's you vs. the computer!
-=--=--=--=--=--=--=--=--=--=--=-
what do you choose rock, paper, scissors: rock
user: rock computer: scissors
you won! rock crushes scissors
</code></pre>
| 0 |
execfile for configuration error no such file or directory | ol
lii would rename codemyconfigcfgcode to codemyconfigpycodeli
libe sure that your config file and the file trying to get the data are in the same folderli
listrongmyconfigpystrongli
ol
pcodedictionarydata1value1data2value2codep
p4import the datap
pcodefrom myconfig import dictionary
print dictionarycodep
| 0 |
raise exception and halt execution in python c api code | ppv on a hrefhttpsgithubcomscipyscipyissues2570 relnofollowthis github issue for scipya explained what the issues are in short setjump and longjump in c could do this in principle but this is errorprone notably not being threadsafe this may be of use in other similar applications but using f2py is generally the better way to get fortran code to communicate with pythonp
| 0 |
caffe netpredict outputs random results googlenet | pplease check the image transformation you are using is it the same in training and testtimep
pafaik bvlcgooglenet subtract image mean with one value per channel while your python codeclassifiercode uses different mean codemeannploadilsvrc2012meannpymean1mean1code this might cause the net to be unable to classify your inputs correctlyp
| 0 |
plot marginal for xaxis | pi think you need to call codeaxautoscaleviewcode after setting the margins an after the plotting 075 is a lot of margin thoughp
precodeimport numpy as np
import matplotlibpyplot as plt
import datetime
import matplotlibdates as mdates
today datetimedatetoday
imsidate datetimedate2016 1 11 datetimedate2016 1 14 datetimedate2016 1 18
imsiup 13 6 24
imsidown 4 23 1
ax pltsubplot
axxaxisdate
axyaxisgrid
plotup axbarimsidate imsiup width075 colorr aligncenter
plotdown axbarimsidate imsidown width075 colory aligncenter bottomimsiup
axxaxissetmajorformattermdatesdateformatterymd
axxaxissetminorlocatormdatesdaylocator
limits
t0 today datetimetimedelta7
t1 today
axsetxboundt0 t1
axsetxmargin075
axautoscaleview lt this
pltxticksrotationvertical
pltsubplotsadjustbottom025
pltshow
codepre
pa hrefhttpistackimgurcomewwewpng relnofollowimg srchttpistackimgurcomewwewpng altenter image description hereap
| 0 |
how to find url containing one word and another using re in python | precodegtgtgt import re
gtgtgt precompilehttpsfirstlevelssecondlevelshtml
gtgtgt text random text httpwwwdomaincomfirstlevel020213secondlevelslughtml more random text httpwwwdomaincomlevelone020213secondlevelslughtml
gtgtgt i pfinditertext
gtgtgt for m in i
printmgroup
httpwwwdomaincomfirstlevel020213secondlevelslughtml
gtgtgt
codepre
phthp
| 0 |
how to stop python from printing commas from a csv file | pyoure outputting the file the same way as it is on disk if you want to parse the file you should check out the a hrefhttpsdocspythonorg2librarycsvhtml relnofollowcsv modulea of pythonp
| 0 |
windows gstreamer alsa alternative | pnot sure if this is still relevant but i had the exact same problem today i got around it by using autoaudiosinkp
pthat way i got the minimal example on the following website to work in windows xpp
pa hrefhttpwwwjonobaconorg20060828gettingstartedwithgstreamerwithpython relnofollowhttpwwwjonobaconorg20060828gettingstartedwithgstreamerwithpythonap
phere is my version of the code essentially the same except for the alsasinkp
precodeusrbinpython
import pygst
pygstrequire010
import gst
import pygtk
import gtk
class main
def initself
selfpipeline gstpipelinemypipeline
selfaudiotestsrc gstelementfactorymakeaudiotestsrc audio
selfpipelineaddselfaudiotestsrc
selfsink gstelementfactorymakeautoaudiosink sink
selfpipelineaddselfsink
selfaudiotestsrclinkselfsink
selfpipelinesetstategststateplaying
startmain
gtkmain
codepre
pi hope that helpsp
| 0 |
htmltotext conversion using python standard library only | pi would also suggest that you should take a look at a hrefhttpwwwaaronswcom2002html2text relnofollowhtml2texta br
also take a look at another a hrefhttpstackoverflowcomquestions328356extractingtextfromhtmlfileusingpythonthreadap
| 0 |
how do i add the trustedhost in pycharm package install | pafter some digging i found the answer registering it here in case someone is interestedp
pgo to emfileem emsettingsem project emnameoftheprojectem emproject interpreterem choose double click the package you want to update and the emavailable packagesem will popup there is a checkbox emoptionsem on the lowerleft part of the window check that and enter emtrustedhostem option and hit the eminstall packageem buttonp
pthat way i was able to update the package from the insecure host thus solving my problemp
| 0 |
delete fulfilling condition row from a file | pa python solution to this would bep
precodefile openmyfiletxt
file2 openmyfile2txt a
for i line in enumeratefile
strlist linesplit
if not strlist2 strlist3 and strlist7 inf
file2writeline
fileclose
file2close
codepre
pthis assumes that the values are separated by spacesp
| 0 |
find currency code in price string | pits veryvery ghetto butp
precodeimport string
filter stringdigits
currency ch for ch in s if ch not in filter0
codepre
| 0 |
how to add methods to customised searchfields in django adminmodeladmin | pdjango is not able to search on properties as youve discovered however you can simply add the codefirstnamecode and codelastnamecode fields to your codesearchfieldscode and it will work as expectedp
pif youre needing to do exact matching on the entire name value my recommendation would be to add a denormalized field perhaps called codefullnamecode that is kept in sync via a postsave signalp
| 0 |
how do most people do consolelog debugging in python | pthe expectation is that you a hrefhttpsdocspythonorg2howtologginghtmlusingarbitraryobjectsasmessages relnofollowimplement your own codestrcode methoda so that you can pick what is important to log in your diagsp
phowever there is the option to log the whole object dictionary in a pretty format using a couple of lines of code for examplep
precodefrom pprint import pformat
class aobject
def initself
selffoo 1
selfbar hello world
selfprivate 0
a a
print pformatvarsa
you can also pass pformat to your logger if thats what you have
codepre
pthis will return something like this depending on how much data you have and thw codewidthcode constraintp
precodeprivate 0
bar hello world
foo 1
codepre
| 0 |
i need to add a to my output of denominations used | pcan you add a codecode to your codeprintcode statementp
precodeprint0 2d182fformatamountdenomiuseddenomiend
codepre
porp
precodeprint0 2d 182fformatamountdenomiuseddenomiend
codepre
pyou can place the codecode wherever you wish within the string you can also add any other characters eg codecode or codecode within the stringp
pto remove white spaces around the variables use codestripcodep
precodeprint0 2d 182fformatamountdenomistripuseddenomistripend
codepre
pif codeamountdenomcode and codeuseddenomcode are not strings first convert using codestrcodep
precodeprint0 2d 182fformatstramountdenomistripstruseddenomistripend
codepre
| 0 |
using a post request to grab filtered data from python flask and update current webpage | pone easy option is to have a div for your content that you filter dynamically when you first hit the route it will just render all content without any filters when you change your filter it will remove that content and replace it with the results of your filterp
pworking off your codep
precodejobsearchform selectnamefilterchangefunction ev
get the filters
var container datacontainer
postapijobsearch function data
containerempty empty the current contents
dataeachfunction job
containerappendjobname
codepre
pthis is just a brief example to show concept i would recommend choosing a front end framework to make the containment of data on the front end more manageablep
| 0 |
how to write a python script to manipulate google spreadsheet data | pgspread is probably the fastest way to begin this process however there are some speed limitations on updating data using gspread from your localhost if youre moving large sets of data with gspread for instance moving 20 columns of data over a column you may want to automate the process using a cron jobp
| 0 |
find if background image is used for any html tag with inline style | paccording to a hrefhttpwwwxmlmecomxpathtoolaspx relnofollowxmlmecoms xpathtoola this xpath should workp
precodecontainsstylebackgroundimage
codepre
phere is my test resultp
pimg srchttpistackimgurcoms315kpng altenter image description herep
| 0 |
how to switch nodes at an index with the head of a list | pswitching elements in a list is actually very easyp
precodemylist0 mylist1 mylist1 mylist0
codepre
pthis will swap the first and second elements in codemylistcode in place python actually has an optimized bytecode command that very quickly swaps two values on the program stack so this is about as fast as you can swap list valuesp
pof course in that case you wouldnt be returning a new list youd be modifying the old one so instead of codemylist switchmylist 2code you would just write codeswitchmylist 2code the code would look something like thisp
precodedef switchlst i
lst0 lsti lsti lst0
codepre
pif you want to return an entirely new list youd need to make a copy firstp
precodedef switchlst i
newlst listlst
newlst0 newlsti newlsti newlst0
return newlst
codepre
pedit if youre working with a linked list that is a bit of a different story i dont think python optimizations exist for linked lists regular lists are very easy to add items to and they work with any kind of object so linked lists very much lose their purpose in python nevertheless heres a suggestionp
precodedef switchll i
head ll
currentitem ll the head again
previtem none the item that links to tempitem
for x in rangei find the item to swap
previtem currentitem
currentitem currentitemnext
now we swap were rotating three items next values so we cant
do the really optimized way
temp currentitemnext
currentitemnext headnext
headnext previtemnext
previtemnext temp
codepre
plinked list manipulation is all about maintaining proper links to the next item also note that the above code will fail if youre trying to swap for a position that doesnt actually exist in your linked list check your inputsp
| 0 |
in what case would i use a tuple as a dictionary key | pyou use tuples as keys when you want to show multiple elements which form a key togetherp
peg codeltxcoordinategtltycoordinategt ltindicating lettergtcodep
phere if we use codexcoordinatecode or codeycoordinatecode separately we wouldnt be representing that pointp
| 0 |
format of time with sqlalchemy in flaskadmin and daterangepicker | palright i figure it outp
pi post my solution here
a hrefhttpsgithubcomflaskadminflaskadminissues1210 relnofollowhttpsgithubcomflaskadminflaskadminissues1210ap
| 0 |
ssl certificate verify failed sslc600 | pi dont know if this will work for you because i dont know your code but i had the same problem with this 4 lines my code work perfectp
pip
precodeimport request
disable ssl warning
requestspackagesurllib3disablewarnings
context sslsslcontextsslprotocoltlsv1
contextverifymode sslcertnone
codepre
pip
pwhen you connect set the parameter of sslcontext to context p
| 0 |
where to define a method that is used only inside init and must not be called anywhere else | pyou could get rid of it once youre donep
precodeclass lineobject
def initself
selflength none
selfassignvaluetolength
selfassignvaluetolength none
def assignvaluetolengthself
selflength 50
codepre
pthis isnt very good practice though instead id just add an assertionp
precode def assignvaluetolengthself
assert selflength is none
selflength 50
codepre
| 0 |
python making a readonly property accessible via varssomeclass | pif i understood you correct something like this should workp
precodeprint eval foobarformat dict v v for v in dir foo
codepre
pbut nevertheless this feels somehow very badp
| 0 |
how to interact with an external scriptprogram | pin fact ossystem and ospopen are now deprecated and subprocess is the recommended way to handle all sub process interactionp
| 0 |
python oswalk on a different computer on the same network | pmy thought is also to go for linux or at least windows with ssh servicep
ol
lia hrefhttpwwwpetefreitagcomitem532cfm relnofollowset up public key authentication over ssha and make sure you can ssh to that windows machine with ssh service on of course without password and password phraseli
limake use of a hrefhttpdocsfabfileorgen143indexhtml relnofollowfabrica a python 25 or higher library and commandline tool for streamlining the use of ssh for application deployment or systems administration tasksli
ol
| 0 |
how to change ticklabels within figure created with axisartist | pim not certain but it looks like youre doing something slightly different from what they are talking about in the documentation when they say you can use codeaxsetxtickscode like normal p
pi think that you might need to set the ticklabels at the time the axes are created when codegridhelpercurvelinearcode is called one of the keyword arguments is codetickformatter2code thats what you need to use first you need to import the formatter change p
precodefrom mpltoolkitsaxisartistgridfinder import maxnlocator
codepre
pto p
precodefrom mpltoolkitsaxisartistgridfinder import maxnlocator dictformatter
codepre
pcodedictformattercode takes a dictionary on initialization when the formatter is passed a location it looks in the dictionary to see if theres a corresponding string right now the locations are 0 25 5 75 1 lets say i want to change those to 5 10 15 20 25 i would create a dictionaryp
precoderlocs 0 25 5 75 1
rlabels 5 10 15 20 25
rticks loc label for loc label in ziprlocs rlabels
codepre
pnotice that coderlabelscode is a list of strings this is important codedictformattercode will throw an error if you try to use ints then i add the keyword argument coderlabels nonecode to codefractionalpolaraxescode and change the code inside a bitp
precodeif rlabels
rlabels dictformatterrlabels
gridhelper gridhelpercurvelineartr
extremesth0 th1 r0 r1
gridlocator1thetagridlocator
gridlocator2rgridlocator
tickformatter1thetatickformatter
tickformatter2rlabels
codepre
pnow i just need to call codefractionalpolaraxescode with the dictionary i madep
precodea1 fractionalpolaraxesf1 thlim(-90, 90),step=(10, 0.2),
theta_offset=90, rlabels = r_ticks)
</code></pre>
<p>and here's the result:</p>
<p><a href="http://i.stack.imgur.com/foyxz.png" rel="nofollow"><img src="http://i.stack.imgur.com/foyxz.png" alt="polar axes graph"></a></p>
<p>here's the entire code:</p>
<pre><code>from __future__ import division
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import affine2d
from matplotlib.projections import polaraxes
from mpl_toolkits.axisartist import angle_helper
from mpl_toolkits.axisartist.grid_finder import maxnlocator, dictformatter
from mpl_toolkits.axisartist.floating_axes import gridhelpercurvelinear, floatingsubplot
def fractional_polar_axes(f, thlim=(0, 180), rlim=(0, 1), step=(30, 0.25),
thlabel='theta', rlabel='r', ticklabels=true, theta_offset=0, rlabels = none):
'''return polar axes that adhere to desired theta (in deg) and r limits. steps for theta
and r are really just hints for the locators.'''
th0, th1 = thlim # deg
r0, r1 = rlim
thstep, rstep = step
tr_rotate = affine2d().translate(theta_offset, 0)
# scale degrees to radians:
tr_scale = affine2d().scale(np.pi/180., 1.)
#pa = axes(polar="true") # create a polar axis
pa = polaraxes
tr = tr_rotate + tr_scale + pa.polartransform()
theta_grid_locator = angle_helper.locatordms((th1-th0)//thstep)
r_grid_locator = maxnlocator((r1-r0)//rstep)
theta_tick_formatter = angle_helper.formatterdms()
if rlabels:
rlabels = dictformatter(rlabels)
grid_helper = gridhelpercurvelinear(tr,
extremes=(th0, th1, r0, r1),
grid_locator1=theta_grid_locator,
grid_locator2=r_grid_locator,
tick_formatter1=theta_tick_formatter,
tick_formatter2=rlabels)
a = floatingsubplot(f, 111, grid_helper=grid_helper)
f.add_subplot(a)
# adjust x axis (theta):
print(a)
a.axis["bottom"].set_visible(false)
a.axis["top"].set_axis_direction("bottom") # tick direction
a.axis["top"].toggle(ticklabels=ticklabels, label=bool(thlabel))
a.axis["top"].major_ticklabels.set_axis_direction("top")
a.axis["top"].label.set_axis_direction("top")
a.axis["top"].major_ticklabels.set_pad(10)
# adjust y axis (r):
a.axis["left"].set_axis_direction("bottom") # tick direction
a.axis["right"].set_axis_direction("top") # tick direction
a.axis["left"].toggle(ticklabels=true, label=bool(rlabel))
# add labels:
a.axis["top"].label.set_text(thlabel)
a.axis["left"].label.set_text(rlabel)
# create a parasite axes whose transdata is theta, r:
auxa = a.get_aux_axes(tr)
print(auxa)
# make aux_ax to have a clip path as in a?:
auxa.patch = a.patch
# this has a side effect that the patch is drawn twice, and possibly over some other
# artists. so, we decrease the zorder a bit to prevent this:
a.patch.zorder = -2
# add sector lines for both dimensions:
thticks = grid_helper.grid_info['lon_info'][0]
rticks = grid_helper.grid_info['lat_info'][0]
print(grid_helper.grid_info['lat_info'])
for th in thticks[1:-1]: # all but the first and last
auxa.plot([th, th], [r0, r1], ':', c='grey', zorder=-1, lw=0.5)
for ri, r in enumerate(rticks):
# plot first r line as axes border in solid black only if it isn't at r=0
if ri == 0 and r != 0:
ls, lw, color = 'solid', 1, 'black'
else:
ls, lw, color = 'dashed', 0.5, 'grey'
# from http://stackoverflow.com/a/19828753/2020363
auxa.add_artist(plt.circle([0, 0], radius=r, ls=ls, lw=lw, color=color, fill=false,
transform=auxa.transdata._b, zorder=-1))
return auxa
if __name__ == '__main__':
f1 = plt.figure(facecolor='white')
r_locs = [0, .25, .5, .75, 1]
r_labels = ['5', '10', '15', '20', '25']
r_ticks = {loc : label for loc, label in zip(r_locs, r_labels)}
a1 = fractional_polar_axes(f1, thlim=(-90, 90),step=(10, 0.2),
theta_offset=90, rlabels = r_ticks)
# example spiral plot:
thstep = 10
th = np.arange(-90, 90+thstep, thstep) # deg
rstep = 1/(len(th)-1)
r = np.arange(0, 1+rstep, rstep)
a1.plot(th, r, 'b')
plt.show()
</code></pre>
| 0 |
how to append a string to only consonants in a list | pi think the problem is in your approach to the problem
try to do something like this p
pedit although theres a better pythonic answer in this question thanks to dano this one does not require additional librariesp
precodevowels a e i o u
def oppishword
result
first true
prevvowel false
for letter in listword
if letter in vowels and not first and not prevvowel
resultappendop
prevvowel true
else
prevvowel false
resultappendletter
first false
if not prevvowel
resultappendop
print joinresult
oppishstreet
gt stropeetop
codepre
ptip dont waste your time defining both vowels and consonants in fact there are vowels and nonvowelsp
| 0 |
python how to connect to oracle database using jdbc | pas mentioned in the question the full path to the jar file for the jdbc driver must be present in either the classpath or the jythonpath environment variable so the jython script can find it these variables can be modified in several ways depending on the environment shell being used as described in the jata tutorial herep
pa hrefhttpdocsoraclecomjavasetutorialessentialenvironmentpathshtml relnofollowpath and classpathap
pin this particular case simply adding the line p
pre classlangnone prettyprintoverridecodeexport classpathusrliboracle121client64libojdbc6jar
codepre
pto one of the startup files eg bashprofile profile bashrc and then logging back in or running codesourcecode on the file was the solutionp
| 0 |
python django storing a class name to later instantiate an object | pyou can use the a hrefhttpsdocspythonorg2libraryfunctionshtmlglobals relnofollowcodeglobalscodea dictionary to do thisp
precodemyclass globalsfullyqualifiedclassname
codepre
pthen initialize an object using that classp
precodemyobject myclass
codepre
| 0 |
convert empty dictionary to empty string | pconvert each item in the dictionary to a string then join them with the empty stringp
precodegtgtgt joinmapstrd
codepre
| 0 |
class methods when overloading addition operator in python | pfor a better way take a look at codenumpypoly1dcode which is implemented as a function instead of a class something like this might suit your needsp
pre classlangpy prettyprintoverridecodedef polycoeffs
def polyxcoeffscoeffs
return sumcxi for ic in enumeratecoeffs
return poly
codepre
pthen you can use it like thisp
pre classlangpy prettyprintoverridecodefn poly456
ret fn7
assertret 333
codepre
pin this example i calculatedp
precode4 5 7 6 72
codepre
| 0 |
looping in python | pyou could put everything in a while loop which could repeat forever or until a user types a certain phrasep
precodeimport math
import sys
import os
print this program will calculate the area height and perimeter of the triangles scalene isosceles equilateral and a right angled triangle
while true
calculate the perimeter
print please enter each side for the perimeter of the triangle
a floatinputenter side a
b floatinputenter side b
c floatinputenter side c
perimeter a b c
print the perimeter for this triangle is perimeter
calculate the area
print please enter each side for the area of the triangle
a floatinputenter side a
b floatinputenter side b
c floatinputenter side c
s a b c 2
sp a b c 2
area ssasbsc 05 area mathsqrtspsp asp bsp c
print the area for this triangle is 02f area
calculate the height
height area 2
print the height of this triangle is height
codepre
por p
precodewhile answerlower in yes y
code
answer inputwould you like to repeat
codepre
pyou could also put it all into a function codedef maincode and then do some form of recursion calling a function in itselfp
pthose are just a few ways there are a ton of ways you can get what you wantp
| 0 |
how to get only the first element of a touple list into an array | pyou need to select the first element of the tuplep
precoder rs0 for rs in list if rs not ingj
codepre
| 0 |
python elementtree copy node with childs | pfor future referencep
psimplest way to copy a node or tree and keep its children without having to import stronganotherstrong library emonlyem for thatp
precodeimport xmletreeelementtree
def copytree treeroot
return etelementtree treeroot
duplicatednodetree copytree node typeduplicatednodetree is elementtree
duplicatedtreerootelement newtreegetroot typeduplicatedtreerootelement is element
codepre
| 0 |
passing stdout to two different places | psince as jf sebastian said stdout amp communicate consume the process stdout your problem is analogous to using a python generator you can only get the process output once p
pthe solution if i understand your question correctly then you just want to use the output of the process twice in that case assign it to a variable once and call that variable as many times as you wish egp
psection 1p
precodeif v1get 1
reply subprocesspopenargs stdoutsubprocesspipe stderrsubprocesspipe
data error replycommunicate
outputtextinsertend data
for line in data the stdout is in data replystdout wont be useful here since you called communicate
do stuff with data
codepre
palternatively in section 2p
precodeif v1get 1
reply subprocesspopenargs stdoutsubprocesspipe stderrsubprocesspipe
data replystdout you can call this variable as many times as you want and it will return the same data
for line in data
inputtextinsertend machinename has matching profiles n
data error replycommunicate lt this would reset data to
outputtextinsertend data
codepre
pheres an example of data being resetp
precodex subprocesspopenecho ok stdoutsubprocesspipe shelltrue
for line in xstdout
print line
this prints ok as expected
tup xcommunicate
tup none this is true since xstdout consumed the output
codepre
pdoes that answer your qp
| 0 |
why does periodically pressing the enter key substantially speed up my code | pi believe this has something to do with the ide that you are using to execute your codep
pi have run your code with syntax alterations for 33 and got the same time to execute both times p
p999
809542283367021p
pbeditb this was performed in stock idle with python 33 i spammed the enter key with multiple experiments and witnessed no time difference between string output on the control v the experimentp
pon a hunch i decided to remove a print function and condense it into one linep
precodeprinti gt clockc
codepre
pthis produced 999 7141783124325343p
pon this basis i believe that the time differential you are seeing is due to the ide sucking up more threads to process your code which results in faster times clearly the time at the end is the total amount of time to compute and print your for loopp
pto confirm my suspicion i decided to put everything into a list of tuples and then print that listp
precodedef newspeedtest
speedlist
c clock
for i in range1000
speedlistappendi clockc
printspeedlist1
codepre
pwhich output 999 00005668934240929957p
pto conclude my experiment confirms it is how iyour idei handles output and cpu consumptionp
| 0 |
python convert a number to a string as is | pthe first step would be however you are getting a number that you think should be 00000 instead of 0 dont actually convert it to a number just keep it as a stringp
| 0 |
pserve is complaining that initpy has no main attribute | pdo you have the py source code that goes with that pyc
if so does it have a strongmainstrong p
| 0 |
how to add space after string and remove a space | plet me know if following do the trickp
precodefrom seleniumwebdrivercommonkeys import keys
departfrom driverfindelementbyiddepartureairportinput
departfromclear
departfromsendkeys
departfromsendkeysuue003
departfromsendkeysfrom
codepre
| 0 |
python orm for turnbased strategy game | pa hrefhttpwwwsqlalchemyorg relnofollowsqlalchemya meets most of your requirements except this p
blockquote
p but i need the history of each turn database state retained so i
can look at any game turn state in pastp
blockquote
pi am not sure what you intend herep
| 0 |
issues with slicing multidimensional list | pyou could start with something like thisp
precodesquare1 boardij for i in range03 for j in range03
square2 boardij for i in range03 for j in range26
codepre
por in a slightly more elegant wayp
precodedef squareab
squareab boardij for i in range3a33a for j in range3b3 3b
codepre
| 0 |
read specific column from datfile | ptry thisp
precodeinfile openinputtxt
for line in infile
list linesplit
if lenlist gt 10
printlist9
codepre
pof course you could save this values to some list o dictp
| 0 |
python opening multiple files using opennpload | pi dont think that this could be archived with open function it returns a file object for each file you are opening and its not possible to pass a list of paths to that functionp
pwhat you can do is define a list with paths or a list to manage different file objects one for each file you want to openp
precodepaths path1path2path3
files
for path in paths
try
filesappendopenpath ltmodegt
except ioerror
print file couldnt be opened or doesnt existformatpath
codepre
por using withp
precodefor path in paths
try
with openpath ltmodegt as mydata
myfunctionmydata
except ioerror
print file couldnt be opened or doesnt existformatpath
codepre
| 0 |
save file python ioerror permission denied | pit may appear a bit convoluted but i suggest that you might want to investigate the etcsudoers filebr
for your purposes you would create the file somewhere that you do have permissions like tmp and then codemovecode it to codevarwwwhtmlimagescode using a script that is named as a codesudoerscode codecmndaliascodebr
you still need to envoke the codecmndaliascode script with codesudocode but if you have declared it with codenopasswdcode then it should just function without asking for the codesudocode passwordp
palways access the codeetcsudoesrscode file using codevisudocodebr
an example of the entries in that file p
precode cmnd alias specification
cmndalias web hometests
codepre
pand then later in the file p
precode user privilege specification
root allallall all
rolf allallall nopasswdweb
codepre
pwith this the codehometestshcode will perform whatever task the user coderolfcode sets it such as moving a file from codetmpcode to codevarwwwhtmlimagescode when the command line codesudo hometestshcode is issued without asking for the passwordp
| 0 |
creating a table like structure in python | pyour question is a bit confusing youre talking about data structure and persistence then about list box gui stuffp
pwrt the data structure and persistence part a table like structure with rows and columns is easily modeled as a list of ducts or list of tuples for the perstitance part you can serialize your list as json and write it to a file or write it as csv using the stdlib cvs package or use a sql dbp
| 0 |
how to take a user sentence and create a list of words out of it | pyou found re already there is a nice example of splitting a stringp
precoderesplitw words words words
codepre
plike this you get all words all punctuation removedp
| 0 |
preview form in a template based on a dropdown options in django | pok that explains things the problem is that youre not creating an actual codetemplatecode object at any point changing two lines will fix itp
precodedef mailcreaterequest
context requestcontextrequest
if requestmethod post
form mailformrequestpost
if formisvalid
if preview in requestpost
post formsavecommitfalse
t formcleaneddatatemplate
tmpl templatettemplatebody lt
preview tmplrendercontextcontextdict lt
return httpresponsepreview
codepre
pmake sure you have codefrom djangotemplate import templatecode up topp
pbtw codemailtemplatenamecode should really be a codecharfieldcodep
| 0 |
how to add a string to a specific line | pif the file to read is big and you dont want to read the whole file in memory at oncep
precodefrom tempfile import mkstemp
from shutil import move
from os import remove close
linenumber 20
filepath myfiletxt
fhr openfilepath
fh abspath mkstemp
fhw openabspath w
for i line in enumeratefhr
if i linenumber 1
fhwwrite line
else
fhwwriteline
fhrclose
closefh
fhwclose
removefilepath
moveabspath filepath
codepre
pstrongnote i used aloks answer a hrefhttpstackoverflowcomquestions2081836readingspecificlinesonlypythonherea as a referencestrongp
| 0 |
appending multiple values to an xml file in python is there a better way to do it than s | pi would suggest you use any of the million template engines out there and do not build it using beautiful soupxmldom its like building html using codeltdivgtappendcode lt please dont do that eitherp
pdo this if you want the most plug and play solutionp
precodefrom makotemplate import template
class objobject
def initself d
for a b in ditems
if isinstanceb list tuple
setattrself a objx if isinstancex dict else x for x in b
else
setattrself a objb if isinstanceb dict else b
deploy
couchbase
gamebucket
name game
password
uris ltadd uri gtltadd urijoin
httpcouchbasechubistaging18091pools
httpcouchbasechubistaging28091pools
httpcouchbasechubistaging38091pools
gt
administrator
username game
password
uris ltadd uri gtltadd urijoin
httpcouchbasechubistaging18091pools
httpcouchbasechubistaging28091pools
httpcouchbasechubistaging38091pools
gt
sessionbucket
name: 'session',
'password': '',
'uris': '<add uri="' + '" /><add uri="'.join([
'http://couchbase.chubi.staging1:8091/pools',
'http://couchbase.chubi.staging2:8091/pools',
'http://couchbase.chubi.staging3:8091/pools'
]) + '" />'
}
}
}
template = template("""<couchbase>
<servers bucket="${deploy.couchbase.gamebucket.name}" bucketpassword="${deploy.couchbase.gamebucket.password}">
${deploy.couchbase.gamebucket.uris}
</servers>
<socketpool minpoolsize="50" maxpoolsize="250" queuetimeout="00:00:00.250" />
</couchbase>
<couchbasecluster>
<servers username="${deploy.couchbase.administrator.username}" password="${deploy.couchbase.administrator.password}">
${deploy.couchbase.gamebucket.uris}
</servers>
</couchbasecluster>
<couchbasesession>
<servers bucket="${deploy.couchbase.sessionbucket.name}" bucketpassword="${deploy.couchbase.sessionbucket.password}">
${deploy.couchbase.sessionbucket.uris}
</servers>
</couchbasesession>
""")
print template.render(deploy=obj(deploy))
</code></pre>
<p>output:</p>
<pre><code><couchbase>
<servers bucket="game" bucketpassword="">
<add uri="http://couchbase.chubi.staging1:8091/pools" /><add uri="http://couchbase.chubi.staging2:8091/pools" /><add uri="http://couchbase.chubi.staging3:8091/pools" />
</servers>
<socketpool minpoolsize="50" maxpoolsize="250" queuetimeout="00:00:00.250" />
</couchbase>
<couchbasecluster>
<servers username="game" password="">
<add uri="http://couchbase.chubi.staging1:8091/pools" /><add uri="http://couchbase.chubi.staging2:8091/pools" /><add uri="http://couchbase.chubi.staging3:8091/pools" />
</servers>
</couchbasecluster>
<couchbasesession>
<servers bucket="session" bucketpassword="">
<add uri="http://couchbase.chubi.staging1:8091/pools" /><add uri="http://couchbase.chubi.staging2:8091/pools" /><add uri="http://couchbase.chubi.staging3:8091/pools" />
</servers>
</couchbasesession>
</code></pre>
<p>by far the cleanest solution would be changing things around a tiny bit:</p>
<pre><code>from mako.template import template
class obj(object):
def __init__(self, d):
for a, b in d.items():
if isinstance(b, (list, tuple)):
setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b])
else:
setattr(self, a, obj(b) if isinstance(b, dict) else b)
deploy = {
'couchbase': {
'gamebucket': {
'name': 'game',
'password': '',
'uris': [
'http://couchbase.chubi.staging1:8091/pools',
'http://couchbase.chubi.staging2:8091/pools',
'http://couchbase.chubi.staging3:8091/pools'
]
},
'administrator': {
'username': 'game',
'password': '',
'uris': [
'http://couchbase.chubi.staging1:8091/pools',
'http://couchbase.chubi.staging2:8091/pools',
'http://couchbase.chubi.staging3:8091/pools'
]
},
'sessionbucket': {
'name': 'session',
'password': '',
'uris': [
'http://couchbase.chubi.staging1:8091/pools',
'http://couchbase.chubi.staging2:8091/pools',
'http://couchbase.chubi.staging3:8091/pools'
]
}
}
}
template = template("""<couchbase>
<servers bucket="${deploy.couchbase.gamebucket.name}" bucketpassword="${deploy.couchbase.gamebucket.password}">
% for url in deploy.couchbase.gamebucket.uris:
<add uri="${url}" />
% endfor
</servers>
<socketpool minpoolsize="50" maxpoolsize="250" queuetimeout="00:00:00.250" />
</couchbase>
<couchbasecluster>
<servers username="${deploy.couchbase.administrator.username}" password="${deploy.couchbase.administrator.password}">
% for url in deploy.couchbase.gamebucket.uris:
<add uri="${url}" />
% endfor
</servers>
</couchbasecluster>
<couchbasesession>
<servers bucket="${deploy.couchbase.sessionbucket.name}" bucketpassword="${deploy.couchbase.sessionbucket.password}">
% for url in deploy.couchbase.gamebucket.uris:
<add uri="${url}" />
% endfor
</servers>
</couchbasesession>""")
print template.render(deploy=obj(deploy))
</code></pre>
<p>output:</p>
<pre><code><couchbase>
<servers bucket="game" bucketpassword="">
<add uri="http://couchbase.chubi.staging1:8091/pools" />
<add uri="http://couchbase.chubi.staging2:8091/pools" />
<add uri="http://couchbase.chubi.staging3:8091/pools" />
</servers>
<socketpool minpoolsize="50" maxpoolsize="250" queuetimeout="00:00:00.250" />
</couchbase>
<couchbasecluster>
<servers username="game" password="">
<add uri="http://couchbase.chubi.staging1:8091/pools" />
<add uri="http://couchbase.chubi.staging2:8091/pools" />
<add uri="http://couchbase.chubi.staging3:8091/pools" />
</servers>
</couchbasecluster>
<couchbasesession>
<servers bucket="session" bucketpassword="">
<add uri="http://couchbase.chubi.staging1:8091/pools" />
<add uri="http://couchbase.chubi.staging2:8091/pools" />
<add uri="http://couchbase.chubi.staging3:8091/pools" />
</servers>
</couchbasesession>
</code></pre>
<p>if you have it in a template, and believe me there is no real difference if you're using <code>mako</code> or <code>jinja2</code> or <code>django templates</code> is whatever you feel most comfortable with, you can get a great birds eye view of what it generates. if you create it using xml dom objects, theres no telling what the heck that does at a glance. its all about <code>readability</code> not about how clever you think you are for making what should have been 40 lines into 10 and not having a damn idea what it does 2 weeks from now when you come back to make a minor adjustment.</p>
<p>also i should add; the class i have <code>obj</code> was just there so i didnt have to change your existing structure. i really do hope its an object.</p>
<hr>
<p>here be dragons.......</p>
<pre><code>from lxml import etree
deploy = {
'couchbase': {
'gamebucket': {
'name': 'game',
'password': '',
'uris': [
'http://couchbase.chubi.staging1:8091/pools',
'http://couchbase.chubi.staging2:8091/pools',
'http://couchbase.chubi.staging3:8091/pools'
]
},
'administrator': {
'username': 'game',
'password': '',
'uris': [
'http://couchbase.chubi.staging1:8091/pools',
'http://couchbase.chubi.staging2:8091/pools',
'http://couchbase.chubi.staging3:8091/pools'
]
},
'sessionbucket': {
'name': 'session',
'password': '',
'uris': [
'http://couchbase.chubi.staging1:8091/pools',
'http://couchbase.chubi.staging2:8091/pools',
'http://couchbase.chubi.staging3:8091/pools'
]
}
}
}
root = etree.element("root")
couchbase = etree.element("couchbase")
servers = etree.element(
"servers",
bucket=deploy['couchbase']['gamebucket']['name'],
bucketpassword=deploy['couchbase']['gamebucket']['password']
)
for url in deploy['couchbase']['gamebucket']['uris']:
servers.append(etree.element("add", uri=url))
servers.append(
etree.element(
"socketpool",
minpoolsize="50",
maxpoolsize="250",
queuetimeout="00:00:00.250"
)
)
couchbase.append(servers)
print etree.tostring(couchbase, pretty_print=true)
</code></pre>
<p>you would need to still do the other two.. please dont do this!!! its hard on the eyes. i feel pretty dirty just showing this example of what not to do!!!</p>
<hr>
| 0 |
scraping biographycom using urllib2 | pyou can discover an api url with httpfox firefox addon fe a hrefhttpwwwbiographycomapiitemsearchconfigpublishedampquerymarx relnofollowhttpwwwbiographycomapiitemsearchconfigpublishedampquerymarxa
brings you a json you can process searching for people to retrive biography links
or you can use an screen crawler like seleniump
| 0 |
write a function getsumoffirstdigitnumlist that takes in a list of positive numbers and returns the sum of all the first digit in the list | precodedef getsumoffirstdigitnum
sum0
for x in num
tempstrx
sumsuminttemp0
return sum
codepre
| 0 |
django querying using array for column value | pdo it this wayp
precodeimport operator
from functools import reduce
def getsearchquerysearch list columnsnone
breaks up the search string and makes a query list
filters the given list based on the query list
if not columns
return list
search searchstripsplit
queries
for col in columns
queriesextendqcolicontains value for value in search
return listfilterreduceoperatoror queries
codepre
| 0 |
why i dont need to declare encoding when using python interpreter | pi suppose an interactive session of python use the a hrefhttpsdocspythonorg2librarysyshtmlsysgetfilesystemencoding relnofollowcodesystem encodingcodea see also a hrefhttpstackoverflowcomquestions2421145pythonunicodestringsandthepythoninteractiveinterpreterpython unicode strings and the python interactive interpreterap
pwhen it read a source file it need to know how to interpret the data its parsing
its logical the script is not necessary written in the same encoding than the terminal executing it and even more when the script is ran without an environment specifying the encodingp
palso it is interesting to read strongjoel spolskystrong a hrefhttpwwwjoelonsoftwarecomarticlesunicodehtml relnofollowthe absolute minimum every software developer absolutely positively must know about unicode and character setsa which might explain why python choose to require the developers to be explicit about the encoding which i would have preferred that they set a default to utf8 but their way is coherent with the a hrefhttpswwwpythonorgdevpepspep0020 relnofollowzen of pythonap
| 0 |
how to stem large csv file using porterstemmer in python | pyoull probably have to read the entire csv file and stem each cell the a hrefhttpsdocspythonorg2librarycsvhtml relnofollowpython codecsvcode librarya will allow you to read the csv file youll probably want to use codecsvreadercode or codecsvdictreadercode the first will allow you to loop through the rows of the csv and read them individually the second will automatically put the data from the csv into a python a hrefhttpwwwtutorialspointcompythonpythondictionaryhtm relnofollowdictionarya either would be a good option for your task p
ponce you have read in the csv you will need to stem the words you have read in you might use the a hrefhttpwwwnltkorg relnofollowcodenltkcode librarya which you might need to install if you have not already done that a hrefhttpwwwnltkorghowtostemhtml relnofollowherea is a resource about stemming with codenltkcodep
| 0 |
combining two record arrays | precodeusrbinenv python
import numpy as np
desc names genderageweight formats s1 f4 f4
a nparraym640750f250600 dtypedesc
b nparraym640750f250600 dtypedesc
alenashape0
blenbshape0
aresizealenblen
aalenb
codepre
pthis works with structured arrays though not recarrays perhaps this is a good reason to stick with structured arraysp
| 0 |
getting live output from running unix command in python | pmost programs will use block buffered output if they are not connected to a tty so you need to run the program connected to a pty the easiest way is to use a hrefhttppypipythonorgpypipexpect relnofollowpexpectap
precodefor line in pexpectspawncommand arg1 arg2
print line
codepre
| 0 |
how to upload small files to amazon s3 efficiently in python | psample parallel upload times to amazon s3 using the python boto sdk are available herep
ul
lia hrefhttplspwdio201306parallels3uploadsusingbotoandthreadsinpython relnofollowparallel s3 uploads using boto and threads in pythonali
ul
prather than writing the code yourself you might also consider calling out to the a hrefhttpsawsamazoncomcli relnofollowaws command line interface clia which can do uploads in parallel it is also written in python and uses botop
| 0 |
handle autoredirects in python request module | pyou should strongnotstrong be setting the codecontenttypecode header leave that to the coderequestscode module as it needs to communicate the multipart boundary in that headerp
pyou are also not actually sending any file data presumably you want to send the image filep
precodeimport requests
session requestssession
headers
refererhttpwwwtotextnet
useragentmozilla50 windows nt 63 wow64 applewebkit53736 khtml like gecko chrome430235781 safari53736
with openimg0jpg rb as imgfile
data
action convert
ocrlang eng
docfile img0jpg imgfile imagejpeg
r1 sessionposthttpwwwtotextnet filesdata headersheaders
codepre
psee the a hrefhttpdocspythonrequestsorgenlatestuserquickstartpostamultipartencodedfile relnofollowempost a multipartencoded fileem sectiona of the emquickstartem documentationp
pyou may also have to send an initial codegetcode request to get a cookie set and there may still be other checks the server makes against the request headers that you havent yet provided youll have to experiment with those headers a server is free to respond any way they like based on the exact headers and request body you sendp
| 0 |
for double or triple bracket how can i remove all value in brackets | pyour question basically deals with removing text within nested brackets assuming only round or square brackets which would be closed properly you can use the following code as mentioned in this a hrefhttpstackoverflowcomquestions1965486removeallnestedblockswhilstleavingnonnestedblocksaloneviapythonquestionap
precodeimport itertools
def removebracketst
p
d 0
l
for c in t
if c or c d 1
lappendd
if c or c d 1
for k g in itertoolsgroupbyzipt l lambda x x1gt0
b listg
if maxd for c d in b gt 0 continue
pappendjoinc for c d in b
print joinp
removebracketsstring
codepre
pif you just want to remove the text within single tags you can use coderegexcode for thisp
precoderesult resubstring
codepre
| 0 |
mysqldb to excel | pif you need a xlsx excel 2007 exporter you can use a hrefhttpsbitbucketorgericgazoniopenpyxl relnofollowopenpyxla otherwise a hrefhttppypipythonorgpypixlwt relnofollowxlwta is an optionp
| 0 |
how to run django runserver over tls 12 | pif you have already tried to update openssl and python using brew and still does not work make sure your settings have debug false p
pwatch this thread for more information a hrefhttpscodegooglecompgoogleappengineissuesdetailid13207 relnofollowhttpscodegooglecompgoogleappengineissuesdetailid13207ap
| 0 |
taking data from an xml document and writing it to another xml document with python | pyou can use the codeetwritecode and codexmldomminidomcode to achieve what you want
considering we do not use codelxmlcode and use only standard pythons elementtreep
pjust extending your codep
precodeimport xmletreeelementtree as et
import xmldomminidom
docetparsetest2xml
rootdocgetroot
elementsrootfindallpoint
rootetelementroot
titleetsubelementroottitle
titletexttitle
tableetsubelementroottable
for element in elements
pointetsubelementtablepoint
elemetsubelementpointid
elemtextname
elem2etsubelementpointlatitude
elem2textcoords
elem3etsubelementpointlongitude
elem3textcoords
etdumproot using etdump just to display the output in the python shell
tree etelementtreeroot
treewritetest3xml this is enough but not yet prettyprint
using xmldomminidom to parse the nonpretty file to make it pretty
a xmldomminidomparsetest3xml
prettyxmlasstring atoprettyxml
with opentest3xml w as f
fwriteprettyxmlasstring write again in prettyprint format
codepre
| 0 |
uwsgi procces blocks request | pyou have a uwsgi server configured to spawn 2 processes then you run 2 long requests those 2 processes are busy with the long requests so new requests must wait until the long requests finishp
pif you want to send new reqeusts to the server while the long requests run increase the processes to more than 2 ie processes 4p
| 0 |
python beaver service not starting on rhel 70 | pi figured the problem out this was because i was usingp
precodeservice
typenotify
codepre
ptypenotify identical to typesimple but with the stipulation that the daemon will send a signal to systemd when it is readyp
pthis was not sending a signal though the service had startedp
pfor more information
a hrefhttpswikiarchlinuxorgindexphpsystemd relnofollowhttpswikiarchlinuxorgindexphpsystemdap
| 0 |
python request to google maps api handshake issue | pafter a long research i found out its a bug in cryptography modulep
psee a hrefhttpsgithubcompycacryptographyissues2299 relnofollowhttpsgithubcompycacryptographyissues2299ap
pworkaround place wsgiapplicationgroup globalp
pin apache virtualhost configuration egp
precodeltdirectory varwwwpathtowsgigt
ltfiles wsgipygt
require all granted
ltfilesgt
wsgiapplicationgroup global
ltdirectorygt
codepre
| 0 |
uwsgi webserver takes way too long to restart on prod | pgraceful reloads imply workers cooperation they get signal hup and they need to die into 60 secondsp
pthere are various reason to block the procedurep
ul
liyou have overridden the hup signal handlerli
liyour workers generate non daemon threadsli
lia bug in your app is preventing the worker to correctly endli
lili
ul
pyou could investigate about why your workers are blocked eventually strace them or simply be less merciful decreasing via workerreloadmercy option those 60 seconds to a lower valuep
| 0 |
trying to use opencv with python on mac os x 106 | pi also had trouble getting the python opencv bindings to work with a macports opencv installationp
pbut i got opencv installed on a mac using homebrew and i can codeimport cvcode and codeimport cv2code in python p
pi a hrefhttpsgithubcommxclhomebrewwikiinstallation relnofollowinstalled homebrewa then did codebrew install opencvcode and then everything worked properlyp
| 0 |
sorting uniques in multiple lists | precodegtgtgt lines tupleopenvarlogfail2banlog r
gtgtgt seen set
gtgtgt for item in lines
item itemstripn
if fail2banactions in item and postfix in item and ban in item
item itemsplit
if item6 not in seen
print item
else
seenadditem6
codepre
| 0 |
Subsets and Splits