text_a
stringlengths 9
150
| text_b
stringlengths 18
20.9k
| labels
int64 0
2
|
---|---|---|
django importerror no module named views | pa hrefhttpistackimgurcom5lnxdpng relnofollowerrora you are getting is selfexplanatoryp
pit seems you have installed wrong package you have installed a hrefhttpspypipythonorgpypiwkhtmltopdf01 relnofollowwkhtmltopdfa package which has no module named view thats why you are getting a hrefhttpistackimgurcom5lnxdpng relnofollowerrora no module named viewsp
pthe correct package is a hrefhttpspypipythonorgpypidjangowkhtmltopdf relnofollowdjangowkhtmltopdfa which has module named viewp
puninstall a hrefhttpspypipythonorgpypiwkhtmltopdf01 relnofollowwkhtmltopdfa and install a hrefhttpspypipythonorgpypidjangowkhtmltopdf relnofollowdjangowkhtmltopdfa
you can find installation and setup instruction for djangowkhtmltopdf a hrefhttpdjangowkhtmltopdfreadthedocsorgenlatest relnofollowhereap
precode1pip uninstall wkhtmltopdf
2pip install djangowkhtmltopdf
codepre
pdont forget to put codewkhtmltopdfcode in installedappsp
precodeinstalledapps
wkhtmltopdf
codepre
| 0 |
combining two queryset into a template tag | pyou would want to create a hrefhttpsdocsdjangoprojectcomendevhowtocustomtemplatetagsassignmenttags relnofollowcodeassignmenttagcodea rather than a generic tag
so you can update your tag asp
precodedef getcampaign
your stuff
return campaignarticle
registerassignmenttaggetcampaign namecampaign
codepre
pand update template asp
precode load campaignarticle
campaign as campaignlist loads the tags and creates campaignlist context variable
for campaignarticle in campaignlist
campaignarticleid
endfor
codepre
| 0 |
override getinstance importexport django | pbasically you need to define custom codeinstanceloadercode class in your resource inner codemetacode classp
precodeclass bookresourceresourcesmodelresource
class meta
model book
fields id name price
instanceloaderclass mycustominstanceloaderclass
class mycustominstanceloaderclassbaseinstanceloader
def getinstanceself row
your implementation here
codepre
psomething like this should help youp
| 0 |
parse args to json elements in python | pyour example suggest you want to codejoincode the arguments you can convert any list into a single string by merging with a separatorp
precodeargs foo bar hold the mustard
print joinargs
codepre
pso to get your list codearg1 arg2code etc join them with the separator and insert emthatem into your templatep
precodenamex s joinargs
codepre
pnote how codecode allows you to skip escaping each codecode in your example this would look likep
precodeparams
blockx namex s joinargs
codepre
pplease keep in mind that you are putting a string representation of a json into a json this is perhaps not the right thing to do a proper api would expect just a single json in which case you can dump codeargscode directlyp
precodeparams
blockx
namex args
codepre
| 0 |
running python code from php | pyou are looking for readline or stdin streamp
pwith a hrefhttpphpnetmanualesfeaturescommandlineiostreamsphp relnofollowphpstdinap
precodefp fopenphpstdinr
line rtrimfgetsfp 1024
codepre
pwith a hrefhttpphpnetmanualesbookreadlinephp relnofollowreadlineap
precodeline readlinecommand
codepre
| 0 |
background extraction in python using open cv | pwhy are you using these linesp
precodethresh cvcreateimagecvgetsizeimg81
codepre
pandp
precodecvthresholdimgthresh100255cvcvthreshbinary
codepre
pp
| 0 |
xgoogle google search return top url | ptry this to get the urls from googlep
precodefrom google import search
for url in searchput your search query here stop15
printurl
codepre
pyou can limit the no of urls by using stopany no you wantp
pdo reply if it worked for youp
pregards
sourabhp
| 0 |
is it safe to create an instance of a class in its metaclass in python | blockquote
pone suspicion i have is that if foo inherited other classes or was subclassed and those other classes had their own metaclass then calling cls in any of the metaclass methods would be calling it on a notyetfinished class object is that truep
blockquote
pthat is true to the extent that in the metaclasss codenewcode its codeinitcode wont have been called yet your metaclass has an codeinitcode as might any subclass so you should make sure that gets called first so i wouldnt try to make an instance of a class that hasnt been fully instantiated yetp
pone thing you might do is manually call the metaclasss codeinitcode from within codenewcode but you would have to set a flag or something in codeinitcode to make sure that the class doesnt get codeinitcoded twice there might be a more clever way too that im not thinking of at the momentp
| 0 |
what is the right way to print fibonacci sequence in python | pthe first one always try to update a with b and next one makes b as 2bp
pthe second performs all updates at once so you should be able to execute it fine instead to have a first method you can go as followsp
precode for i in rangen
printb
bab
aba
codepre
| 0 |
python 27x generators to return indexes of falses in a boolean list | pthis is your list with indexes code0true 1false 2true 3falsecode now codebooleanlistindexcode searches for the first codefalsecode in the list and returns the index which of course is always 1p
pyou mistakengly think that codefor element in booleanlistcode somehow exhausting the codebooleanlistcode but it is notp
pyou need to use ranged codeforcode insteadp
precodedef cursorbooleanlist
for index in range0 lenbooleanlist
if booleanlistindex is false
yield index
testlist true false true false
g cursortestlist
print gnext
print gnext
print gnext
codepre
| 0 |
strategies for storing frequency of dynamic data | ptry to do hack on client side in recording email attempt to a log file then you can read that file to count frequency of emails sentp
pi think that you can put data in memory in dict for some time say for ex 5 or 10 min then you can send data to db thus not putting load on db of frequent writes if you put a check in your code for sudden surge in email from a particular domain then it might provide you a solution for your problemp
| 0 |
error help tuple object has no attribute getx | ppointsetnn returns a tuple so nn is tuple set herep
precode for xy in selfgetpoints
if querydistpointx y lt count
count querydistpointx y
trace x y trace is a tuple
return trace
codepre
pchange top
precodetrace pointx y
codepre
pand pointsetgetpoints returns a list of tuplesp
precode return ix iy for i in selflist
codepre
pchange top
precodereturn selflist
codepre
pthough this seems intentional since selflist in pointset is already a list of points are you sure you want them to be pointsp
| 0 |
how can i unpack four variables from a list | precodevarlist 1 king t 1
for ijkl in zipitervarlist4
print ijkl
1 king t 1
codepre
pthe 4 is the amount of elements you want if you had a list like codevarlist1 2 3 4 5 6 7 8910codep
pit will zip four elements in a step of 4 giving the outputp
precode1 2 3 4
5 6 7 8
codepre
pthe elements in your list must be a multiple of the variables you are assigning them to or you will not get all the elements as shown in the ouput abovep
| 0 |
how to add indexes to txt file output and then modify lines using indexes python | precodeh filedbtxt r
lines hreadsplitn
hclose
for index line in enumeratelines
print index line
codepre
| 0 |
how do i run a python script using an already running blender | pmy solution was to launch blender via console with a python script blender python scriptpy that contains a while loop and creates a server socket to receive requests to process some specific code the loop will prevent blender from opening the gui and the socket will handle the multiple requests inside the same blender processp
| 0 |
shift indented code to the left remove leading tabs | pselect the text you want to indent and press p
p1 strongctrl strong to remove one tab space from beginning of each line and p
p2 strongctrl strong to add one tab in each lines beginningp
pnot tested for all versions but works for sublime text 2p
| 0 |
statsmodels 050 having trouble with tab completion in ipython | pim not sure what this question means what have you done so far what do you expect to happen im going to go out on a limb and say that maybe you got the import wrong it should bep
precodeimport statsmodelsapi as sm
codepre
| 0 |
having all my scores and names in one big array | pyou need to initialize your array outside of your loopp
precodenamearr
while intstudentsgtintstudent
name input what is your name
score input what is your score
student student 1
namearrappendname
namearrappendscore
printnamearr
codepre
potherwise you just set it back to an empty list every loopp
| 0 |
using multithreading to process an image faster on python | ptake a look at a hrefhttpblogdoughellmanncom200904pymotwmultiprocessingpart1html relnofollowdoug hellmans tutoriala on multiprocessing as bjrn points out there are various issues regarding parallel processing which youll need to get a hang of but it can really be worth the effortp
ptip you can use a hrefhttpdocspythonorglibrarymultiprocessinghtmlmultiprocessingcpucount relnofollowmultiprocessingcpucounta to check the number of cores available to youp
| 0 |
how to accept a json post | pfirstly dont use a python script that prints out result directly to cgi you will be forever debugging itp
puse a light weight framework like flask you can do something as simple as p
precodefrom flask import flask
application flaskname
applicationroute methodsget post
def index
if requestmethod post
use flasks build in json decoder
thedata requestgetjson
then do something with the data
return this was a post request how interesting
else
request was get rather than post so do something with else
return hello world
codepre
psee how to configure flask to run with lighttpd here a hrefhttpflaskpocooorgdocsdeployingfastcgi relnofollowhttpflaskpocooorgdocsdeployingfastcgiap
pif you want to test this you can either write another python script to send json data to your server i recommend looking at the python requests library for this a hrefhttpwwwpythonrequestsorgenlatest relnofollowhttpwwwpythonrequestsorgenlatesta or you can do this manually using a http request builder such as httprequester for firefox a hrefhttpsaddonsmozillaorgenusfirefoxaddonhttprequester relnofollowhttpsaddonsmozillaorgenusfirefoxaddonhttprequesterap
| 0 |
classifier predictions are unreliable is that because my gmm classifier is not trained correctly | pfor classification tasks its important to tune parameter given to the classifier also a large number of classification algorithm follow chose theory witch means if you change some parameter of the model briefly you may get some huge different results also its important to use different algorithms and not just use one algorithm for all classification tasksp
pfor this problem you can try different classification algorithm to test that your data is good and try different parameter with different values for each classifier then you can determined that where is the problemp
pone alternative way is to use grid search to explore and tune best parameter for specific classifier read this a hrefhttpscikitlearnorgstablemodulesgridsearchhtml relnofollowhttpscikitlearnorgstablemodulesgridsearchhtmlap
| 0 |
updating list with a for loop | pits because of you have a list comprehension inside the loop and python calculate your desire list in first loop so the length of list is code4code instead you can use the following code p
precodegtgtgt l
gtgtgt for i in list
if i2 lt 25
lappendi
printlenl i
1 1
2 2
3 3
4 4
gtgtgt l
1 2 3 4
codepre
| 0 |
dealing with the tkinter text widgets indexing system | precodedef afterperiodnumber
return intstrnumberpartition2
codepre
| 0 |
how to merge the elements in a list sequentially in python | pjust one line of code is enough p
precodea abcd
output ai ai1 for i in xrangelena if i lt lena1
print output
codepre
| 0 |
any python libs for parsing apache config files | pzconfig i think used to ship with a schema for parsing apache configuration files it doesnt seem to anymore but its oriented around parsing those types of files and turning the config into a python object a quick glance at the documentation suggests it wouldnt be too hard to set up a zconfig schema corresponding to whatever apache options youd like to parse and validatep
pa hrefhttppypipythonorgpypizconfig260 relnofollowhttppypipythonorgpypizconfig260ap
| 0 |
how to write a mutlicolumn file in python | pi think codepprintcode is your wayp
precodegtgtgt import pprint
gtgtgt pprintdoc
support to prettyprint lists tuples amp dictionaries recursivelynnvery simp
le but useful especially in debugging data structuresnnclassesnnn
prettyprintern handle prettyprinting operations onto a stream using a con
figuredn set of formatting parametersnnfunctionsnnnpformat
n format a python object into a prettyprinted representationnnpprintn
prettyprint a python object to a stream default is sysstdoutnnsaferepr
n generate a standard reprlike value but protect against recursiven
data structuresnn
gtgtgt
codepre
| 0 |
how do i efficiently replace the last line in a string | pi would suggest this approachp
precodegtgtgt x
test1
test2
test3
gtgtgt print njoinxsplitlines1something else
test1
test2
something else
gtgtgt
codepre
| 0 |
more pythonic way to iterate in numpy | pi like list comprehensionsp
precodek x y for x y in zipsomearray someotherarray
codepre
pothers like codemapcodep
precodemap lambda x y xy zipsomearray someotherarray
codepre
pwill multiply two arrays and return you a list or generator of course you there are other ways of doing that particular task in numpy if you want to convert it back to an array you can do p
pk array x y for x y in zipsomearray someotherarray p
| 0 |
simple python number generation | pwhy to loop twice we know codestrncode give n times strp
precodegtgtgt for x in range10
printstrx 10
0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5
6 6 6 6 6 6 6 6 6 6
7 7 7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9
codepre
pdemop
precodegtgtgt a5
aaaaa
gtgtgt a10
aaaaaaaaaa
gtgtgt hello10
hellohellohellohellohellohellohellohellohellohello
gtgtgt 910
9999999999
codepre
| 0 |
convert hex string to int in python | pwith 0x prefix you might also use eval functionp
pfor examplep
precodegtgta0xff
gtgtevala
255
codepre
| 0 |
giving parameters into testcase from suite in python | pi dont believe so the signature for setup needs to be what unittest is expecting afaik setup is automagically called within the testcases run method as setup youre not going to be able to pass it unless you override run to pass in the var you want but i think what you want defeats the purpose of strongunitstrong testing dont try to use a dry philosophy with this each unit youre testing should be a part of a class or even part of a functionmethod p
| 0 |
how to be able to avoid a browser refreshing a page after a http post request has been sent in pythoncgi | pa common way to do this is to store the pending messages for a given user on the server associated with that users session and to display them the next time you deliver a page to that userp
psuch messages are often called flash messages nothing to do with adobe flash or session messagesp
psee a hrefhttpsdocsdjangoprojectcomendevrefcontribmessages relnofollowthe django documentationa for an idea of how you would do this in djangop
| 0 |
best way to constantly request http data | pi think i found the problem i needed to keep an open http session that way i get the data more continuously whats the best way of doing this i did http requestssession and using requests nowp
| 0 |
how to istall opencv in epd | plinux has a number of interfaces to opencv have you tried a hrefhttpdocsopencvorgdoctutorialsintroductionlinuxinstalllinuxinstallhtml relnofollowhttpdocsopencvorgdoctutorialsintroductionlinuxinstalllinuxinstallhtmla or a hrefhttpstackoverflowcomquestions13381574opencv243andpythonopencv 243 and pythonap
| 0 |
python remove tag and replace u00a0 in json file | pstart with the python a hrefhttpsdocspythonorg3libraryjsonhtml relnofollowcodejsoncode modulea that will allow you to read and write the json string into python data structures then use the normal python tools to process the datap
pto process the html look at a hrefhttpwwwcrummycomsoftwarebeautifulsoup relnofollowbeautiful soupap
| 0 |
php can run the python programm from php shell but not on the webbrowserubuntu | pthe linux user used to run php web server and php cli are probably different try to change the permissions of py if you can execute after that you got your answerp
precodechmod 0777 homeadministratordesktoptestpy
codepre
| 0 |
python lib psutil how to get exit status with wait | pafter going back and forth on a few comments i suspect youre actually looking to do something like thisp
pin your main program fire and forget some background processes but later in the same program whenever each of those processes actually finishes run some code that gets access to the processs return code and maybe outputp
hr
pheres an example that does that by using a watcher thread for each background processp
precodeimport subprocess
import threading
def doitarglist callback
def threadfunc
p subprocesspopenarglist
stdoutsubprocesspipe stderrsubprocesspipe
out err pcommunicate
callbackout err preturncode
t threadingthreadtargetthreadfunc
tstart
codepre
hr
pthis has two obvious limitations but ultimately theyre the exact same multiplexing problems you deal with when trying to eg talk to lots of machines over the internet at the same time and they have the same solutionsp
pfirst having hundreds of threads is bad theyre not emdoingem anything but they still have big stacks that eat up your virtual memory space especially bad in 32bit python and take up space in the kernel scheduler table especially bad in older unixes fortunately if you dont care about windows you can get around that the same way you do with network code toss the subprocess pipes into a codeselectcode or codepollcode loop or if you emdoem care about windows or just dont want to write your own codeselectcode loop find a framework that does all the heavy lifting for you if you a hrefhttpspypipythonorgpypi3aactionsearchamptermsubprocessampsubmitsearch relnofollowsearch pypi for subprocessa you will find some options specific to codesubprocesscode if youre already using an eventdriven network or gui framework like twisted or qt it may well have its own way to do this built in eg see a hrefhttptwistedmatrixcomdocumentscurrentcorehowtoprocesshtml relnofollowusing processesa for twistedp
psecond your codecallbackcode gets called in some arbitrary background thread and has no way to propagate a return value or exception to the rest of your code except by mutating some shared value which means youre now dealing with all the usual headaches of shareddata threading even though you never asked to do so all of the usual ways to improve that situationcodequeuecode codeconcurrentfuturescode etcapply here as wellp
hr
pof course if youre lucky you only have a dozen or so processes running at a time so the first problem isnt a problem and all you want to do in the callback is say to print or log some data (so the second problem isn't a problem).</p>
| 0 |
unable to open a connection to postgresql from python3 | pyou can also use another module psycopg2 to connect to postgresqlp
pa hrefhttpinitdorgpsycopgdownload relnofollowhttpinitdorgpsycopgdownloadap
| 0 |
practical point of view why would i want to use python with c | pone nice thing about using a scripting language is that you can reload new code into the application without quitting the app then making changes recompile and then relaunching the app when people talk about quicker development times some of that refers to this capability
a downside of using a scripting languages is that their debuggers are usually not as fully featured as what you would have in c i havent done any python programming so i dont know what the features are of its debugger if it has one at allp
pthis answer doesnt exactly answer what you asked but i thought it was relevant the answer is more the procons of using a scripting language please dont flame me p
| 0 |
python script for mastermind solving stops unexpectedly also gives error after increasing range | pas i understand it from your code you call function rungame from function restartgame and if p
precodeif timesdone lt timesuntil
codepre
pyou call restartgame from rungame therefore if timesuntil variable exceed certain value you get maximum recursion depth exceeded error
you get a sequence of nested calls of the formp
precoderungame
restartgame
rungame
restartgame
codepre
pto increase the maximum recursion depth you could use syssetrecursionlimit function but a far better solution would be to rewrite your code in such a way
to get rid of recursionp
| 0 |
writing list to a file in python | pyoure not explaining properly and your question frankly is not an explicit question but a code writing request which is against stackoverflows policy so here is what you get p
pcodecontentscode with include a list of every line each row of this list will include 4 lists separating your datap
precodewith openfiletxt r as file
contents linesplit for line in file
codepre
pthen you can modify codecontentsindexnum alteredvaluecode or add codecontentsappendnewvaluecode whatever it is you want to modify or add and write it back to file like sop
precodewith openfiletxt w as file
for item in contents
printitem filefile
codepre
pthis is a quick fixp
| 0 |
pandas readtable with multiple column definitions | pfull script that spits out a dataframe with the information i want the monkey business with updating and dropping columns is necessary to keep the composite index coderetvalmergedset howoutercode give the same columns but an integer indexp
precodefrom subprocess import checkoutput
import numpy as np
import pandas as pd
from itertools import cycle
fname foo
headerrows intssplitb0
for s in checkoutputgrep on fnamesplit
subtract one because header column is read separately
limiters rangea b1 for a b in zipheaderrows1 headerrows1
limiters cycletrue
nameses t diagnostic1 diagnostic2
t diagnostic1 diagnostic3
t diagnostic2 diagnostic3
with openfname r as fobj
for names limit in zipnameses limiters
line fobjreadline
dset pddataframenploadtxtline for i line in ziplimit fobj
columnsnames
dsetsetindext inplacetrue
if the return value already exists merge in the new dataset
try
retval retvalmergedset howouter
leftindextrue rightindextrue
suffixes
for col in c for c in retvalcolumns if not cendswith
upd joincol
try
retvalcolupdateretvalupd
retvaldropupd axis1 inplacetrue
except keyerror
pass
except nameerror
retval dset
printretval
codepre
| 0 |
odoo file upload with browser open file dialog | pyou need to implement a custom widget for this object buttons trigger actions in server side not client sidep
| 0 |
interactive nonblocking subprocesspopen script without using communicate or pexpect | blockquote
pa why does it blockp
blockquote
pit blocks because thats what codereadcode does it reads all of the bytes until an endoffile indication since the process never indicates end of file the codereadcode never returnsp
blockquote
pb how may i massage this slightly emphasis on slightly so that it will run without blockingp
blockquote
pone thing to do is to cause the process to indicate end of file a small change is to cause the subprocess to exitp
precodeprocstdinwritels lashtr exitn
codepre
| 0 |
do nothing if rss feed hasnt changed | pthere are a number of different approaches you could take the easiest is probably to keep a unique key or hash of the most recent article acquired for each feed that your program deals with this could be a combination of the article title amp date or even an md5sum of the entire contents of the articlep
pyou could then write this data to an xml state file for your script or use something like a hrefhttpdocspythonorgrelease25libmodulecpicklehtml relnofollowcpicklea to save the data then every time your program runs only retrieve the feed articles that are the most recent checking each against your latest article hash from the last runp
pand of course dont forget to update your most recent article feed hash before your script exitsp
pif your script deals with multiple feeds youll have to store one of these latest article hash items per feedp
| 0 |
what exactly does the page 1 mean here builderror mainuserprofile page 1 none | pit means that it cannot find an function thats called userprofileif you are using codeurlforcode in your main blueprint and this function should take a parameter called page for example like thisp
precodewebappapprouteerrorslogltintpagegt methodsget post
flaskloginloginrequired
def errorslogpage
codepre
| 0 |
iterate over a file in a growing folder in python | pi would use python codesetcodes to build a list of files youve already processed and then cycle through the directory some number of times until you are comfortable that you have seen all of the current batch of filesp
psomething likep
precode usrbinenv python
import os
import time
processed set
tripswithnochange 0
timetoletwritercatchup 2
maxnumberoftrips 10
while tripswithnochange lt maxnumberoftrips
for rootdirsfiles in oswalk
candidates setfiles
remove the files already visited from consideration
candidatesdifferenceupdateprocessed
if lencandidates 0
tripswithnochange 1
continue
for f in candidates
process file
pass
processedupdatecandidates
timesleeptimetoletwritercatchup
codepre
pthere are several codemagiccode numbers in this approach that you will need to tune until you are confident that all the files are processed specificallyp
ul
litripswithnochangeli
litimetoletwritercatchupli
limaxnumberoftripsli
ul
pmaybe this will give you some ideasp
| 0 |
sort list by member variables correctly | pas per zehnpaard
a hrefhttpnedbatcheldercomblog200712htmle20071211t054956 relnofollowhttpnedbatcheldercomblog200712htmle20071211t054956a
a hrefhttpblogcodinghorrorcomsortingforhumansnaturalsortorder relnofollowhttpblogcodinghorrorcomsortingforhumansnaturalsortorderap
pand blivetwidge
a hrefhttpstackoverflowcomquestions4836710doespythonhaveabuiltinfunctionforstringnaturalsortdoes python have a built in function for string natural sortap
| 0 |
how to make crossdomain ajax calls with csrf token | pi am doing this on my javascript initialization for a page i want to do ajax posts with djangop
precodedocumentajaxsendfunctionevent xhr settings
function sameoriginurl
url could be relative or scheme relative or absolute
var host documentlocationhost host port
var protocol documentlocationprotocol
var srorigin host
var origin protocol srorigin
allow absolute or scheme relative urls to same origin
return url origin urlslice0 originlength 1 origin
url srorigin urlslice0 sroriginlength 1 srorigin
or any other url that isnt scheme relative or absolute ie relative
httphttpstesturl
function safemethodmethod
return getheadoptionstracetestmethod
if safemethodsettingstype ampamp sameoriginsettingsurl
xhrsetrequestheaderxcsrftoken csrftoken
codepre
pi dont remember where ive found it however after using it i can do ajax posts like thisp
precodepost url foo datamyjson functiondata
ifdataresultok
windowlocationreplace url bar
else
alertdata err
errorfunction
alertajax error
);
</code></pre>
| 0 |
increment the next element based on previous element | ptry using index of current element to check for the next element in the list
replace p
precodeif i1b
codepre
pwithp
precodeif ccindexi1b
codepre
| 0 |
sending mail by unauthorised sender in google appengine | passuming mydomaincom is registered as a google domain account try adding sendermydomaincom with the role developer in the permissions section of the app engine admin console a hrefhttpsappenginegooglecompermissionsampappidsyourapp relnofollowhttpsappenginegooglecompermissionsampappidsyourappa replace yourapp with your apps idp
pfor more information see a hrefhttpscloudgooglecomappenginedocspythonmailsendingmail relnofollowhttpscloudgooglecomappenginedocspythonmailsendingmailap
| 0 |
what is the best way to get all the divisors of a number | pold question but here is my takep
precodedef divsn m
if m 1 return 1
if n m 0 return m divsn m 1
return divsn m 1
codepre
pyou can proxy withp
precodedef divisorgeneratorn
for x in reverseddivsn n
yield x
codepre
pnote for languages that support this could be tail recursivep
| 0 |
how to separate numbers into digits and store them in a list | pmaybe these can solve your problemp
precodes
123
456
7 8
def digitsfromstrstring
return
x if x else 0
for x in string
if x n
print digitsfromstrs
codepre
| 0 |
how do i check if a sub string exist in a list nested in a dictionary | pyou need to test against each string in the list separatelyp
precodex hello im bob hello im gabe
for i s in enumeratex
if gabe in s
print index i
codepre
| 0 |
how to label certain x values | pit depends somewhat on whether youre using the procedural matlablike or objectoriented interface in either case say you wanted to label code1code code25code and code4code with codeacode codebcode and codeccode with the procdeual interface you could callp
precodepltxticks1 25 4 a b c
codepre
pin the latter case you would dop
precodeax pltgca
axsetxticks1 25 4
axsetxticklabelsa b c
codepre
por in one stepp
precodeax pltgca
axsetxticks1 25 4 xticklabelsa b c
codepre
| 0 |
proxy server for selenium and python | pi dont think plugins are a very good solution certainly not when there are pure http solutions that work the same across all browsers versions and operating systemsp
pyou could use this a hrefhttpsgithubcomautomatedtesterbrowsermobproxypy relnofollowpython wrappera for a hrefhttpsgithubcomlightbodybrowsermobproxy relnofollowbrowsermoba which is a very wellknown standalone or embedded proxy server written in javap
pthe a hrefhttpsgithubcomautomatedtesterbrowsermobproxypyblobmasterbrowsermobproxyclientpyl181 relnofollowcodea shows how the codeheaderscode python method can be used to add headers without the need to post to the rest api the tests have a hrefhttpsgithubcomautomatedtesterbrowsermobproxypyblobmastertesttestclientpy relnofollowsome examplesa of it in use egp
precodeselfclient clientlocalhost9090
selfclientheadersuseragent rubber ducks floating in a row
selfclientheadersauthorization basic dxnlcjpwyxnz user user password pass
codepre
pstrongupdatestrongp
pjust to clarify how the webdriver and the proxy fit togetherp
ul
listart your proxy server first and wait until its ready you can do that externally and pass hostport to webdriver or start it embedded in your application then pass webdriver a codeproxycode objectli
lia hrefhttpsgithubcomautomatedtesterbrowsermobproxypyhowtousewithseleniumwebdriver relnofollowthis examplea demonstrates the second approach using firefox profiles and chrome optionsli
lialternatively start the proxy embedded use it to obtain a codeproxycode object which represents a selenium proxy server then add it to your codedesiredcapabilitiescode object and create your driver that way as per a hrefhttps//github.com/lightbody/browsermob-proxy#using-with-selenium" rel="nofollow">this example</a>.</li>
</ul>
<p>from that point on, the proxy-listening is automatic, and you can start to create your har files.</p>
<hr>
<p>alternatively, you could see <a href="http://stackoverflow.com/a/9469400/954442">this answer</a> for a custom python proxy server using twisted.</p>
<p>i have a longer answer about selenium proxies in python <a href="http://stackoverflow.com/q/35004026/954442">here</a>.</p>
| 0 |
django app discovery issue in settings file how to solve | pyou are importing codecode from codelocalsettingscode and codeproductionsettingscode after you imported from codesettingstemplatecode so your codeinstalledappscode is getting overwritten somewhere p
pthe idea about environment separation is that you put the common settings in one file in your case codesettingstemplatecode and then only add the environment specific settings in codelocalsettingscode and codeproductionsettingscode p
palso you probably dont want to import both production and local settings directly into the settings you should import from local file when youre in local environment and from production file when in production environment p
pits a good practice to put everything in codesettingspycode and then import from either local or production instead of creating 3 files like you did p
| 0 |
importerror when importing flask wtf forms | plooks like you installed only wtf not codeflaskwtfcode extensionp
pto install codeflaskwtfcode codepip install flaskwtfcodep
| 0 |
looking for foreignkey active and add to queryset | pyou are getting errors from what youve attempted because codeannotatecode method needs an aggregate function eg codesumcode codecountcode etc rather than a codeqcode objectp
psince django 17 its possible to do what you want using codeprefetchrelatedcode see docs here
a hrefhttpsdocsdjangoprojectcomen18refmodelsquerysetsdjangodbmodelsprefetch relnofollowhttpsdocsdjangoprojectcomen18refmodelsquerysetsdjangodbmodelsprefetchap
precodedevicesetobjectsprefetchrelated
prefetchcontrolset
querysetcontrolobjectsfilteractivetrue
toattrcontrol
codepre
| 0 |
glasslab cluster library | pas far as i can see in the link you provided there is a setuppy file in the source packagep
pso download the sources unzip them in a separate folder go to that folder and type p
precodepython setuppy install
codepre
pyou will probably need the mingw gcc compiler free to make this runp
phope this helps i have no windows systems anymore and can not test thisp
| 0 |
server logging in database or logfile | pjust in case you consider to tweak the standard python logger to log to a database this recipe might give you a head start a hrefhttpcodeactivestatecomrecipes498158 relnofollowlogging to a jabber accountap
| 0 |
modify python path for python3 only | pif you cant import time math modules that are in stdlib then your installation of python 3 is brokenp
pwhen you run codepython setuppy installcode the files are installed in correct place for current python executable be it a system python or python from a virtualenv environment the same goes for codepipcodep
pyou dont need to modify any paths just use an appropriate executablesp
| 0 |
counting function calls python | phow about as a decorator that maintains a global eww dict each function is a key fully qualified name and the value is the maximum number of calls to that function each time it executes the enclosed function it checks that the value 0 executes the function and decrements the countp
pif you need it for just one function a less generic decorator could use a global var instead of a dict and checkexecutedecrement that value as abovep
| 0 |
kivy io and database communication possible | ptheoretically kivy supports all python packages so you can use codesqlitecode codesqlalchemycode to store it your data directly on the device or maybe even remote database with ssl tunnel for transporting sql more a hrefhttpcheparevcomkivysqlite relnofollowhereap
| 0 |
python after a certain if loop repeat a certain part of the code | pi think you should repeat whole this part while you dont get result you are expected forp
precodewhile true
a ceiqtgenericdialogitemsnonesave evaluationokcancel
ret adoit
if ret lt 0
break if cancel dialog will not proceed data analysis
for i in agetvalues
if istepbegin
begin agetvaluei
if istepend
end agetvaluei
if begin lt end
break if everything is ok move out
items2
items2appendtextitemtextstart timestep must be smaller than end timestep
a ceiqtgenericdialogitems2noneerrorokcancel
ret adoit
if ret lt 0
break if cancel dialog will not proceed data analysis
codepre
| 0 |
where do i add a scale factor to the essential matrix to produce a real world translation value | pi have the same problemi think the monocular camera may need a object known the 3d coordinatethat may help p
| 0 |
deleteview extension | pcodetypeselfcode will return your object actual class codepersondeleteviewcode not class where that code is located codebasedeleteviewmixincode so codesupercode will be launched in context of codepersondeleteviewcode that will cause to launch again post method from codebasedeleteviewmixincode and not as youre expecting from codedeleteviewcodep
pjust hardcode your mixin class name in your codesupercode callp
| 0 |
make a request to download a video in python | pas a hrefhttpstackoverflowcomusers415143markmamark maa mentioned you can get it done without leaving the standard library by utilizing codeurllib2code i like to use a hrefhttpdocspythonrequestsorgenlatest relnofollowrequestsa so i cooked this upp
precodeimport os
import requests
dumpdirectory ospathjoinosgetcwd mp3
if not ospathexistsdumpdirectory
osmakedirsdumpdirectory
def dumpmp3forresource
payload
api advanced
format json
video resource
initialrequest requestsgethttpyoutubeinmp3comfetch paramspayload
if initialrequeststatuscode 200 good to go
downloadmp3atinitialrequest
def downloadmp3atinitialrequest
j initialrequestjson
filename 0mp3formatjtitle
r requestsgetjlink streamtrue
with openospathjoindumpdirectory filename wb as f
printdumping 0formatfilename
for chunk in ritercontentchunksize1024
if chunk
fwritechunk
fflush
codepre
pits then trivial to iterate over a list of youtube video links and pass them into codedumpmp3forcode onebyonep
precodefor video in httpwwwyoutubecomwatchvi62zjga8jom
dumpmp3forvideo
codepre
| 0 |
python csv search script | pthis script read codetestcsvcode file and parse it an write to codeoutputtxtcodep
precodef opentestcsvr
d
s
for line in f
llinesplit
if not l0 in d
dl0l1rstrip
sl0
else
sl0strstrl1rstrip
wopenoutputtxtw
wwrite10s 10s 10srn idparentidatachment
for i in dkeys
wwrite10s 10s 10srn idisi
fclose
wclose
codepre
hr
example
pinputp
precode1123
2456
1333
3
1asas
1333
000001sasa
1ss
1023265333
0221212
000001sasa2
000001sas4
codepre
poutputp
precodeid parentid atachment
000001 sasa sasa2sas4
1023265 333
1 123 333asas333ss
3
2 456
0221212
codepre
| 0 |
python game 2048 out of list index | pi did a quick debug and i was able to get a indexerror when calling move looking through you seem to expect selfcell to be populated but it only is ever populated through your reset function you may not see this if your ui module calls reset when initializingp
pthere is a second indexerror then when the row and col are not the same number this as mentioned in the other answer is because your 2d array representation is col row not row col p
pbelow is the printout of 4 6 which has 4 column and 6 row you likely just need to swap the two in your representationp
precode0 0 0 0
2 0 2 0
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
codepre
pa potential improvement to your syntax but you can initiate your cells as such test with your usagep
precodeselfcell 0 selfgridwidth for row in xrangeselfgridheight
codepre
plastly i believe you may get an indexerror in your newtile because python lists begin at the 0th element youll want to iter 0 through n1p
precode for row in rangeselfgridheight1
for col in rangeselfgridwidth1
codepre
| 0 |
in the python google app engine how do i export all the entities of a model to a file in google storage for developers | pi know this is old but i posted an example of using the app engine mapper api dumping datastore data into cloud storage here
a hrefhttpstackoverflowcomquestions10966841googleappengineusingbigqueryondatastore1096990010969900google app engine using big query on datastoreap
| 0 |
zipfile module in python runtime problems | psee if this works any better at a minimum youll find out which file is failing and whyp
precodeimport os
import ospath
from time import localtime
from zipfile import zipfile zipdeflated
def zipperzipfilename directory
archive zipfilezipfilename w zipdeflated
for root dirs files in oswalkdirectory
for f in files
path ospathjoinroot f
try
archivewritepath
except valueerror err
print error compressing s path
s osstatpath
print sstmtime
print localtimesstmtime
print strerr
archiveclose
if name main
zipperfoozip
codepre
| 0 |
why is my dynamodb throughput so high | pturns out that i was not calculating the required throughput correctly its not just based on the number of written items but on their sizes a single write unit per second is for 1kb of data so an item thats 2kb in size requires twice the throughput of an 1kb item most of my items are a lot bigger than 1kbp
| 0 |
new path is not reflected in python code | pi believe you have to use the file extension and no forward slash before the data folderp
precodesnap1 nploadtxtdatamilli17txt
codepre
| 0 |
reverse for home with arguments and keyword arguments not found | pi will suggest you to call url into your basehtml like p
precodeltfootergt
ltpgt
lta href url home gthomeltagt
ltpgt
ltfootergt
codepre
pwrite url name without quotes p
| 0 |
storing images in db using django models | pyou can store image in strongbytea fieldstrong p
pthe strongbytea data typestrong allows storage of binary strings a hrefhttpwwwpostgresqlorgdocs92staticdatatypebinaryhtml relnofollowpostgres documentation linkap
pthe earlier version of django does not support bytea field so i have been using this library called a hrefhttpsgithubcomniwibedjormextpgbytea relnofollowdjormextpgbyteaa p
| 0 |
how do i merge dictionaries together using weights | palgorithmically indistinguishable from a hrefhttpstackoverflowcomquestions6701358howdoimergedictionariestogetherusingweights67017476701747gnibblersa but somehow the generator expression pleases me p
precodegtgtgt from collections import defaultdict
gtgtgt weights values defaultdictint defaultdictint
gtgtgt keyweightvalue key dweight value
for d in alldictionaries
for key value in ddataiteritems
gtgtgt for k w v in keyweightvalue
weightsk valuesk weightsk w valuesk w v
gtgtgt dictk valuesk 10 weightsk for k in weights
apples 50 oranges 70 bananas 30
codepre
| 0 |
user input concentric circles | precodeimport turtle
import random
num intinputhow many circles
radius intinputradius
move to starting point tangent to right edge of largest circle
turtleforwardradius
turtleleft90
draw circles largest to smallest
for circle in rangenum 0 1 num 1
draw a filled circle
turtlebeginfill
turtlecolorrandomrandom randomrandom randomrandom
turtlecircleradius circle num
turtleendfill
shift inward to next circle startingpoint
turtleleft90
turtleforwardradius num
turtleright90
codepre
pgiven 6 120 producesp
pimg srchttpistackimgurcom164qsgif altenter image description herep
| 0 |
how do i continue to process a file despite a unicodedecodeerror error | pif the files are encoded in proper way then you will have to decode the codebom byte order markercode first to figure out the encodingp
pyou can use a hrefhttppymotwcom2codecs relnofollowcodeca module it can detect the bom and decode the files accordinglyp
| 0 |
find multiple patterns in a string | pyou can alternatively use codeanycode but your approach seems to be sufficientp
precodet querylower
forbiddens drop delete update insert alter
if anyi in t for i in forbiddens
print oh you are not supposed to enter that
codepre
| 0 |
export bigquery data to csv without using google cloud storage | pyou can download all data directly without routing it through google cloud storage using paging mechanism basically you need to generate a page token for each page download the data in the page and iterate this until all data has been downloaded ie no more tokens are available here is an example code in java which hopefully clarifies the ideap
precodeimport comgoogleapiclientgoogleapisauthoauth2googlecredential
import comgoogleapiclientgoogleapisjavanetgooglenethttptransport
import comgoogleapiclienthttphttptransport
import comgoogleapiclientjsonjsonfactory
import comgoogleapiclientjsonjsonfactory
import comgoogleapiclientjsonjackson2jacksonfactory
import comgoogleapiservicesbigquerybigquery
import comgoogleapiservicesbigquerybigqueryscopes
import comgoogleapiclientutildata
import comgoogleapiservicesbigquerymodel
your class starts here
private string projectid fill in the project id here
private string query enter your query here
private bigquery bigquery
private job insert
private tabledatalist tabledatalist
private iteratorlttablerowgt rowsiterator
private listlttablerowgt rows
private long maxresults 100000l max number of rows in a page
run query
public void open throws exception
httptransport transport googlenethttptransportnewtrustedtransport
jsonfactory jsonfactory new jacksonfactory
googlecredential credential googlecredentialgetapplicationdefaulttransport jsonfactory
if credentialcreatescopedrequired
credential credentialcreatescopedbigqueryscopesall
bigquery new bigquerybuildertransport jsonfactory credentialsetapplicationnamemy appbuild
jobconfigurationquery queryconfig new jobconfigurationquerysetqueryquery
jobconfiguration jobconfig new jobconfigurationsetqueryqueryconfig
job job new jobsetconfigurationjobconfig
insert bigqueryjobsinsertprojectid jobexecute
jobreference jobreference insertgetjobreference
while true
job poll bigqueryjobsgetprojectid jobreferencegetjobidexecute
string state pollgetstatusgetstate
if doneequalsstate
errorproto errorresult pollgetstatusgeterrorresult
if errorresult null
throw new exception"error running job: " + poll.getstatus().geterrors().get(0));
break;
}
thread.sleep(10000);
}
tabledatalist = getpage();
rows = tabledatalist.getrows();
rowsiterator = rows != null ? rows.iterator() : null;
}
/* read data row by row */
public /* your data object here */ read() throws exception {
if (rowsiterator == null) return null;
if (!rowsiterator.hasnext()) {
string pagetoken = tabledatalist.getpagetoken();
if (pagetoken == null) return null;
tabledatalist = getpage(pagetoken);
rows = tabledatalist.getrows();
if (rows == null) return null;
rowsiterator = rows.iterator();
}
tablerow row = rowsiterator.next();
for (tablecell cell : row.getf()) {
object value = cell.getv();
/* extract the data here */
}
/* return the data */
}
private tabledatalist getpage() throws ioexception {
return getpage(null);
}
private tabledatalist getpage(string pagetoken) throws ioexception {
tablereference sourcetable = insert
.getconfiguration()
.getquery()
.getdestinationtable();
if (sourcetable == null)
throw new illegalargumentexception("source table not available. please check the query syntax.");
return bigquery.tabledata()
.list(projectid, sourcetable.getdatasetid(), sourcetable.gettableid())
.setpagetoken(pagetoken)
.setmaxresults(maxresults)
.execute();
}
</code></pre>
| 0 |
read chinese character from excel file python3 | pwell the problem i had wasnt in reading the chinese characters actually my problem were in printing in console
i thought that the print encoder works fine and i just didnt read it the characters but this code works fine p
precodefrom xlrd import openworkbook
wb openworkbooktestxls
messages
links
for sheet in wbsheets
numberofrows sheetnrows
numberofcolumns sheetncols
for row in range1 numberofrows
i 0
for col in rangenumberofcolumns
value sheetcellrowcolvalueencodegbk
if i 0
messagesappendvalue
else
linksappendvalue
i1
printlinks
codepre
pto check it i paste the first result in selenium driver since i was going to use it anywayp
precodeelement driverfindelementbyclassnameemailsendkeysstrmessages0gbk
codepre
pand it works like a charmep
| 0 |
default value of memberfunction in python | pyou are right you cant do thatp
pfor example in python you have to be very careful about this because it will use the same list over and over in this case it will continue appending to the same listp
precodedef foo2selfaa
aaappendfoo
return la
codepre
pinstead a very common approach is to assign codenonecode as the default value and then have an ifstatement to set it inside the functionp
precodedef foo2selfaanone
if not aa
aa selfa
return la
codepre
| 0 |
how to append the first item of list to the end of all permutations of that list | pi guess what you want isp
precodeairportlist1 listi airportlist1 for i in permutationsairportlist1
codepre
| 0 |
python regex meaning | ol
lipraw string notation rtext keeps regular expressions sane without it every backslash in a regular expression would have to be prefixed with another one to escape itpli
lip groups a statement its treated as one thing so you can do or or if the things in the brackets need to handled togetherpli
lip matches it if its the beginning of the stringpli
lipdot in the default mode this matches any character except a newlinepli
lipsince it is the means match 0 or more matches of the previous thing which in this case is any characterpli
lipdefw lines beginning with the string def and then w matches any nonalphanumeric characters and is equivalent to azaz09 since we have the again this time it matches 0 or more nonalphanumeric characterspli
lipw the is for 1 or more of the previous which in this case is w equivalent to azaz09pli
ol
p7w we know that one alreadyp
ol
lip means just to match differentiate it from grouping things same for pli
lip match 0 or more characters insidepli
lip the matched string ends with a colon at the endpli
ol
pthe whole thing seems to be matching a definition of a function in python ie def foox will be matched dealing with regular expressions is hard using tools such as a hrefhttpwwwpythonregexcom relnofollowhttpwwwpythonregexcoma helps me to try out different things and since re are slightly different in different languages its nice to have tools for those too</p>
| 0 |
looping through a folder to merge several excel sheets into one column | pyou can also easilly append data likep
precodedf
for f in cfile1xls c file2xls
data pdreadexcelf sheet1iloc2
dataindex ospathbasenamef lendata
dfappenddata
df pdconcatdf
codepre
pfrom
a hrefhttpstackoverflowcomquestions25400240usingpandascombiningmerging2differentexcelfilessheetsusing pandas combiningmerging 2 different excel filessheetsap
| 0 |
converting a list into a string | pyou can do this with joins and a list comprehensionp
precodedef goodcharss
return joinjoiny for y in x if yisdigit or yisalpha for x in ssplit
codepre
| 0 |
need to transfer multiple files from client to server | pi believe youre actually receiving all the files content but then writing them all to one filep
pyour server is only accepting a single connection and it writes whatever data it receives into the file until it receives no more data that wont happen until the client closes its socket at the endp
pthere are a couple of ways to fix this p
ol
limove the codeacceptcode call into the server loop and the codeconnectcode call into the client loop have your client connect send the filename transfer the entire content of a single file then emcloseem the connection on the next iteration do it all over againli
lialternatively at the beginning of each file have the client send to the server both the filename to be transferred and the file size so the server knows how to find the end of the file content then write exactly that many bytes to the server but see also below as to transmitting the file sizeli
ol
pi would recommend 1 as more robust and easier to implementp
psecond subject your mechanism for sending the filename is flawed if i follow it correctly your program would not work properly if the filename being transmitted begins with a digit as the server will not be able to determine how many bytes are being used to send the filename length there are two usual ways of sending numbersp
ol
liuse the codestructcode module to format a binary integer in a welldefined way you actually send the packed format and the server would unpack it it would then know exactly how many bytes long to receive for the filenameli
lijust send a header line containing the filename followed by a null byte or newline or some other welldefined defined terminator byte then the server can read a byte at a time of the filename until it sees the terminatorli
ol
| 0 |
using django inside tornado app cant access mysql records created after the tornado app starts | pbased on ben darnells code all it took was the followingp
precodefrom djangodb import connection
if userid is none
return none
try
connectionqueries
user usermodelobjectsgetpkuserid
connectionclose
return user
except usermodeldoesnotexist
return none
codepre
| 0 |
generating random string based on some hex | ul
lishort answer you cantli
lilongr answerbr
a md5 hashsum contains 128 bits of information so to store that you also need 128 bits the closest you get from that to a human readable form would probably be to base64 encode it that will leave you with 22 characters 24 with padding thats probably as short as it gets
br
where does the randomness in your md5 hash come from anyway md5 hashes arnt random so youre probably hashing something random what to get them and by doing so you cant increase the entropy in any way only decrease itli
ul
pyou could probably create you own way to encode the checksum using a larger range of characters from the unicode range but that would mean you had to select a suitable set of characters that anybody will know how to pronouncebr
something like code code would seem fairly clear but some symbols like codecode no so muchp
| 0 |
python memory error reading text fastest solution | pif you are reading a large file and then storing the lines in arrays then you are actually doubling the required memory size p
pone source can be if you are using codeline inputreadlinescode if that is the source of the problem you can replace that with thisp
precodefor item in input
functionitem
codepre
pthat iterates over each linep
palso consider using the codecsvcode library if your text file is a csvp
pa hrefhttpstackoverflowcoma42852652327328sourceap
| 0 |
compare two csv files and write shared items to a new csv file | phow big is your files can you load both of them in memory the code above loads one of them and because you are interested in whole row i guess you dont have to comapre contents within rowp
pyou dont need csv reader too p
pso try p
precodef1 openpathtof1csv rreadlines
f2 openpathtof2csv rreadlines
f3 openpathtof3 a
for lines in f1
if lines in f2
f3writelines
f1close
f2close
f3close
codepre
| 0 |
djangonvd3 does not show any graph | pmake sure your static files for nvd3 and d3 are available then check if there is any type of error in the js consolep
| 0 |
it is possible export table sqlite3 table to csv or similiar | pexternal programs see documentation for a hrefhttpsqliteorg relnofollowsqlite3a for details you can do it from shellcommand linep
pon the fly
a hrefhttpdocspythonorglibrarycsvhtml relnofollowcsv modulea will help you to handle csv file format correctlyp
| 0 |
http request object does not respond | pinstead of codedirecttotemplatecode you may want to use coderendertoresponsecode which renders a given template and returns httpresponse p
prefer a hrefhttpsdocsdjangoprojectcomendevtopicshttpshortcutsrendertoresponse relnofollowrendertoresponsea note you will have to import it using codefrom djangoshortcuts import rendertoresponsecodep
| 0 |
django csrf in ajax post csrf cookie not set until csrf used | pyou can always just drop a code csrftoken code hidden form field anywhere in your template and pick it up by name if the cookie isnt set yet you dont have to put it inside a form tag to be valid htmlp
pjust change your logic to something likep
precodevar csrftoken getcookiecsrftoken inputnamecsrfmiddlewaretokenval
codepre
pthat of course depends on what codegetcookiecode returnsp
| 0 |
nltk conditionalfreqdist to pandas dataframe | pthis is a nice place to use a codecollectionsdefaultdictcodep
precodefrom collections import defaultdict
import pandas as pd
def condfreqdistdata
takes a list of tuples and returns a conditional frequency
distribution as a pandas dataframe
cdf defaultdictdefaultdictint
for cond freq in data
cfdcondfreq 1
return pddataframecfdfillna0
codepre
pstrongexplanationstrong a codedefaultdictcode essentially handles the exception handling in primelenss answer behind the scenes instead of raising codekeyerrorcode when referring to a key that doesnt exist yet a codedefaultdictcode first creates an object for that key using the provided constructor function then continues with that object for the inner codedictcode the default is codeintcode which is code0code to which we then add code1code p
pnote that such an object may not pickle nicely due to the default constructor function in the codedefaultdictscode to pickle a codedefaultdictcode you need to convert to a codedictcode fist codedictmydefaultdictcodep
| 0 |
get the id from url | puse codeurlparsecode or if you really want to use string libs thenp
precodeprefix sep text textpartitionamp
codepre
por just codetext textpartitionamp2codep
| 0 |
execution of python code with m option or not | pthe main reason to run a module or package as a script with m is to simplify deployment especially on windows you can install scripts in the same place in the python library where modules normally go instead of polluting path or global executable directories such as local the peruser scripts directory is ridiculously hard to find in windows p
pthen you just type m and python finds the script automagically for example codepython m pipcode will find the correct pip for the same instance of python interpreter which executes it without m if user has several python versions installed which one would be the global pipp
pif user prefers classic entry points for commandline scripts these can be easily added as small scripts somewhere in path or pip can create these at install time with entrypoints parameter in setuppy p
pso just check for codename maincode and ignore other nonreliable implementation details p
| 0 |
pyspark pyfiles doesnt work | pi was facing a similar kind of problem my worker nodes could not detect the modules even though i was using the codepyfilescode switch p
pthere were couple of things i did first i tried putting import statement after i created sparkcontext sc variable hoping that import should take place after the module has shipped to all nodes but still it did not work i then tried codescaddfilecode to add the module inside the script itself instead of sending it as a command line argument and afterwards imported the functions of the module this did the trick at least in my case p
| 0 |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card- Downloads last month
- 5