content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: python c api to create a python module I'm writing a python module in C, and looking for a way to write a module inside of a module. PyMODINIT_FUNC initA(void) { PyObject* pMod, pSubMod; pMod = Py_InitModule3("A", A_Methods, A_Doc); pSubMod = PyModule_New("B"); PyModule_AddStringConstant(pSubMod, "__doc__", B_Doc...
python c api to create a python module
I'm writing a python module in C, and looking for a way to write a module inside of a module. PyMODINIT_FUNC initA(void) { PyObject* pMod, pSubMod; pMod = Py_InitModule3("A", A_Methods, A_Doc); pSubMod = PyModule_New("B"); PyModule_AddStringConstant(pSubMod, "__doc__", B_Doc); PyModule_AddIntConstant(pSubMod, "SOMETHI...
[ "You haven't actually created an importable module called A.B, since A is not a package. You can't create packages in C, only modules; packages are defined by the filesystem (or by an alternate loader, but that would not be pertinent here).\n" ]
[ 4 ]
[]
[]
[ "c", "python", "python_module" ]
stackoverflow_0008329388_c_python_python_module.txt
Q: How to use Beautiful Soup to extract info out of this in Python <font class="detDesc">Uploaded 10-29&nbsp;18:50, Size 4.36&nbsp;GiB, ULed by <a class="detDesc" href="/user/NLUPPER002/" title="Browse NLUPPER002">NLUPPER002</a></font> I need the Uploaded 10-29 18:50, Size 4.36 GiB and NLUPPER002 in two separate ar...
How to use Beautiful Soup to extract info out of this in Python
<font class="detDesc">Uploaded 10-29&nbsp;18:50, Size 4.36&nbsp;GiB, ULed by <a class="detDesc" href="/user/NLUPPER002/" title="Browse NLUPPER002">NLUPPER002</a></font> I need the Uploaded 10-29 18:50, Size 4.36 GiB and NLUPPER002 in two separate arrays. How do I do it? Edit: This is a part of a html page that has a ...
[ "soup = BeautifulSoup(your_data)\nuploaded = []\nlink_data = []\nfor f in soup.findAll(\"font\", {\"class\":\"detDesc\"}):\n uploaded.append(f.contents[0]) \n link_data.append(f.a.contents[0]) \n\nFor example, using the following data:\nyour_data = \"\"\"\n<font class=\"detDesc\">Uploaded 10-29&nbsp;18:50, S...
[ 2, 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0008328943_beautifulsoup_python.txt
Q: Can I create a static C array with Cython? I'd like to do exactly this in Cython: cdef int shiftIndexes[] = [1,-1, 0, 2,-1, -1, 4, 0, -1, 8, 1, -1, 16, 1, 0, 32, 1, 1, 64, 0, 1, 128, -1, 1] I've seen a few references in fixed bug reports and old email lists that static array functionality exists in Cython, but I ...
Can I create a static C array with Cython?
I'd like to do exactly this in Cython: cdef int shiftIndexes[] = [1,-1, 0, 2,-1, -1, 4, 0, -1, 8, 1, -1, 16, 1, 0, 32, 1, 1, 64, 0, 1, 128, -1, 1] I've seen a few references in fixed bug reports and old email lists that static array functionality exists in Cython, but I can't find anty examples and this particular exa...
[ "Use pointer notation instead:\ncdef int *shiftIndexes = [1,-1, 0, 2,-1, -1, 4, 0, -1, 8, 1, -1, 16, 1, 0, 32, 1, 1, 64, 0, 1, 128, -1, 1]\n\nAnd it will work like a charm.\n" ]
[ 27 ]
[]
[]
[ "arrays", "cython", "python" ]
stackoverflow_0008320951_arrays_cython_python.txt
Q: How to make download manager more robust? I have made this simple download manager, but the problem is it wont work on complex urls, when pages are redirected. def str(d): for i in range(len(d)): if d[-i] == '/': x=-i break s=[] l=len(d)+x+1 print d[l],d[len(d)-1] ...
How to make download manager more robust?
I have made this simple download manager, but the problem is it wont work on complex urls, when pages are redirected. def str(d): for i in range(len(d)): if d[-i] == '/': x=-i break s=[] l=len(d)+x+1 print d[l],d[len(d)-1] s=d[l:] return s import urllib2 url=r...
[ "I think redirection is not a problem here:\nSince urllib2 already follows redirect automatically, google redirects to a page in case of error.\nTry this script :\nurl1 = 'http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=9&ved=0CG0QFjAI&url=http%3A%2F%2Fwww.iasted.org%2Fconferences%2Fformatting%2FPresen...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008329650_python.txt
Q: Python refactoring: cleaning up imports This might be a newbie-type question (I came to python from PHP5 OO), but I have a few things I am uncertain about the import statement in trying to clean up and refactor some of our Python modules. Let's say, for example, I have a db connection factory module that imports m...
Python refactoring: cleaning up imports
This might be a newbie-type question (I came to python from PHP5 OO), but I have a few things I am uncertain about the import statement in trying to clean up and refactor some of our Python modules. Let's say, for example, I have a db connection factory module that imports mysqldb and looks something like this: import ...
[ "\nI believe that MySQLdb.cursors is another module, and that nested modules must be imported separately\nIf you want to specifically catch an exception declared in MySQLdb, then yes, you will have to import something. If you want to catch any exception, then you won't have to import. But this may not be advisabl...
[ 1, 1 ]
[]
[]
[ "import", "python", "refactoring" ]
stackoverflow_0008329442_import_python_refactoring.txt
Q: HTTP basic authentication, using python I want my users to go to a protected directory on my domain. Both .htaccess and .htpasswd are created and reside in the protected library. The html that asks for a username/password combination is: <form method="post" enctype="multipart/form-data" action="bin/logintest.cgi">...
HTTP basic authentication, using python
I want my users to go to a protected directory on my domain. Both .htaccess and .htpasswd are created and reside in the protected library. The html that asks for a username/password combination is: <form method="post" enctype="multipart/form-data" action="bin/logintest.cgi"> Username: <input type="text" name="username"...
[ "The returned object from a urlopen call is much like an open file stream, you need to read it to get the output.\nChange print result to print result.read():\nresult = urllib2.urlopen(request)\n\nprint \"Content-type: text/html\\n\\n\"\nprint result.read()\n\n\nOr, change result = urllib2.urlopen(request) to resul...
[ 1, 1 ]
[]
[]
[ "cgi", "forms", "html", "python" ]
stackoverflow_0008329919_cgi_forms_html_python.txt
Q: How to rename last letter but not the file ending in python Possible Duplicate: How to change last letter of filename to lowercase if it is a letter? This post is a follow-up of my previous post. The Answer below was from Abhijit. It checks the last character of a filename and changes it to lower case if it is ...
How to rename last letter but not the file ending in python
Possible Duplicate: How to change last letter of filename to lowercase if it is a letter? This post is a follow-up of my previous post. The Answer below was from Abhijit. It checks the last character of a filename and changes it to lower case if it is a character. I need to adapt it so that it checks the 5th from l...
[ "Do something like this\n>>> import os\n>>> for root, subFolders, files in os.walk('/tmp'):\n... for f in files:\n... if len(f) < 5: continue\n... newf = f[:-5]+f[-5].lower()+f[-4:]\n... print \"changing\",f,\"to\",newf\n... \n\nbut looks like you want character before extension instead of 5 char? in ...
[ 0 ]
[]
[]
[ "python", "rename" ]
stackoverflow_0008330104_python_rename.txt
Q: Can I get a return value from multiprocessing.Process? I've implemented some simple parallelism in a Monte Carlo code using the Python multiprocessing module. I have code that looks like: montecarlos = [MonteCarlo(f,fargs) for fargs in farglist] jobs = [multiprocessing.Process(mc) for mc in montecarlos] for job in...
Can I get a return value from multiprocessing.Process?
I've implemented some simple parallelism in a Monte Carlo code using the Python multiprocessing module. I have code that looks like: montecarlos = [MonteCarlo(f,fargs) for fargs in farglist] jobs = [multiprocessing.Process(mc) for mc in montecarlos] for job in jobs: job.start() for job in jobs: job.join() results = [mc...
[ "The MonteCarlo objects have been pickled and sent to child processes to be run - the .results attribute in this process isn't populated because the local mc has never been run.\nIf you create a multiprocessing.Queue, you can pass that into each MonteCarlo job, and when it finishes it should put the result in there...
[ 46 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0008329974_multiprocessing_python.txt
Q: How do I use permutation to find all possible words from an input? I am doing a project for my programming class, here are the 5 things that I am working towards. Thanks for your help! list of valid words will be provided in a words.txt ask for input that only accepts a combination of 2-8 letters Ex. input would ...
How do I use permutation to find all possible words from an input?
I am doing a project for my programming class, here are the 5 things that I am working towards. Thanks for your help! list of valid words will be provided in a words.txt ask for input that only accepts a combination of 2-8 letters Ex. input would be "polo" Find all possible valid words of this input from inside words....
[ "as far as the error is concerned \nprint(list1[random].randint(1,length)) should be changed to\nprint(list1[random.randint(1,length)])\n" ]
[ 1 ]
[]
[]
[ "permutation", "python", "python_itertools" ]
stackoverflow_0008329995_permutation_python_python_itertools.txt
Q: python: creating a dictionary Lets say I have a list of strings: ["dog", "cat" ,"boy", "cat", "car", "bus",....] and I want to convert it into a dictionary like that: {"dog": ["cat"], "cat":["boy","car"], "boy": ["cat"], "car":["bus"]....} What is the best way to turn each string in the list to a key and the fo...
python: creating a dictionary
Lets say I have a list of strings: ["dog", "cat" ,"boy", "cat", "car", "bus",....] and I want to convert it into a dictionary like that: {"dog": ["cat"], "cat":["boy","car"], "boy": ["cat"], "car":["bus"]....} What is the best way to turn each string in the list to a key and the following string to the value as a li...
[ "lst = [\"dog\", \"cat\" ,\"boy\", \"cat\", \"car\", \"bus\"]\npairs = zip(lst, lst[1:]) # [(\"dog\", \"cat\"), (\"cat\", \"boy\"), ...]\nd = {}\nfor k,v in pairs:\n d.setdefault(k, []) # Set e.g. d[\"dog\"] to [] if there is no d[\"dog\"] yet\n d[k].append(v)\n\n", "Here is the obligatory defaultdic...
[ 7, 4, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0008330207_dictionary_python.txt
Q: Selenium Grid2 - Is it possible to run 10 Chrome instances? Currently Selenium Grid2 running with the default config shows that it can run 5 firefox browsers, 5 chrome browsers and 1 IE. With a max of 5 instances at the same time. How can I change this so that it runs 10 chrome instances at the same time? I have s...
Selenium Grid2 - Is it possible to run 10 Chrome instances?
Currently Selenium Grid2 running with the default config shows that it can run 5 firefox browsers, 5 chrome browsers and 1 IE. With a max of 5 instances at the same time. How can I change this so that it runs 10 chrome instances at the same time? I have succesfully changed the maxsession parameter of the node with -max...
[ "I figured it out:\nrun the node with the argument of MaxSession, and let the browser Configuration have the MaxInstances parameter, ie: \njava -jar $JARFILE -Dwebdriver.chrome.driver=$CHROMEDRIVER -role webdriver -hub http://$HUB_IP:4444/grid/register -maxSession 10 -browser browserName=chrome,maxInstances=10\"\n\...
[ 7 ]
[]
[]
[ "google_chrome", "python", "selenium_grid", "selenium_webdriver" ]
stackoverflow_0008313310_google_chrome_python_selenium_grid_selenium_webdriver.txt
Q: Executing and saving command line Possible Duplicate: Executing command line programs from within python How to execute single command within python and save everything between command and prompt to variable? I've tried following code: import os var = os.system('ls') Unfortunatelly, my var value is 0 instead 'l...
Executing and saving command line
Possible Duplicate: Executing command line programs from within python How to execute single command within python and save everything between command and prompt to variable? I've tried following code: import os var = os.system('ls') Unfortunatelly, my var value is 0 instead 'ls' output. How can I fix it?
[ "You can use subprocess.check_output. Example from the linked documentation:\n>>> subprocess.check_output([\"echo\", \"Hello World!\"])\n'Hello World!\\n'\n\n" ]
[ 1 ]
[]
[]
[ "command_line", "debian", "python" ]
stackoverflow_0008330934_command_line_debian_python.txt
Q: Why does Python fail to run ant build? If I run ant release in the shell in my dir proj it works fine, however, when I try to execute it from python, it fails, why? /Users/hunterp/proj Buildfile: /Users/hunterp/proj/build.xml BUILD FAILED /Users/hunterp/proj/build.xml:46: sdk.dir is missing. Make sure to generate...
Why does Python fail to run ant build?
If I run ant release in the shell in my dir proj it works fine, however, when I try to execute it from python, it fails, why? /Users/hunterp/proj Buildfile: /Users/hunterp/proj/build.xml BUILD FAILED /Users/hunterp/proj/build.xml:46: sdk.dir is missing. Make sure to generate local.properties using 'android update proj...
[ "It is difficult to answer this question without more information about your setup or the code you are using. Particularly the parts that are generating the error since we don't know what your code looks like (either in build.xml or in your python script).\nAn easy thing to start with, as indicated by @Mark, is to...
[ 0 ]
[]
[]
[ "android", "ant", "environment_variables", "python", "shell" ]
stackoverflow_0008273706_android_ant_environment_variables_python_shell.txt
Q: Find all possible subsets that sum up to a given number I'm learning Python and I have a problem with this seems to be simple task. I want to find all possible combination of numbers that sum up to a given number. for example: 4 -> [1,1,1,1] [1,1,2] [2,2] [1,3] I pick the solution which generate all possible subs...
Find all possible subsets that sum up to a given number
I'm learning Python and I have a problem with this seems to be simple task. I want to find all possible combination of numbers that sum up to a given number. for example: 4 -> [1,1,1,1] [1,1,2] [2,2] [1,3] I pick the solution which generate all possible subsets (2^n) and then yield just those that sum is equal to the ...
[ "Here's some code I saw a few years ago that does the trick:\n>>> def partitions(n):\n if n:\n for subpart in partitions(n-1):\n yield [1] + subpart\n if subpart and (len(subpart) < 2 or subpart[1] > subpart[0]):\n yield [subpart[0] + 1] + subpart[1...
[ 5, 1, 1, 1 ]
[]
[]
[ "algorithm", "python", "subset" ]
stackoverflow_0008330371_algorithm_python_subset.txt
Q: Why the exception handling is not checking existence of library I don't understand why python (at least 2.7) is not validating the exception handling mechanism for errors. Example: try: some code selecting data from pymongo except pymongo.errors.OperationFailure: exception In this case, if the exception i...
Why the exception handling is not checking existence of library
I don't understand why python (at least 2.7) is not validating the exception handling mechanism for errors. Example: try: some code selecting data from pymongo except pymongo.errors.OperationFailure: exception In this case, if the exception is not called for the first time, python will not validate if I actual...
[ "If I'm reading your question right, you want to know why except pymongo.errors.OperationFailure doesn't cause an error when the module is loaded if you haven't already imported the pymongo module.\nLike most things in Python, the arguments to except clauses are evaluated at runtime. In fact, they can be expression...
[ 6, 1, 1 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0008331267_exception_handling_python.txt
Q: using a text file in python Im trying to take a text file and use only the first 30 lines of it in python. this is what I wrote: text = open("myText.txt") lines = myText.readlines(30) print lines for some reason I get more then 150 lines when I print? What am I doing wrong? A: Use itertools.islice import itert...
using a text file in python
Im trying to take a text file and use only the first 30 lines of it in python. this is what I wrote: text = open("myText.txt") lines = myText.readlines(30) print lines for some reason I get more then 150 lines when I print? What am I doing wrong?
[ "Use itertools.islice\nimport itertools\n\nfor line in itertools.islice(open(\"myText.txt\"), 0, 30)):\n print line\n\n", "If you are going to process your lines individually, an alternative could be to use a loop:\nfile = open('myText.txt')\nfor i in range(30):\n line = file.readline()\n # do stuff with...
[ 5, 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008331195_python.txt
Q: Join two lists of dictionaries around a single non-unique key I have 2 lists of dictionaries, say: l1 = [{"customer":"amy", "order":2}, {"customer":"amy", "order":3}, {"customer":"basil", "order":4}] l2 = [{"customer":"amy", "died":"who fell down the stairs"}, {"customer":'basil', "died":"assaulted by bears"}] I ...
Join two lists of dictionaries around a single non-unique key
I have 2 lists of dictionaries, say: l1 = [{"customer":"amy", "order":2}, {"customer":"amy", "order":3}, {"customer":"basil", "order":4}] l2 = [{"customer":"amy", "died":"who fell down the stairs"}, {"customer":'basil', "died":"assaulted by bears"}] I am looking for an elegant way of taking the keys from l2 and puttin...
[ "Easy:\nSELECT *\nFROM l1, l2\nWHERE l1.customer = l2.customer\n\n...just kidding...\ndef join(t1,t2,column):\n result = []\n for entry in t2:\n for match in [d for d in t1 if d[column] == entry[column]]:\n result.append(dict((k,v) for k,v in entry.items()+match.items()))\n return result\...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008331373_python.txt
Q: How to recursively loop through a file structure and rename directories in python I would like to resursively rename directories by changing the last character to lowercase (if it is a letter) I have done this with the help of my previous posts (sorry for the double posting and not acknowledging the answers) This ...
How to recursively loop through a file structure and rename directories in python
I would like to resursively rename directories by changing the last character to lowercase (if it is a letter) I have done this with the help of my previous posts (sorry for the double posting and not acknowledging the answers) This code works for Files, but how can I adapt it for directories as well? import fnmatch im...
[ "The problem is that the default of os.walk is topdown. If you try to rename directories while traversing topdown, the results are unpredictable. \nTry setting os.walk to go bottom up:\nfor root, subFolders, files in os.walk(rootdir,topdown=False):\n\nEdit\nAnother problem you have is listFiles() is returning, well...
[ 7 ]
[]
[]
[ "directory", "python", "rename" ]
stackoverflow_0008331446_directory_python_rename.txt
Q: wxpython , NameError: global name 'SetTopWindow' is not defined In certain pieces of my app, saying SetTopWindow(self.configFrame) works just fine, but in others, it borks out with: NameError: global name 'SetTopWindow' is not defined code: self.configFrame = configFrame(parent=self, id=-1, title='blabla Config...
wxpython , NameError: global name 'SetTopWindow' is not defined
In certain pieces of my app, saying SetTopWindow(self.configFrame) works just fine, but in others, it borks out with: NameError: global name 'SetTopWindow' is not defined code: self.configFrame = configFrame(parent=self, id=-1, title='blabla Configuration') self.configFrame.Show() SetTopWindow(self.configFrame) Im ...
[ "That's app.SetTopWindow, where app is your wx.App.\n", "SetTopWindow is an wx.App method, as indicated by @larsmans.\nYou can not use self.SetTopWindow for a wx.Frame instance because it is not a wx.Frame method.\nNeither can be used as SetTopWindow() as in line 119 in your code because it is not any function yo...
[ 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008262655_python_wxpython.txt
Q: Scraping with BeautifulSoup and multiple paragraphs I'm trying to scrape a speech from a website using BeautifulSoup. I'm encountering problems, however, since the speech is divided into many different paragraphs. I'm extremely new to programming and am having trouble figuring out how to deal with this. The HTML o...
Scraping with BeautifulSoup and multiple paragraphs
I'm trying to scrape a speech from a website using BeautifulSoup. I'm encountering problems, however, since the speech is divided into many different paragraphs. I'm extremely new to programming and am having trouble figuring out how to deal with this. The HTML of the page looks like this: <span class="displaytext">Tha...
[ "import urllib2,sys\nfrom BeautifulSoup import BeautifulSoup\n\naddress = 'http://www.presidency.ucsb.edu/ws/index.php?pid=29644&st=&st1=#axzz1fD98kGZW'\nsoup = BeautifulSoup(urllib2.urlopen(address).read())\n\nspan = soup.find(\"span\", {\"class\":\"displaytext\"}) # span.string gives you the first bit\nparas = [...
[ 8, 2, 0 ]
[]
[]
[ "beautifulsoup", "python", "web_scraping" ]
stackoverflow_0008331579_beautifulsoup_python_web_scraping.txt
Q: Python method that is also a generator function? I'm trying to build a method that also acts like a generator function, at a flip of a switch (want_gen below). Something like: def optimize(x, want_gen): # ... declaration and validation code for i in range(100): # estimate foo, bar, baz # .....
Python method that is also a generator function?
I'm trying to build a method that also acts like a generator function, at a flip of a switch (want_gen below). Something like: def optimize(x, want_gen): # ... declaration and validation code for i in range(100): # estimate foo, bar, baz # ... some code here x = calculate_next_x(x, foo,...
[ "An edit to my answer, why not just always yield? You can have a function which yields a single value. If you don't want that then just choose to have your function either return a generator itself or the value:\n def stuff(x, want_gen):\n if want_gen:\n def my_gen(x):\n #code with yield\n...
[ 3, 3, 3, 2, 1, 0, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0005432121_generator_python.txt
Q: how to compile Nginx when it will be used with Tornado first there is this jewel: the best explication for nginx configuration and i've found that it will be better to compile the source only with what we'll need! so my questions are simple: Which are modules that will only need when compiling Nginx when it will u...
how to compile Nginx when it will be used with Tornado
first there is this jewel: the best explication for nginx configuration and i've found that it will be better to compile the source only with what we'll need! so my questions are simple: Which are modules that will only need when compiling Nginx when it will used only to serve static file. Is it useful to make compile ...
[ "The easiest and most reliable method will be to use nginx as a reverse proxy for tornado. Have nginx handle all the frontend connections, as well as SSL. This will also allow you to run multiple tornado processes (up to # of CPU cores) if you need more processing power.\nAny other configuration will depend on your...
[ 3 ]
[]
[]
[ "nginx", "python", "tornado" ]
stackoverflow_0008332239_nginx_python_tornado.txt
Q: Recovering encrypted word using dictonary in python I'm trying to recover an RSA encrypted 5 character word using a forward search dictionary attack in Python but having difficulty. The word was encrypted in 2 24 bit blocks (3648141 5604637) padding last block with a space e = 5 n = 21508387 table = {} for ptext ...
Recovering encrypted word using dictonary in python
I'm trying to recover an RSA encrypted 5 character word using a forward search dictionary attack in Python but having difficulty. The word was encrypted in 2 24 bit blocks (3648141 5604637) padding last block with a space e = 5 n = 21508387 table = {} for ptext in range(65,90): ctext = pow(ptext,e,n) table[cte...
[ "Generate all three-letter combinations, encode them as integer, apply the pow function, report when they match your encrypted message.\nThe most obvious way to iterate through all three letter combinations is with three nested loops instead of the one you have right now.\n" ]
[ 1 ]
[]
[]
[ "dictionary", "encryption", "python", "rsa", "search" ]
stackoverflow_0008331909_dictionary_encryption_python_rsa_search.txt
Q: How to rotate the xlabels while adding another yaxis? For some reason, after i add a second y axis to my plot fig.plt.figure() ax = plt.Axes(fig) fig.add_axes(ax) ax2 = ax.twinx() fig.add_axes(ax2) The xticklabels are no longer rotated!? fig.autofmt_xdate(rotation = num) Does anyone know why this is happening? ...
How to rotate the xlabels while adding another yaxis?
For some reason, after i add a second y axis to my plot fig.plt.figure() ax = plt.Axes(fig) fig.add_axes(ax) ax2 = ax.twinx() fig.add_axes(ax2) The xticklabels are no longer rotated!? fig.autofmt_xdate(rotation = num) Does anyone know why this is happening? I can comment out the last two lines: #ax2 = ax.twinx() #fi...
[ "Place fig.autofmt_xdate(rotation = num) after the statement defining ax but before the call to ax.twinx() and :\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as md\nimport datetime as dt\nimport numpy as np\n\nnp.random.seed(0)\nt=md.drange(dt.datetime(2009,10,1),\n dt.datetime(2010,1,15),\n...
[ 7 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008332395_matplotlib_python.txt
Q: spinner class thread error - only one thread allowed I already asked a question about this yesterday, but now I have another :) im trying to write a text effects type class for my terminal apps to use - it does stuff like position cursor, clear screen, colour selection inside the echo string with colours preceded ...
spinner class thread error - only one thread allowed
I already asked a question about this yesterday, but now I have another :) im trying to write a text effects type class for my terminal apps to use - it does stuff like position cursor, clear screen, colour selection inside the echo string with colours preceded by an '@', random case, colour cylcling and other fun stuf...
[ "Only the run method is actually running in a diffrent thread. The problem with your code is that you try to start the thread more than one time (in the echo method). You should check if the thread is already started (look at self._stop) before starting.\ndef echo (self, arg=None, sep=' ', end='\\n', rndcase=True, ...
[ 0 ]
[]
[]
[ "class", "multithreading", "python" ]
stackoverflow_0008331470_class_multithreading_python.txt
Q: Is it safe to call os.unlink(__file__) in Python? I'm using Python 2.6 on linux. I have a run.py script which starts up multiple services in the background and generates kill.py to kill those processes. Inside kill.py, is it safe to unlink itself when it's done its job? import os # kill services os.unlink(__file__...
Is it safe to call os.unlink(__file__) in Python?
I'm using Python 2.6 on linux. I have a run.py script which starts up multiple services in the background and generates kill.py to kill those processes. Inside kill.py, is it safe to unlink itself when it's done its job? import os # kill services os.unlink(__file__) # is it safe to do something here? I'm new to Python...
[ "Don't have your scripts write new scripts if you can avoid it – just write out a list of the PIDs, and then through them.\nIt's not very clear what you're trying to do, but creating and deleting scripts sounds like too much fragile magic.\nTo answer the question:\nPython compiles all of the source and closes the f...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0008333658_linux_python.txt
Q: While iterating through a dictionary inside a dictionary, more that one key gets modified despite the break statement I found this very weird bug that I can't understand. First of all inside this function I unpickle: tableOrders = pickle.load(open("\\\\VIERNES7-3\Documentos c\sharedTableOrders.p","rb")) If I do p...
While iterating through a dictionary inside a dictionary, more that one key gets modified despite the break statement
I found this very weird bug that I can't understand. First of all inside this function I unpickle: tableOrders = pickle.load(open("\\\\VIERNES7-3\Documentos c\sharedTableOrders.p","rb")) If I do pprint(tableOrders) I get: {1: {'blink': False, 'canceled': 'no', 'orders': [{u'availability': u'si', ...
[ "Problem is in the object you are pickling, surely there both objects are same e.g.\n>>> import pickle\n>>> d = {'name':'same'}\n>>> ds = pickle.dumps([d,d])\n>>> newd = pickle.loads(ds)\n>>> newd[0]['name'] = 'different'\n>>> newd\n[{'name': 'different'}, {'name': 'different'}]\n\nSo look into the object you are p...
[ 1 ]
[]
[]
[ "dictionary", "loops", "pickle", "python" ]
stackoverflow_0008333512_dictionary_loops_pickle_python.txt
Q: How to get rows having certain difference? If I have a table like this: CREATE TABLE #TEMP (id1 int, id2 int, val int) INSERT INTO #TEMP VALUES(0, 0, 0) INSERT INTO #TEMP VALUES(0, 1, 1) INSERT INTO #TEMP VALUES(0, 2, 2) INSERT INTO #TEMP VALUES(0, 3, 3) INSERT INTO #TEMP VALUES(0, 4, 4) INSERT INTO #TEMP VALUES(...
How to get rows having certain difference?
If I have a table like this: CREATE TABLE #TEMP (id1 int, id2 int, val int) INSERT INTO #TEMP VALUES(0, 0, 0) INSERT INTO #TEMP VALUES(0, 1, 1) INSERT INTO #TEMP VALUES(0, 2, 2) INSERT INTO #TEMP VALUES(0, 3, 3) INSERT INTO #TEMP VALUES(0, 4, 4) INSERT INTO #TEMP VALUES(0, 5, 5) INSERT INTO #TEMP VALUES(1, 0, 0) INSER...
[ "I would drop the indexes and try and create an index on val only. This is the part that decides what should be returned. It might encourage the optimizer to evaluate the difference first thus only then joining there after where the difference is known to be 1 as oppose to joining all the data first only to find ...
[ 1, 0, 0 ]
[]
[]
[ "database", "python", "sql", "sqlite" ]
stackoverflow_0008024716_database_python_sql_sqlite.txt
Q: Multideep django query I have a model like this: class AttributeType(models.Model): name = models.CharField(max_length=32) class Attribute(models.Model): # Server attributes ...
Multideep django query
I have a model like this: class AttributeType(models.Model): name = models.CharField(max_length=32) class Attribute(models.Model): # Server attributes ...
[ "I guess the best you can do is something like this! so it will return all systems at once! but you still have to do 2 queries! which is not a big deal, MySQL sometimes behaviour better having 2 queries then one with a lot JOINs.\natt = AttributeType.objects.values_list('name', flat=True)\nfor a in Server.attribute...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0008333409_django_django_models_python.txt
Q: Using subprocess in a curses application I'm creating an application that uses curses to build a simple user interface. It also uses the subprocess module to run external text editor so a user can type some text, then close the editor and go back to the main program. The problem is that when the editor is console-...
Using subprocess in a curses application
I'm creating an application that uses curses to build a simple user interface. It also uses the subprocess module to run external text editor so a user can type some text, then close the editor and go back to the main program. The problem is that when the editor is console-based such as Vim or Nano, curses doesn't de-i...
[ "Would modifying your code to:\nif c == ord('q'):\n subprocess.call('reset', shell=False)\n break\n\nbe enough for you? Or is there some additional behaviour in your real script that is not in the code you pasted here, that makes this workaround unsuitable to your goal?\n" ]
[ 0 ]
[]
[]
[ "curses", "python", "subprocess" ]
stackoverflow_0008333945_curses_python_subprocess.txt
Q: How to override constructor of Python class with many arguments? Say, I have a class Foo, extending class Bar. And I want to slightly override Foo's consructor. And I don't want even know what signarure of Bar's constructors is. Is there a way to do this? If you didn't understand, I mean the following: class Bar: ...
How to override constructor of Python class with many arguments?
Say, I have a class Foo, extending class Bar. And I want to slightly override Foo's consructor. And I don't want even know what signarure of Bar's constructors is. Is there a way to do this? If you didn't understand, I mean the following: class Bar: def __init__ (self, arg1=None, arg2=None, ... argN=None): ......
[ "class Parent(object):\n def __init__(self, a, b):\n print 'a', a\n print 'b', b\n\nclass Child(Parent):\n def __init__(self, c, d, *args, **kwargs):\n print 'c', c\n print 'd', d\n super(Child, self).__init__(*args, **kwargs)\n\ntest = Child(1,2,3,4)\n\nOutput:\n\nc 1\nd 2\...
[ 52, 11 ]
[]
[]
[ "constructor", "python" ]
stackoverflow_0008333354_constructor_python.txt
Q: How to limit length of data in a cell of excel reports I am creating a report in excel format.I am fetching data from fields of database and writing it in cell of excel sheet.But for one field the data is too long,such that it spreads in many columns.What can I do to ,so that the data remains within that cell and ...
How to limit length of data in a cell of excel reports
I am creating a report in excel format.I am fetching data from fields of database and writing it in cell of excel sheet.But for one field the data is too long,such that it spreads in many columns.What can I do to ,so that the data remains within that cell and is displayed more when we stretch the column.I tried increas...
[ "I think that most spreadsheet programs will let long text flow out of cells into neighbouring cells if those neighbours are blank. Try putting an X in the next cell to see if it stops the text from flowing. If that works, then experiment with a space or a non-breaking space character.\n", "Format the cell with t...
[ 0, 0 ]
[]
[]
[ "openerp", "python" ]
stackoverflow_0008308447_openerp_python.txt
Q: Unordered collection for unhashable objects? I've got a dict where some of the values are not hashable. I need some way to compare two unordered groups of these to ensure they contain equal elements. I can't use lists because list equality takes the order into account but sets won't work because dicts aren't hash...
Unordered collection for unhashable objects?
I've got a dict where some of the values are not hashable. I need some way to compare two unordered groups of these to ensure they contain equal elements. I can't use lists because list equality takes the order into account but sets won't work because dicts aren't hashable. I had a look through the python docs, and th...
[ "When duplicate entries don't exist, the usual choices are:\n\nIf the elements are hashable: set(a) == set(b)\nIf the elements are orderable: sorted(a) == sorted(b)\nIf all you have is equality: len(a) == len(b) and all(x in b for x in a)\n\nIf you have duplicates and their multiplicity matters, the choices are:\...
[ 14, 2 ]
[]
[]
[ "collections", "python" ]
stackoverflow_0008332710_collections_python.txt
Q: Python pickle syntax I'm using the latest python release and after searching, I can't seem to find anything on pickles that will work for me. I am simply going through tutorials attempting to learn about pickling and none of the source code that apparently works on the tutorials will work for me, I suspect this i...
Python pickle syntax
I'm using the latest python release and after searching, I can't seem to find anything on pickles that will work for me. I am simply going through tutorials attempting to learn about pickling and none of the source code that apparently works on the tutorials will work for me, I suspect this is something to do with the...
[ "The 'a+' mode may be causing you problems. And, if you're on Windows, it would be useful to open a file in a binary mode. Also, you should close the file before reopening to read it back in. And make sure you're writing and reading the same file ('log.txt' vs. 'filename'):\nimport pickle \nlists = [1,2,3,4,5]\n...
[ 2 ]
[]
[]
[ "io", "pickle", "python" ]
stackoverflow_0008334364_io_pickle_python.txt
Q: Django. Business Logic Bottlenecks. Is there any smart way to find bottlenecks in business logic. For example, we have application, that have one view that doing HttpResponse('1') in big project. We are sure, that no SQL queries in middlewares exists. But HttpResponse working really slow(50 rps vs 200 rps on clear...
Django. Business Logic Bottlenecks.
Is there any smart way to find bottlenecks in business logic. For example, we have application, that have one view that doing HttpResponse('1') in big project. We are sure, that no SQL queries in middlewares exists. But HttpResponse working really slow(50 rps vs 200 rps on clear django project). What reasons can be? ...
[ "The debug toolbar works well, but I also like running django-devserver. It can give you more information than you can process sometimes.\nDEVSERVER_MODULES = (\n 'devserver.modules.sql.SQLRealTimeModule',\n 'devserver.modules.sql.SQLSummaryModule',\n 'devserver.modules.profile.ProfileSummaryModule',\n\n ...
[ 1, 0, 0, 0 ]
[]
[]
[ "django", "performance", "python", "views" ]
stackoverflow_0008327300_django_performance_python_views.txt
Q: What happens to Numpy/Scipy pointers when they are copied to local variable? I am aware that numpy arrays are pointer arrays. And I know that is possible to define pointers in python. But I am wondering, if I make a variable equal to an element in a numpy vector, is it still a pointer or is it de-referenced? Is...
What happens to Numpy/Scipy pointers when they are copied to local variable?
I am aware that numpy arrays are pointer arrays. And I know that is possible to define pointers in python. But I am wondering, if I make a variable equal to an element in a numpy vector, is it still a pointer or is it de-referenced? Is there a way I can find out or test this? Example import scipy vec = scipy...
[ "You almost have it, but here is how to create a view of a single element:\nIn [1]: import numpy as np\n\nIn [23]: v = np.arange(10)\n\nIn [24]: a = v[3:4]\n\nIn [25]: a[0] = 100\n\nIn [26]: v\nOut[26]: array([ 0, 1, 2, 100, 4, 5, 6, 7, 8, 9])\n\nHere a is a view of the fourth element of v, so when...
[ 4, 1 ]
[]
[]
[ "numpy", "pointers", "python", "scipy" ]
stackoverflow_0008320109_numpy_pointers_python_scipy.txt
Q: Recursive find and replace of attribute names on a nested Python object A third party has provided me with a data structure that's a bunch of nested Python objects. It is strictly a tree. Some of the attribute names on these objects are Python reserved words such that attempting to access them results in a SyntaxE...
Recursive find and replace of attribute names on a nested Python object
A third party has provided me with a data structure that's a bunch of nested Python objects. It is strictly a tree. Some of the attribute names on these objects are Python reserved words such that attempting to access them results in a SyntaxError: >>> print mat['model'].rules[8].def.blocklabel File "<stdin>", line...
[ "Here's the not-very-general answer for those of you who, like me, are dealing with scipy.io.loadmat() and just want to move on with your day:\nfrom scipy.io.matlab.mio5_params import mat_struct as matlab_struct\ndef recursive_rename( obj,oldattr,newattr ) : \n if isinstance(obj,matlab_struct) :\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008334277_python.txt
Q: Passing argument from a list I have a function that I'm using and I need to pass it a list of arguments, however, it gives an error when I try to pass the list because it can't hash. The function in question here is the values() method on a Django Queryset, but I think this is a more general python question. So I ...
Passing argument from a list
I have a function that I'm using and I need to pass it a list of arguments, however, it gives an error when I try to pass the list because it can't hash. The function in question here is the values() method on a Django Queryset, but I think this is a more general python question. So I have: values_list = ['arg1', 'arg2...
[ "you need to use list unpacking\nmodels.MyModel.objects.values(*values_list).all()\n\n(note the asterisk)\n", "can you use a tuple instead of a list? a tuple is hashable.\n", "It makes sense to make values_list as a tuple instead of a list, but if you can't alter the values method, then list unpacking is the wa...
[ 8, 0, 0 ]
[]
[]
[ "django", "list", "python" ]
stackoverflow_0008334162_django_list_python.txt
Q: How do I install Python/Django Modules? I know absolutely nothing about Django, but I am needing to get an existing project running in OSX. From the project's directory I run python manage.py runserver and get the error: Error: No module named cms. Seems like the INSTALLED_APPS constant (in settings.py) defines...
How do I install Python/Django Modules?
I know absolutely nothing about Django, but I am needing to get an existing project running in OSX. From the project's directory I run python manage.py runserver and get the error: Error: No module named cms. Seems like the INSTALLED_APPS constant (in settings.py) defines the required modules... but how do I install...
[ "you can install all dependencies in once, if there is a requirements.txt file! you just have to run the follow command:\npip install -r requirements.txt\n\notherwise you can install one by one:\npip install django-cms\n\nHere is the PIP documentation:\nhttp://pypi.python.org/pypi/pip\nif you are used to ruby, you ...
[ 32, 9 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008334614_django_python.txt
Q: How can I print a string using .format(), and print literal curly brackets around my replaced string Possible Duplicate: How can I print a literal “{}” characters in python string and also use .format on it? Basically, I want to use .format(), like this: my_string = '{{0}:{1}}'.format('hello', 'bonjour') And ha...
How can I print a string using .format(), and print literal curly brackets around my replaced string
Possible Duplicate: How can I print a literal “{}” characters in python string and also use .format on it? Basically, I want to use .format(), like this: my_string = '{{0}:{1}}'.format('hello', 'bonjour') And have it match: my_string = '{hello:bonjour}' #this is a string with literal curly brackets However, the fi...
[ "Here is the new style:\n>>> '{{{0}:{1}}}'.format('hello', 'bonjour')\n'{hello:bonjour}'\n\nBut I thinking escaping is somewhat hard to read, so I prefer to switch back to the older style to avoid escaping:\n>>> '{%s:%s}' % ('hello', 'bonjour')\n'{hello:bonjour}'\n\n" ]
[ 28 ]
[]
[]
[ "curly_brackets", "formatting", "python", "string", "string_formatting" ]
stackoverflow_0008334792_curly_brackets_formatting_python_string_string_formatting.txt
Q: Is this a Python 3 bug on str.format? sqlstring = 'INSERT INTO {}' table = 'Product' sqlstring.format(table) does not result to 'INSERT INTO Product' but still 'INSERT INTO {}' why is this so? A: Python 3.2 does this correctly: $ python3.2 Python 3.2.2 (default, Sep 5 2011, 22:09:30) [GCC 4.6.1] on linux2 Typ...
Is this a Python 3 bug on str.format?
sqlstring = 'INSERT INTO {}' table = 'Product' sqlstring.format(table) does not result to 'INSERT INTO Product' but still 'INSERT INTO {}' why is this so?
[ "Python 3.2 does this correctly:\n$ python3.2\nPython 3.2.2 (default, Sep 5 2011, 22:09:30) \n[GCC 4.6.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> sqlstring = 'INSERT INTO {}'\n>>> table = 'Product'\n>>> sqlstring.format(table)\n'INSERT INTO Product'\n>>> \n\nW...
[ 5, 5 ]
[]
[]
[ "cpython", "python", "python_3.2", "python_3.x" ]
stackoverflow_0008334875_cpython_python_python_3.2_python_3.x.txt
Q: How to get around memory allocation error in python nosetest? I have a python script to allocate a huge memory space and eventually ended up overflow. Is there anyway nosetests can peacefully handle this? A: Unfortunately the only way to survive such a thing would be to have your test fixture run that particular...
How to get around memory allocation error in python nosetest?
I have a python script to allocate a huge memory space and eventually ended up overflow. Is there anyway nosetests can peacefully handle this?
[ "Unfortunately the only way to survive such a thing would be to have your test fixture run that particular test in a subcommand using subprocess.Popen(), and capture its output and error code so that you can see the nonzero error code and “out of memory” traceback that result. Note that sys.executable is the full p...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008334999_python.txt
Q: Scraping multiple pages for parsing in Beautiful Soup I'm trying to scrape multiple pages off of a single website for BeautifulSoup to parse. So far, I've tried using urllib2 to do this, but have been encountering some problems. What I've attempted is: import urllib2,sys from BeautifulSoup import BeautifulSoup fo...
Scraping multiple pages for parsing in Beautiful Soup
I'm trying to scrape multiple pages off of a single website for BeautifulSoup to parse. So far, I've tried using urllib2 to do this, but have been encountering some problems. What I've attempted is: import urllib2,sys from BeautifulSoup import BeautifulSoup for numb in ('85753', '87433'): address = ('http://www.pr...
[ "You need to put the rest of the code inside the loop. Right now you're iterating over both items in the tuple, but at the end of the iteration only the last item remains assigned to address which subsequently gets parsed outside the loop.\n", "Here's a tidier solution (using lxml):\nimport lxml.html as lh\n\nro...
[ 1, 1, 1 ]
[]
[]
[ "python", "urllib2", "web_scraping" ]
stackoverflow_0008334805_python_urllib2_web_scraping.txt
Q: Is there a way to negate a boolean returned to variable? I have a Django site, with an Item object that has a boolean property active. I would like to do something like this to toggle the property from False to True and vice-versa: def toggle_active(item_id): item = Item.objects.get(id=item_id) item.active...
Is there a way to negate a boolean returned to variable?
I have a Django site, with an Item object that has a boolean property active. I would like to do something like this to toggle the property from False to True and vice-versa: def toggle_active(item_id): item = Item.objects.get(id=item_id) item.active = !item.active item.save() This syntax is valid in many ...
[ "You can do this:\nitem.active = not item.active\n\nThat should do the trick :)\n", "I think you want\nitem.active = not item.active\n\n", "item.active = not item.active is the pythonic way\n", "Another (less concise readable, more arithmetic) way to do it would be:\nitem.active = bool(1 - item.active)\n\n", ...
[ 162, 17, 14, 10, 7, 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008335029_django_python.txt
Q: Python os.dup and side-effects At the beginning of my python script I do: if '-' in args: fd = os.fdopen(os.dup(0)) sys.stderr.write(fd.read()) fd.close() I thought that this wouldn't affect the behavior of the rest of my program but it seems to, i.e. if I comment out these 4 lines my code works but if they...
Python os.dup and side-effects
At the beginning of my python script I do: if '-' in args: fd = os.fdopen(os.dup(0)) sys.stderr.write(fd.read()) fd.close() I thought that this wouldn't affect the behavior of the rest of my program but it seems to, i.e. if I comment out these 4 lines my code works but if they are executed then my program has un...
[ "You are not, alas, using os.dup() correctly. Evidently you want to “look ahead” in the Standard Input stream to see what will be there, and print it out, but then have the rest of the program start up and see the same input still sitting there waiting on the Standard Input. (Is my guess correct that you are doing ...
[ 2, 0 ]
[]
[]
[ "linux", "pipe", "python", "system" ]
stackoverflow_0007115704_linux_pipe_python_system.txt
Q: Python unittest and discovery I have directories, which contain files named like: test_foo.py Each file is a test case. I would like to Run all the tests in a directory from the command line. I am using unittest2, since we are running Python 2.5.1. From one of these directories I tried typing this at the command ...
Python unittest and discovery
I have directories, which contain files named like: test_foo.py Each file is a test case. I would like to Run all the tests in a directory from the command line. I am using unittest2, since we are running Python 2.5.1. From one of these directories I tried typing this at the command line: python -m unittest2 discover...
[ "I ran into the same issue when running python -m unittest discover. Here is a good checklist to verify your setup. Nose is more flexible with the allowed configurations, but not necessarily better.\n\nMake sure all files/directories start with test. Do not use test-something.py, since that is not a valid Python mo...
[ 86, 59, 27 ]
[]
[]
[ "discovery", "python", "unit_testing" ]
stackoverflow_0003295386_discovery_python_unit_testing.txt
Q: Adding a string to a list using augmented assignment >>> b = [] >>> c = '1234' >>> b += c >>> b ['1', '2', '3', '4'] >>> What is happening here? This should not work, right? Or am I missing something obvious? >>> b = [] >>> c = '1234' >>> b + c Traceback (most recent call last): File "<pyshell#7>", line 1, in ...
Adding a string to a list using augmented assignment
>>> b = [] >>> c = '1234' >>> b += c >>> b ['1', '2', '3', '4'] >>> What is happening here? This should not work, right? Or am I missing something obvious? >>> b = [] >>> c = '1234' >>> b + c Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> b + c TypeError: can only concatenate list (n...
[ "Strings are iterable: the elements are the string's characters. When you add an iterable to a list, the iterable's elements get appended to the list.\nEither of the following will do what you're expecting (i.e. append the string, not extend the list with the string's characters):\nb += [c]\n\nor \nb.append(c)\n\n"...
[ 15, 10, 3, 2, 2, 0, 0 ]
[]
[]
[ "augmented_assignment", "list", "python", "string" ]
stackoverflow_0008322792_augmented_assignment_list_python_string.txt
Q: Python - A keyboard command to stop infinite loop? Possible Duplicate: Why can't I handle a KeyboardInterrupt in python? I was playing around with some Python code and created an infinite loop: y = 0 x = -4 itersLeft = x while(itersLeft<0): y = y + x itersLeft = itersLeft - 1 print "y = ",y, "itersL...
Python - A keyboard command to stop infinite loop?
Possible Duplicate: Why can't I handle a KeyboardInterrupt in python? I was playing around with some Python code and created an infinite loop: y = 0 x = -4 itersLeft = x while(itersLeft<0): y = y + x itersLeft = itersLeft - 1 print "y = ",y, "itersLeft = ", itersLeft print y Is there a keyboard shortc...
[ "Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.\nEdit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you nee...
[ 33 ]
[]
[]
[ "aptana", "command_line", "infinite_loop", "keyboard_shortcuts", "python" ]
stackoverflow_0008335184_aptana_command_line_infinite_loop_keyboard_shortcuts_python.txt
Q: Is anyone using Python for GS1 XML and AS2 EDI? I'm helping some manufacturing companies link up their EDI systems using the GS1 XML specs (this is an international spec for companies to pass things like purchase-orders, invoices, barcodes etc. http://en.wikipedia.org/wiki/GS1). There are lots of Big Iron solution...
Is anyone using Python for GS1 XML and AS2 EDI?
I'm helping some manufacturing companies link up their EDI systems using the GS1 XML specs (this is an international spec for companies to pass things like purchase-orders, invoices, barcodes etc. http://en.wikipedia.org/wiki/GS1). There are lots of Big Iron solutions, and lots of Java and C# solutions, and even a coup...
[ "I worked with GS1 XML specs.\nNothing special, just very baroque.\nfor edi I use bots (http://bots.sourceforge.net)\nfor AS2 (bots does not do AS2) http://opensource.mendelson-e-c.com/\n", "Followup.\nI made the original post back in September. It's now December and the system is complete.\nIn the end I did use ...
[ 6, 5 ]
[]
[]
[ "edi", "python" ]
stackoverflow_0007426951_edi_python.txt
Q: White border on a transparent QSplashScreen image in PyQt Google though I tried, I cannot seem to figure out how to get rid of the white border I'm getting around a png I'm serving to a QSplashScreen. I've seen this article, but I don't know how to translate that to PyQt, or whether that's even what I want. I've...
White border on a transparent QSplashScreen image in PyQt
Google though I tried, I cannot seem to figure out how to get rid of the white border I'm getting around a png I'm serving to a QSplashScreen. I've seen this article, but I don't know how to translate that to PyQt, or whether that's even what I want. I've even tried setting a black and white mask separately which ach...
[ "So long as you use an image with clean transparent areas, it should only be necessary to pass a mask of it to QSplashScreen.setMask.\nThis script works as expected for me on Linux:\nfrom PyQt4 import QtGui, QtCore\n\ndef show_splash(path):\n image = QtGui.QPixmap(path)\n splash = QtGui.QSplashScreen(image)\n...
[ 3 ]
[]
[]
[ "pyqt", "python", "splash_screen", "windows_7" ]
stackoverflow_0008332704_pyqt_python_splash_screen_windows_7.txt
Q: How to make my program not add a repeat to my list? Python I need my python program to not add the same letter in the list. There can be no repeats. This is my current code: common = [] for letter in first and last: if letter in first and last: common.append(letter) print common EDIT: Ok I did this and it ...
How to make my program not add a repeat to my list? Python
I need my python program to not add the same letter in the list. There can be no repeats. This is my current code: common = [] for letter in first and last: if letter in first and last: common.append(letter) print common EDIT: Ok I did this and it seems to work. for letter in first and last: if letter in f...
[ "Python doesn't understand verbal logic. Tell the interpreter exactly what you mean:\nif (letter in first) and (letter in last) and (letter not in common):\n\n", "Do you need the list to be in the same order that you read it in? One approach is to first make a set object, add everything to the set, then make the ...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008335741_python.txt
Q: Create classes that grab youtube queries and display information using Python I want to use the urllib module to send HTTP requests and grab data. I can get the data by using the urlopen() function, but not really sure how to incorporate it into classes. I really need help with the query class to move forward. F...
Create classes that grab youtube queries and display information using Python
I want to use the urllib module to send HTTP requests and grab data. I can get the data by using the urlopen() function, but not really sure how to incorporate it into classes. I really need help with the query class to move forward. From the query I need to pull • Top Rated • Top Favorites • Most Viewed • Most Recen...
[ "I assume that your challenge is parsing XML.\nresults_str = top_rated.read()\nsplittedlist = results_str.split('<entry')\n\nAnd I see you are using string functions to parse XML. Such functions based on finite automata (regular languages) are NOT suited for parsing context-free languages such as XML. Expect it to ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008318766_python.txt
Q: Python 3.x and TestLink xmlprc Appreciate your helping first, I am new for the python 3.x. When I try to use Python 3.x to parse the testlink xmlprc server. I got below error, but I can run the code under Python 2.x, any idea? import xmlrpc.client server = xmlrpc.client.Server("http://172.16.29.132/SITM/lib/api/x...
Python 3.x and TestLink xmlprc
Appreciate your helping first, I am new for the python 3.x. When I try to use Python 3.x to parse the testlink xmlprc server. I got below error, but I can run the code under Python 2.x, any idea? import xmlrpc.client server = xmlrpc.client.Server("http://172.16.29.132/SITM/lib/api/xmlrpc.php") //here is my testlink se...
[ "When I've seen this message before, it happened because the contents of the transported data wasn't escaped for XML transport. The solution was to wrap the data in an XMLRPC Binary object.\nIn your case, you don't control the server side, so the above isn't a solution for you but it may suggest what the actual pr...
[ 0, 0 ]
[]
[]
[ "python", "xml_rpc" ]
stackoverflow_0008293650_python_xml_rpc.txt
Q: Python / Redis : Get Bitset string I'm wondering how i can get the string value of a bitset in redis, i have the following code : import redis as redis def main(): redisClient = redis.StrictRedis(host='localhost', port=6379, db=0) redisClient.setbit("mybitset",5,1) bitset=redisClient.get("mybitset") ...
Python / Redis : Get Bitset string
I'm wondering how i can get the string value of a bitset in redis, i have the following code : import redis as redis def main(): redisClient = redis.StrictRedis(host='localhost', port=6379, db=0) redisClient.setbit("mybitset",5,1) bitset=redisClient.get("mybitset") print bitset # expect the output to ...
[ "If I understand correctly the redisClient.get(\"mybitset\") call returns a string containing the binary data. Try replacing your print bitset with:\nprint \"{0:b}\".format(ord(bitset[0]))\n\nThis will only work if your bitset is one byte long. If it spans multiple bytes try using the struct module. For example, if...
[ 4 ]
[]
[]
[ "python", "redis" ]
stackoverflow_0008335567_python_redis.txt
Q: Python how to get the base instance of an instance? In C# I would go: myObj.base I have a Date class which inherits from date.datetime. The Date class overrides __gt__() and __lt__() so when using the < and > operators they are called. I do not want to use these overrides - I want to use the date.datetime methods...
Python how to get the base instance of an instance?
In C# I would go: myObj.base I have a Date class which inherits from date.datetime. The Date class overrides __gt__() and __lt__() so when using the < and > operators they are called. I do not want to use these overrides - I want to use the date.datetime methods on an instance of Date.
[ "Use super() to get the superclass object. Type help(super) in the Python command prompt.\nFrom the manual:\nclass super(object)\n | super(type) -> unbound super object\n | super(type, obj) -> bound super object; requires isinstance(obj, type)\n | super(type, type2) -> bound super object; requires issubclass(typ...
[ 8, 4 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0008335930_python_python_2.6.txt
Q: Generating a WSDL using Python and SOAPpy First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return thi...
Generating a WSDL using Python and SOAPpy
First of all, I will admit I am a novice to web services, although I'm familiar with HTML and basic web stuff. I created a quick-and-dirty web service using Python that calls a stored procedure in a MySQL database, that simply returns a BIGINT value. I want to return this value in the web service, and I want to gener...
[ "When I tried to write Python web service last year, I ended up using ZSI-2.0 (which is something like heir of SOAPpy) and a paper available on its web.\nBasically I wrote my WSDL file by hand and then used ZSI stuff to generate stubs for my client and server code. I wouldn't describe the experience as pleasant, bu...
[ 12, 1, 1 ]
[]
[]
[ "python", "soap", "soappy", "wsdl", "zsi" ]
stackoverflow_0000273002_python_soap_soappy_wsdl_zsi.txt
Q: Python initial read from socket returns some unexpected characters I have a Python socket server that I'm trying to read text commands from a line at a time, code is below. The first time it is run, line contains what look like some garbage characters before the data. On subsequent calls to readline I get the ex...
Python initial read from socket returns some unexpected characters
I have a Python socket server that I'm trying to read text commands from a line at a time, code is below. The first time it is run, line contains what look like some garbage characters before the data. On subsequent calls to readline I get the exact data I typed in from the telnet client (Putty). Why am I getting th...
[ "You need to make sure and use \"RAW\" mode in this case. Otherwise, your telnet client is trying to discover and negotiate with a telnet server. See this link for more info:\n3.6 Making raw TCP connections\nYou could probably switch \"Telnet negotiation mode\" to passive in the Telnet settings area too.\n" ]
[ 1 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0008335993_python_sockets.txt
Q: exec cos(x) freezes program if x not in [-9,9] from math import * def solution_handler(self, input): while re.search(r'(?<!\.)...
exec cos(x) freezes program if x not in [-9,9]
from math import * def solution_handler(self, input): while re.search(r'(?<!\.)(\d+)(?!\.)(\d*)', input): rx = re.search(r'...
[ "The problem is with your loop: remove the exec and it would still hang. Try this instead:\nfrom __future__ import division\nfrom math import *\ndef solution_handler(self, input):\n return eval(input)\n\n" ]
[ 2 ]
[]
[]
[ "exec", "python", "regex" ]
stackoverflow_0008336006_exec_python_regex.txt
Q: Trying to merge files after removing duplicate content Here is my problem. I have n files and they all have overlapping and common text in them. I want to create a file using these n files such that the new file only contains unique lines in it that exist across all of the n files. I am looking for a bash command,...
Trying to merge files after removing duplicate content
Here is my problem. I have n files and they all have overlapping and common text in them. I want to create a file using these n files such that the new file only contains unique lines in it that exist across all of the n files. I am looking for a bash command, python api that can do it for me. If there is an algorithm ...
[ "If the order of the lines is not important, you could do this:\nsort -u file1 file2 ...\n\nThis will (a) sort all the lines in all the files, and then (b) remove duplicates. This will give you the lines that are unique among all the files.\n", "For testing common data you can use comm:\nDESCRIPTION\n The co...
[ 3, 2, 1, 1 ]
[]
[]
[ "algorithm", "bash", "linux", "python" ]
stackoverflow_0008335651_algorithm_bash_linux_python.txt
Q: Shell problems when running scripts in Ubuntu as new user When I log into a particular Ubuntu Linux (10.04 64bit) host via SSH, I get a bash shell. From here I am able to run a particular Python script, with the executable bit set, that has this as the first line: #!/usr/bin/env python However if another (new) us...
Shell problems when running scripts in Ubuntu as new user
When I log into a particular Ubuntu Linux (10.04 64bit) host via SSH, I get a bash shell. From here I am able to run a particular Python script, with the executable bit set, that has this as the first line: #!/usr/bin/env python However if another (new) user logs into the same host via SSH and tries to run this (or a ...
[ "I was having the same issue and it was not immediately clear from the above answers what the problem was, or what the solution was, however I think I now understand.\nApparently windows line breaks are encoded slightly differently. While cygwin can encode in a unix format, I was using a windows text editor (Notepa...
[ 6, 3, 2 ]
[]
[]
[ "dos", "linux", "python", "shell", "ubuntu" ]
stackoverflow_0004082062_dos_linux_python_shell_ubuntu.txt
Q: I keep on getting a type error Well I'm teaching myself about python classes and when I run my code I get the following error: class Critter(object): """A virtual pet""" def _init_(self, name, mood): print("A new critter has been born!!!!!") self.name = name ...
I keep on getting a type error
Well I'm teaching myself about python classes and when I run my code I get the following error: class Critter(object): """A virtual pet""" def _init_(self, name, mood): print("A new critter has been born!!!!!") self.name = name self.__mood = mood ...
[ "I would recommend that you more carefully format your submissions. Python is really picky about indentation -- read PEP8 for a good intro on how to properly format Python code.\nThe problem is that you spelled __init__ wrong. You have _init_ which is just another method to Python.\n", "Note that the following ...
[ 4, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0008336234_class_python.txt
Q: What does "None" mode mean in Image.fromarray? I am converting from a numpy array to an image using the Image.fromarray() The docstring shows that the default mode is "None". What does that mean? Is it one of the modes such as "L", or is it another mode? A: If you don't specify a mode or specify None, it will ...
What does "None" mode mean in Image.fromarray?
I am converting from a numpy array to an image using the Image.fromarray() The docstring shows that the default mode is "None". What does that mean? Is it one of the modes such as "L", or is it another mode?
[ "If you don't specify a mode or specify None, it will decide which mode to use from the type.\n(The authors of the Image class appear not to know how to write a Python docstring; the doc comments are all there in the source, but as comments rather than a docstring.)\n" ]
[ 2 ]
[]
[]
[ "numpy", "python", "python_imaging_library" ]
stackoverflow_0008336671_numpy_python_python_imaging_library.txt
Q: Can't figure out how to use Mechanize with Python to select items from a dropdown box on an ASP.NET page I have an ASP.NET page (located here: http://www.kraftrecipes.com/Products/ProductMain.aspx) that has a dropdown box of various food brands. I'm trying to use Mechanize in Python so I can click on each item in ...
Can't figure out how to use Mechanize with Python to select items from a dropdown box on an ASP.NET page
I have an ASP.NET page (located here: http://www.kraftrecipes.com/Products/ProductMain.aspx) that has a dropdown box of various food brands. I'm trying to use Mechanize in Python so I can click on each item in the list, go to the product list page, and eventually use BeautifulSoup to scrape product information. Here's ...
[ "There is only one form on the page. What you want is controls.\nTry:\nform = browser.forms()[0]\ncontrol = form.find_control(name=\"ctl00$SPWebPartManager1$g_9bdf5859_9c73_4144_8b6a_9a3b3df417d5$ctl01$ddlBrand\")\n\n" ]
[ 0 ]
[]
[]
[ "asp.net", "html", "mechanize", "python" ]
stackoverflow_0008335909_asp.net_html_mechanize_python.txt
Q: Matplotlib: Custom axis formatter using display coordinates In Matplotlib, I would like to use a FunctionFormatter for the y axis to format the ticks such that no ticks are displayed in an area near the bottom of the plot. This is to make a "y data-less" region, a strip along the bottom of the plot, where data wi...
Matplotlib: Custom axis formatter using display coordinates
In Matplotlib, I would like to use a FunctionFormatter for the y axis to format the ticks such that no ticks are displayed in an area near the bottom of the plot. This is to make a "y data-less" region, a strip along the bottom of the plot, where data with no y value will be plotted. In pseudocode, that function wou...
[ "Formatter has nothing to do with displaying ticks, it controls only how tick labels are formatted. What you need is modified Locator, which locates displayed ticks' positions. \nThere are 2 ways to accomplish the task:\n\nwrite your own Locator class, inherited from matplotlib.ticker.Locator. Unfortunately there e...
[ 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008332698_matplotlib_python.txt
Q: how to assign value in django I have a problem in subtracting a two values. i just want to be like this a = b - c here is my code in my handlers.py def create(self, request): if not self.has_model(): return rc.NOT_IMPLEMENTED attrs = self.flatten_dict(request.POST) if attrs....
how to assign value in django
I have a problem in subtracting a two values. i just want to be like this a = b - c here is my code in my handlers.py def create(self, request): if not self.has_model(): return rc.NOT_IMPLEMENTED attrs = self.flatten_dict(request.POST) if attrs.has_key('data'): ext_po...
[ "If you really want it to look like a = b - c then you'll have to change your assignment to sumOfQuantity:\nsumOfQuantity = Booking.objects.filter(date_select='2011-11-29').aggregate(Sum('quantity'))['quantity__sum']\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_piston", "python" ]
stackoverflow_0008337005_django_django_piston_python.txt
Q: Google App Engine Python: Class Definition "Invalid Syntax" When I run this code in the dev_appserver it gives me the "Invalid syntax" error at line 22, where the HugAPanda class is initialized. Does anybody know why this would happen? Here's the code: import wsgiref.handlers from google.appengine.ext import db fr...
Google App Engine Python: Class Definition "Invalid Syntax"
When I run this code in the dev_appserver it gives me the "Invalid syntax" error at line 22, where the HugAPanda class is initialized. Does anybody know why this would happen? Here's the code: import wsgiref.handlers from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.w...
[ "You have invalid syntax in a line above. (Line 15 it looks like)\nself.response.out.write(\"<form action=\\\"/HugPanda\\\" method=\\\"post\\\"><div><input type=\\\"text\\\" name=\\\"PandaMessage\\\" value=\\\"A message for a panda.\\\"></div><div><input type=\\\"submit\\\" value=\\\"Hug a panda?\\\"></div></form><...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python", "syntax_error" ]
stackoverflow_0008337349_google_app_engine_python_syntax_error.txt
Q: how to generate a graph/diagram like Google Analytics's Visitor Flow? I am trying to generate a diagram similar to that presented by the recent Google Analytics "Visitor Flow". These are also known as Alluvial diagrams. I can use a web or non-web based solution, as long as I can run it myself. The data I want to...
how to generate a graph/diagram like Google Analytics's Visitor Flow?
I am trying to generate a diagram similar to that presented by the recent Google Analytics "Visitor Flow". These are also known as Alluvial diagrams. I can use a web or non-web based solution, as long as I can run it myself. The data I want to visualize is the following: at time t1, I have x1 units, divided into n1 ...
[ "I thought this was an interesting question, so I made an example alluvial diagram using d3: http://nickrabinowitz.com/projects/d3/alluvial/alluvial.html\nAnd, because d3 is so good at animation, and I thought it would look cool, I made an animated version as well: http://nickrabinowitz.com/projects/d3/alluvial/all...
[ 60 ]
[ "Consider Parallel coordinates plot in R\n![Parallel Coordinate Plot of a Horse Race ][1]\ndf <- structure(list(Horse = structure(c(11L, 16L, 13L, 15L, 3L, 18L, 10L, 17L, 19L, 8L, 5L, 9L, 1L, 4L, 12L, 2L, 14L, 7L, 6L), \n.Label = c(\"Advice\", \"Atomic Rain\", \"Chocolate Candy\", \"Desert Party\", \"Dunkirk\", \"F...
[ -1 ]
[ "d3.js", "graphviz", "python", "visualization" ]
stackoverflow_0008222356_d3.js_graphviz_python_visualization.txt
Q: Architecture for a lot of data logging, DB or file? I'm working on a Python app I want to be scalable to accommodate about 150 writes per second. That's spread out among about 50 different sources. Is Mongodb a good candidate for this? I'm split on writing to a database, or just making a log file for each source...
Architecture for a lot of data logging, DB or file?
I'm working on a Python app I want to be scalable to accommodate about 150 writes per second. That's spread out among about 50 different sources. Is Mongodb a good candidate for this? I'm split on writing to a database, or just making a log file for each source and parsing them separately. Any other suggestions for l...
[ "I would say that mongodb very good fit for the logs collection, because of:\n\nMongodb has amazing fast writes\nLogs not so important, so it's okay to loose some of them in case of server failure. So you can run mongodb without journaling option to avoid writes overhead. \nIn additional you can use sharding to inc...
[ 6 ]
[]
[]
[ "logging", "mongodb", "python" ]
stackoverflow_0008336418_logging_mongodb_python.txt
Q: Pythonic way to find index of n th occurance of a value in a list? Here is my list list=[1,2,1,1,1,1,1,4,5] Now i want to know the index of 5th '1' in a pythonic way. A: Enumerate can help here [x for x in enumerate(list) if x[1]==1][5][0] #X[1]==1 implies values of element equals 1, since x[0] will be enumer...
Pythonic way to find index of n th occurance of a value in a list?
Here is my list list=[1,2,1,1,1,1,1,4,5] Now i want to know the index of 5th '1' in a pythonic way.
[ "Enumerate can help here\n[x for x in enumerate(list) if x[1]==1][5][0]\n\n#X[1]==1 implies values of element equals 1, since x[0] will be enumeration index.\n\n", "[i for (i,e) in enumerate(list) if e==1][5]\n\n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008337514_python.txt
Q: Python: Getting a list of values associated with a single key in a dictionary The task is to take all the movies associated with a dictionary of actors. actor_dict = {'actor_A': [m1, m2, m3, m4], 'actor_B': [m5,m6,m7,m8]} How can I single out the list of values from the entire dictionary? A: One possibility wou...
Python: Getting a list of values associated with a single key in a dictionary
The task is to take all the movies associated with a dictionary of actors. actor_dict = {'actor_A': [m1, m2, m3, m4], 'actor_B': [m5,m6,m7,m8]} How can I single out the list of values from the entire dictionary?
[ "One possibility would be:\nmovies_list = []\nfor v in actor_dict.itervalues():\n movies_list.extend(v)\n\nIf you want unique movies (if one movie appears in more actors' lists):\nmovies_set = []\nfor v in actor_dict.itervalues():\n movies_set.update(v)\nmovies_list = list(movies_set)\n\nor:\nmovies_list = li...
[ 4 ]
[]
[]
[ "dictionary", "key", "python" ]
stackoverflow_0008337675_dictionary_key_python.txt
Q: Posting large files to usenet using Python & nntplib: How are large files split? I'm intrigued by uBackup, using Usenet for backing up large files. I thought it would be a good idea to use python for this, but I'm having problems understanding the correct protocol for posting large files. I know you need to compre...
Posting large files to usenet using Python & nntplib: How are large files split?
I'm intrigued by uBackup, using Usenet for backing up large files. I thought it would be a good idea to use python for this, but I'm having problems understanding the correct protocol for posting large files. I know you need to compress your files and best split them up in smaller parts. But when you actually post the ...
[ "Sorry for the confusion. The uBackup article on WikiHow explains in step 2 how to split files.\nIt uses 7-zip.org to do so. \nIn this image you can see that the file(s) are split into 50 Mb chunks.\nhttp://www.wikihow.com/Image:2T-7-zip.org-parameters.jpg\nIn step 4 you can see that the files are uploaded with 'Ca...
[ 2 ]
[]
[]
[ "nntp", "python", "usenet" ]
stackoverflow_0005634345_nntp_python_usenet.txt
Q: itertools and strided list assignment Given a list, e.g. x = [True]*20, I want to assign False to every other element. x[::2] = False raises TypeError: must assign iterable to extended slice So I naively assumed you could do something like this: x[::2] = itertools.repeat(False) or x[::2] = itertools.cycle([False...
itertools and strided list assignment
Given a list, e.g. x = [True]*20, I want to assign False to every other element. x[::2] = False raises TypeError: must assign iterable to extended slice So I naively assumed you could do something like this: x[::2] = itertools.repeat(False) or x[::2] = itertools.cycle([False]) However, as far as I can tell, this res...
[ "What you are attempting to do in this code is not what you think (i suspect)\nfor instance:\nx[::2] will return a slice containing every odd element of x, since x is of size 20,\nthe slice will be of size 10, but you are trying to assign a non-iterable of size 1 to it.\nto successfully use the code you have you wi...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "python", "python_itertools", "slice" ]
stackoverflow_0008336543_python_python_itertools_slice.txt
Q: Python - subprocesses and the python shell I am trying to shell out to a non-python subprocess and allow it to inherit the stdin and stdout from python. - i am using subprocess.Popen This would probably work if I am calling from a console, but it definitely doesn't work when I am using the python shell (I am using...
Python - subprocesses and the python shell
I am trying to shell out to a non-python subprocess and allow it to inherit the stdin and stdout from python. - i am using subprocess.Popen This would probably work if I am calling from a console, but it definitely doesn't work when I am using the python shell (I am using IDLE by the way) Is there any way to convince p...
[ "This works both from a script and from the interactive interpreter, but not from IDLE:\nsubprocess.Popen(whatever, stdin=sys.stdout, stdout=sys.stdin)\n\nYou can't use the objects which IDLE assigns to sys.stdin and sys.stdout as arguments to subprocess.Popen. These objects (the interfaces to the IDLE shell window...
[ 6, 4 ]
[]
[]
[ "popen", "python", "python_idle", "subprocess" ]
stackoverflow_0008336996_popen_python_python_idle_subprocess.txt
Q: Dynamic import in Python How can I make this import: from module import * with imp module? Disclaimer: I need use imp module because I need make several statements and I want to do it dynamicly I need use * because I need that in the file I made the import, the variables and methods defined in module be availabl...
Dynamic import in Python
How can I make this import: from module import * with imp module? Disclaimer: I need use imp module because I need make several statements and I want to do it dynamicly I need use * because I need that in the file I made the import, the variables and methods defined in module be available directly, i mean without mod...
[ "Here!\ndef load_everything_from(module_names):\n g = globals()\n for module_name in module_names:\n m = __import__(module_name)\n names = getattr(m, '__all__', None)\n if names is None:\n names = [name for name in dir(m) if not name.startswith('_')]\n for name in names:...
[ 5, 1, 0 ]
[]
[]
[ "dynamic", "import", "module", "python" ]
stackoverflow_0008336119_dynamic_import_module_python.txt
Q: Pygame Problems I've been developing a simple game where a square moves around a screen. Recently I've tried using classes to organize everything but now the square doesn't move around the screen. I'm not sure where I went wrong. Here's my script: import os, sys import pygame from pygame.locals import * class Pla...
Pygame Problems
I've been developing a simple game where a square moves around a screen. Recently I've tried using classes to organize everything but now the square doesn't move around the screen. I'm not sure where I went wrong. Here's my script: import os, sys import pygame from pygame.locals import * class Player(pygame.sprite.Spr...
[ "You didn't just change your first script's structure. There are lots of other changes too. Some points:\n\nWhere did you set your Player sprite's color? Or where did you fill your sprite's surface? I can't see any sprites in your updated version, I think it's because your background color and sprite color is the s...
[ 1 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0008336742_pygame_python.txt
Q: How to add to beginning Python path in bash Here is my .bash_profile PYTHONPATH=".:/home/miki725/django/django:$PYTHONPATH" export PYTHONPATH So then I open python however the directory I add in .bash_profile is not the first one: Python 2.4.3 (#1, Sep 21 2011, 20:06:00) [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] o...
How to add to beginning Python path in bash
Here is my .bash_profile PYTHONPATH=".:/home/miki725/django/django:$PYTHONPATH" export PYTHONPATH So then I open python however the directory I add in .bash_profile is not the first one: Python 2.4.3 (#1, Sep 21 2011, 20:06:00) [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2 Type "help", "copyright", "credits" or "...
[ "Your best bet is to modify sys.path at runtime. In a shared hosting enviroment it's common to do this in your .wsgi file. You could do something like this:\nimport sys\nsys.path.insert(0, '/home/miki725/django/django')\n\nIf you add export PYTHONSTARTUP=/home/miki725/.pythonrc to your .bash_profile, you can add th...
[ 2, 0, 0, 0 ]
[]
[]
[ "bash", "python", "python_import", "pythonpath" ]
stackoverflow_0008337686_bash_python_python_import_pythonpath.txt
Q: Tipfy & Jinja: Creating a logout URL for every page I have a jinja template with the usual boilerplate links, one of them being the "sign out" link. The URL of this link has to be generated using Users.create_logout_url() before rendering a page. I would like to avoid having to generate this URL and add it to my ...
Tipfy & Jinja: Creating a logout URL for every page
I have a jinja template with the usual boilerplate links, one of them being the "sign out" link. The URL of this link has to be generated using Users.create_logout_url() before rendering a page. I would like to avoid having to generate this URL and add it to my render_response for every single get/post handler. I've ...
[ "I do something similar with Jinja / GAE and I use a BaseHandler + a template that I include. BaseHandler:\nclass BaseHandler(webapp2.RequestHandler):\n ...\n def render_jinja(self, name, **data):\n data['logout_url']=users.create_logout_url(self.request.uri)\n template = jinja_environment.get_t...
[ 6, 4 ]
[]
[]
[ "google_app_engine", "jinja2", "python", "tipfy" ]
stackoverflow_0008329204_google_app_engine_jinja2_python_tipfy.txt
Q: Python I/O: How to use the wsgi.input stream from io module In a WSGI application we can read the row input data from the wsgi.input field: def application(env, start_response): ..... data = env['wsgi.input'].read(num_bytes) ..... However, I want to wrap the file-like object using the new ...
Python I/O: How to use the wsgi.input stream from io module
In a WSGI application we can read the row input data from the wsgi.input field: def application(env, start_response): ..... data = env['wsgi.input'].read(num_bytes) ..... However, I want to wrap the file-like object using the new io module: import io def application(env, start_response): ...
[ "The io.open() function does not accept file-object as the first parameter. \nHowever, it accepts an integer representing the handle to an open file. so you may have some success using:\nf = io.open(env['wsgi.input'].fileno, 'rb')\n\nAddendum:\nThe io module is written for python 3, where string handling is quite d...
[ 2 ]
[]
[]
[ "io", "python", "wsgi" ]
stackoverflow_0008338430_io_python_wsgi.txt
Q: Mapping line numbers across two diff files using emacs/python/winmerge Consider the following two files that are slightly different: foo (old version): <Line 1> a <Line 2> b <Line 3> c <Line 4> d foo (new version): <Line 1> a <Line 2> e <Line 3> b <Line 4> c <Line 5> f <Line 6> d As you can see, characters e and...
Mapping line numbers across two diff files using emacs/python/winmerge
Consider the following two files that are slightly different: foo (old version): <Line 1> a <Line 2> b <Line 3> c <Line 4> d foo (new version): <Line 1> a <Line 2> e <Line 3> b <Line 4> c <Line 5> f <Line 6> d As you can see, characters e and f are introduced in the new file. I have a set of line numbers correspondi...
[ "You can do it all in Emacs:\n(defun get-joint-index (file-a index file-b)\n (let ((table (make-hash-table :test #'equal)))\n (flet ((line () (buffer-substring-no-properties\n (point-at-bol) (point-at-eol))))\n (with-temp-buffer (insert-file file-b)\n (loop for i from 1 do (putha...
[ 3, 2 ]
[]
[]
[ "diff", "emacs", "python", "winmerge" ]
stackoverflow_0008337098_diff_emacs_python_winmerge.txt
Q: Python introspection - how to check current module / line of call from within function I have a function: # utils.py def hello(name='World'): # Detect where I'm being called from. print('Hi, %s. You called this from %s at line # %d.' % (name, mod, lineno)) # ``mod`` and ``lineno`` on previous line woul...
Python introspection - how to check current module / line of call from within function
I have a function: # utils.py def hello(name='World'): # Detect where I'm being called from. print('Hi, %s. You called this from %s at line # %d.' % (name, mod, lineno)) # ``mod`` and ``lineno`` on previous line would have been set in real use. I import that function and run it elsewhere # other.py (this c...
[ "Access the enclosing frame of inspect.currentframe():\nimport inspect\n\ndef hello(name='World'):\n f = inspect.currentframe().f_back\n mod = f.f_code.co_filename\n lineno = f.f_lineno\n print('Hi, %s. You called this from %s at line # %d.' %\n (name, mod, lineno))\n\n", "The traceback modul...
[ 13, 3, 1 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0005326539_introspection_python.txt
Q: How quickly find ip address in range of IP addresses? Possible Duplicate: python and ip range? How to get list of IP addresses? I have a many ip ranges in text file: 1.0.0.0 - 1.0.0.255 .... 223.255.254.0 - 223.255.254.255 How to quickly find range for ip address ? A: You can translate the dotted-ip-address t...
How quickly find ip address in range of IP addresses?
Possible Duplicate: python and ip range? How to get list of IP addresses? I have a many ip ranges in text file: 1.0.0.0 - 1.0.0.255 .... 223.255.254.0 - 223.255.254.255 How to quickly find range for ip address ?
[ "You can translate the dotted-ip-address to an integer using the build-in socket.\nhttp://code.activestate.com/recipes/66517-ip-address-conversion-functions-with-the-builtin-s/ \nAnd then do a test to see if you ip-address falls between the two integers:\na = dottedQuadToNum(ipfrom)\nb = dottedQuadToNum(ipto)\nmine...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008339057_python.txt
Q: Split and non-latin strings in Python 2.X Example: # -*- coding: utf-8 -*- my_str = u'Строка ^ с ^ разделителями!' # Russian letters print my_str.replace(' ', '') print my_str.replace(' ', '').split('^') Result: Строка^с^разделителями! [u'\u0421\u0442\u0440\u043e\u043a\u0430 ', u' \u0441 ', u' \u0440\u0430\u0437...
Split and non-latin strings in Python 2.X
Example: # -*- coding: utf-8 -*- my_str = u'Строка ^ с ^ разделителями!' # Russian letters print my_str.replace(' ', '') print my_str.replace(' ', '').split('^') Result: Строка^с^разделителями! [u'\u0421\u0442\u0440\u043e\u043a\u0430 ', u' \u0441 ', u' \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044...
[ "These are normal strings, you're just seeing their internal representation (because you're not printing a string, you're printing a list in the second example). Do\nfor s in my_str.replace(' ', '').split('^'):\n print s\n\nand you'll see. Conversely, try \nprint repr(my_str.replace(' ', ''))\n\nand see what hap...
[ 4 ]
[]
[]
[ "python", "split", "utf_8" ]
stackoverflow_0008339345_python_split_utf_8.txt
Q: Sphinx failed to read searchd response I have strange behavior of Sphinx searchd. I used it with Python standard client on ubuntu 9.10 For same query it's can give normal response or can give broken package like this: failed to read searchd response (status=0,ver=1,len=278,read=72) this problem appears with 50% pr...
Sphinx failed to read searchd response
I have strange behavior of Sphinx searchd. I used it with Python standard client on ubuntu 9.10 For same query it's can give normal response or can give broken package like this: failed to read searchd response (status=0,ver=1,len=278,read=72) this problem appears with 50% probability. I have test index with only 5 do...
[ "I know this question is very old, but for the benefit of any Googlers coming here....\nThis can also happen if your sphinx server version does nto match exactly with the API version you are using.\n", "I figured out this. If Sphinx can't assign user request to worker(if there are no free workers at that time) it...
[ 1, 0 ]
[]
[]
[ "python", "sphinx" ]
stackoverflow_0002697388_python_sphinx.txt
Q: Aptana vs. Eclipse - pygame working only on Aptana? Have used Eclipse with PyDev for a while...without any problems. Recently I wanted to try out PyGame but the problem is that Eclipse gives errors when trying to do that: Traceback (most recent call last): File "C:\Users\Artur\workspace\miniprojekt\src\pygame.py",...
Aptana vs. Eclipse - pygame working only on Aptana?
Have used Eclipse with PyDev for a while...without any problems. Recently I wanted to try out PyGame but the problem is that Eclipse gives errors when trying to do that: Traceback (most recent call last): File "C:\Users\Artur\workspace\miniprojekt\src\pygame.py", line 1, in <module> import pygame File "C:\Users\Artur\...
[ "You are right in that Aptana Studio 3 uses the same PyDev you installed, so, it should be exactly the same thing... do the following:\n\nUpdate PyDev to the latest nightly build -- this is just to be sure you have the proper version.\nRename your own module from pygame.py to something else... i.e.: mypygame.py (th...
[ 1 ]
[]
[]
[ "aptana", "eclipse", "pydev", "python", "python_3.x" ]
stackoverflow_0008335779_aptana_eclipse_pydev_python_python_3.x.txt
Q: When does rabbitmq use tcp backpressure? According to the Pika documentation "the RabbitMQ broker uses TCP Backpressure to slow your client if it is delivering messages too fast." I've registered a backpressure callback and it has yet to be called. My queue has more than 40 million messages and it's growing. By se...
When does rabbitmq use tcp backpressure?
According to the Pika documentation "the RabbitMQ broker uses TCP Backpressure to slow your client if it is delivering messages too fast." I've registered a backpressure callback and it has yet to be called. My queue has more than 40 million messages and it's growing. By setting the backpressure multiplier to -1 I can ...
[ "It's not really when \"your client... is delivering messages too fast\", but when any client is delivering messages too fast.\nRabbitMQ monitors the amount of memory it's using and will exert backpressure when it goes over a certain fraction of the physical memory on the machine. By default this fraction is 0.4, b...
[ 7 ]
[]
[]
[ "pika", "python", "rabbitmq", "tcp" ]
stackoverflow_0008335667_pika_python_rabbitmq_tcp.txt
Q: StringIO and pystache generate spurious null bytes I am parsing a mustache file into a string, and after that I want to process that string with the csv module. For that I generate a file like interface to the string using StringIO. The csv module is complaining with: _csv.Error: line contains NULL byte So I made...
StringIO and pystache generate spurious null bytes
I am parsing a mustache file into a string, and after that I want to process that string with the csv module. For that I generate a file like interface to the string using StringIO. The csv module is complaining with: _csv.Error: line contains NULL byte So I made a simple test: import pystache from cStringIO import St...
[ "txt = \"Hello Steve\" is a bytestring, could the preprocessed string be a unicode string?\n" ]
[ 1 ]
[]
[]
[ "mustache", "python" ]
stackoverflow_0008339470_mustache_python.txt
Q: how to query a multiple column in django I have a problem in displaying specific columns in my model in django... I have read in the documentation in about the queryset feature of django. my question is that it is also possible in django to run just like this query? select name, age, address from person; can anyo...
how to query a multiple column in django
I have a problem in displaying specific columns in my model in django... I have read in the documentation in about the queryset feature of django. my question is that it is also possible in django to run just like this query? select name, age, address from person; can anyone can give me an idea, i also try it like thi...
[ "If you want only some columns use only:\nMymodel.objects.only('name', 'age', 'address')\n\nIf you don't want some columns use defer:\nMymodel.objects.defer('some_big_field')\n\nYou can still access field you haven't queried, but it will cost you one mode DB hit.\nAlso you can use values and values_list methods, bu...
[ 10, 4 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0008339572_django_python_sql.txt
Q: In Python - Selenium2 how to set the time for which a webdriver instance should wait,when loading a page,before giving a timeout exception? I tried it by instantiating a webdriver using the time out as the third parameter as shown below: self.driver = webdriver.Firefox(None, None, 5) and then used the driver to ...
In Python - Selenium2 how to set the time for which a webdriver instance should wait,when loading a page,before giving a timeout exception?
I tried it by instantiating a webdriver using the time out as the third parameter as shown below: self.driver = webdriver.Firefox(None, None, 5) and then used the driver to fetch a web page like so self.driver.get("http://www.google.com") However it waits indefinitely for the page to load. Also tried out WebDriverW...
[ "The WebDriverWait should be used like:\nWebDriverWait(driver, 10).until(lambda driver : driver.title.lower().startswith(\"cheese!\"))\n\nPlease refer to: http://seleniumhq.org/docs/03_webdriver.html\n" ]
[ 0 ]
[]
[]
[ "python", "python_bindings", "selenium", "selenium_webdriver" ]
stackoverflow_0008339404_python_python_bindings_selenium_selenium_webdriver.txt
Q: pykka -- Actors are slow? I am currently experimenting with Actor-concurreny (on Python), because I want to learn more about this. Therefore I choosed pykka, but when I test it, it's more than half as slow as an normal function. The Code is only to look if it works; it's not meant to be elegant. :) Maybe I made so...
pykka -- Actors are slow?
I am currently experimenting with Actor-concurreny (on Python), because I want to learn more about this. Therefore I choosed pykka, but when I test it, it's more than half as slow as an normal function. The Code is only to look if it works; it's not meant to be elegant. :) Maybe I made something wrong? from pykka.actor...
[ "So what is happening here is that your functional version is creating two very large lists which is the bulk of the time. When you introduce actors, mutable data like lists must be copied before being sent to the actor to maintain proper concurrency. Also the list created inside the actor must be copied as well wh...
[ 14 ]
[]
[]
[ "actor", "pykka", "python" ]
stackoverflow_0008339348_actor_pykka_python.txt
Q: Global HotKeys in Win&X11 I need to make a global hotkey for my application, and it should work under X11 and Windows. A: What GUI toolkit are you using? Generally, global hot keys are handled by the Desktop environment or Window Manager - I dont believe that Python's builtin toolkit (tkinter) can make global ho...
Global HotKeys in Win&X11
I need to make a global hotkey for my application, and it should work under X11 and Windows.
[ "What GUI toolkit are you using? Generally, global hot keys are handled by the Desktop environment or Window Manager - I dont believe that Python's builtin toolkit (tkinter) can make global hotkeys. You might look at xlib for Unix and a win lib for windows.\n", "Just an addition - on windows, if you are using wxp...
[ 4, 0 ]
[]
[]
[ "hotkeys", "python" ]
stackoverflow_0000770049_hotkeys_python.txt
Q: Python Block Formatting How do I indent a multiline string in the context of string formatting? e.g. ''' < %s > ''' % (paragraph) where paragraph contains newlines. ('foo\nbar') If I use the above code, I get output like this: ''' < foo bar > ''' when I really want this: ''' < foo bar > ''' I ...
Python Block Formatting
How do I indent a multiline string in the context of string formatting? e.g. ''' < %s > ''' % (paragraph) where paragraph contains newlines. ('foo\nbar') If I use the above code, I get output like this: ''' < foo bar > ''' when I really want this: ''' < foo bar > ''' I know I could do something lik...
[ "How about this:\n'''\n<\n %s\n>\n''' % (\"\\n \".join(paragraph.split(\"\\n\")))\n\nResult:\n<\n foo\n bar\n>\n\nThe string used in the .join() method must contain the same whitespace (plus a \\n at the start) as whatever comes before %s in your string.\n", "You can't expect the Python interpreter to aut...
[ 2, 1, 1, 1 ]
[]
[]
[ "block", "formatting", "python", "quote", "string" ]
stackoverflow_0008340086_block_formatting_python_quote_string.txt
Q: ZMQ Pub-Sub Program Failure When Losing Network Connectivity I have a simple pub-sub setup on a mid-sized network, using ZMQ 2.1. Although some subscribers are using C# bindings, others are using Python bindings, and the issue I'm having is the same for either. If I pull the network cable from a machine running a...
ZMQ Pub-Sub Program Failure When Losing Network Connectivity
I have a simple pub-sub setup on a mid-sized network, using ZMQ 2.1. Although some subscribers are using C# bindings, others are using Python bindings, and the issue I'm having is the same for either. If I pull the network cable from a machine running a subscriber, I get an un-catchable error that immediately terminat...
[ "Original question: Is there something obvious I should be doing but I'm not?\nNo.\nThe workaround for now is to use IP addressing. This does not cause program failure upon network disconnect for ZMQ 2.1.x. \n" ]
[ 1 ]
[]
[]
[ "c#", "publish_subscribe", "python", "zeromq" ]
stackoverflow_0008333630_c#_publish_subscribe_python_zeromq.txt
Q: How do you deal with multiple Python classes in the same module depending on each other? I'm using an ODM library and I'm defining documents as classes within the same module, when they are related. I've hit a circular dependency problem and because I haven't come across this before in Python, I don't know how to ...
How do you deal with multiple Python classes in the same module depending on each other?
I'm using an ODM library and I'm defining documents as classes within the same module, when they are related. I've hit a circular dependency problem and because I haven't come across this before in Python, I don't know how to inform the classes of the existence of each other. Example: ''' docs.py ''' from mongoengine i...
[ "ReferenceField accepts class name as well.\nanother_field = ReferenceField('Bar')\n\n" ]
[ 5 ]
[]
[]
[ "class", "import", "python" ]
stackoverflow_0008340770_class_import_python.txt
Q: How to make a random but partial shuffle in Python? Instead of a complete shuffle, I am looking for a partial shuffle function in python. Example : "string" must give rise to "stnrig", but not "nrsgit" It would be better if I can define a specific "percentage" of characters that have to be rearranged. Purpose is ...
How to make a random but partial shuffle in Python?
Instead of a complete shuffle, I am looking for a partial shuffle function in python. Example : "string" must give rise to "stnrig", but not "nrsgit" It would be better if I can define a specific "percentage" of characters that have to be rearranged. Purpose is to test string comparison algorithms. I want to determine...
[ "This is a problem simpler than it looks. And the language has the right tools not to stay between you and the idea,as usual:\nimport random\n\ndef pashuffle(string, perc=10):\n data = list(string)\n for index, letter in enumerate(data):\n if random.randrange(0, 100) < perc/2:\n new_index = ...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "python", "random", "shuffle", "string" ]
stackoverflow_0008340584_python_random_shuffle_string.txt
Q: How to deactivate method cache in CPython 2.7.2? I'm trying to implement my own kind method cache. For that, first I want to disable the existing method cache implemented in CPython 2.7.2, since I would also like to benchmark CPython without this method cache. I have been looking into the code and found some metho...
How to deactivate method cache in CPython 2.7.2?
I'm trying to implement my own kind method cache. For that, first I want to disable the existing method cache implemented in CPython 2.7.2, since I would also like to benchmark CPython without this method cache. I have been looking into the code and found some method cache code in the 'typeobject.c' file: /* Internal A...
[ "I think the cleanest way would be to find the occurrences of if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG)) in typeobject.c and replace !PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG) with 0. I think that's 3 lines you would have to change.\nThen edit the #define MCACHE_CACHEABLE_NAME(name) macro...
[ 5 ]
[]
[]
[ "caching", "cpython", "methods", "python" ]
stackoverflow_0008341007_caching_cpython_methods_python.txt
Q: Selenium and Python on Snow Leopard I'm trying to use the stock Python (2.6.1) on Snow Leopard with Selenium. Being quite new to Python, I'm a at a bit of a loss for what I've done wrong, as this exact same process worked just fine on my ubuntu box: sudo easy_install -U selenium Create a simple test with Firefox ...
Selenium and Python on Snow Leopard
I'm trying to use the stock Python (2.6.1) on Snow Leopard with Selenium. Being quite new to Python, I'm a at a bit of a loss for what I've done wrong, as this exact same process worked just fine on my ubuntu box: sudo easy_install -U selenium Create a simple test with Firefox Selenium UI, and export it as Python WebD...
[ "Check your Firefox binary location first. Does it placed at here: /Applications/Firefox.app/Contents/MacOS/firefox\n? \nFor more information, please check this page: http://code.google.com/p/selenium/wiki/FirefoxDriver\n", "I know nothing about Selenium but the traceback indicates that it doesn't have a usable p...
[ 7, 0 ]
[]
[]
[ "macos", "python", "selenium" ]
stackoverflow_0008334706_macos_python_selenium.txt
Q: Syntax error in python mercurial plugin I just installed this "checkfiles" plugin and it has a syntax error. I don't know Python, but I've tried a few things and can't figure it out. I'm wondering if someone else could take a peek and see if anything stands out. It's the very last line of the code below: if ...
Syntax error in python mercurial plugin
I just installed this "checkfiles" plugin and it has a syntax error. I don't know Python, but I've tried a few things and can't figure it out. I'm wondering if someone else could take a peek and see if anything stands out. It's the very last line of the code below: if self.opt_all: self.check_diffs = Fals...
[ "The last line is correct modern Python.\nIt contains a conditional expression which was added in Python 2.5.\nSo, I think your Hg must be running Python 2.4 or earlier.\n", "Replace line 120 with\nself.files = ctx and ctx.files() or []\n\nwhich is the Python 2.4 compatible way to do\nself.files = ctx.files() if ...
[ 4, 0 ]
[]
[]
[ "mercurial", "python" ]
stackoverflow_0008153965_mercurial_python.txt
Q: k-permutations in lexicographical order I'm trying to generate k-permutations (variations) in lexicographical (alphabetical) order. For example, this code import itertools a = list('ABCD') k = 2 for c in itertools.combinations(a, k): for p in itertools.permutations(c): print "".join(p), prints AB BA...
k-permutations in lexicographical order
I'm trying to generate k-permutations (variations) in lexicographical (alphabetical) order. For example, this code import itertools a = list('ABCD') k = 2 for c in itertools.combinations(a, k): for p in itertools.permutations(c): print "".join(p), prints AB BA AC CA AD DA BC CB BD DB CD DC and I'm looki...
[ "You can just use permutations without combinations:\nimport itertools\n\na = 'ABCD'\nk = 2\n\nfor p in itertools.permutations(a, k):\n print \"\".join(p),\n\nSee also:\n\nDocumentation for permutations(iterable[,r])\n\n", ">>> [\"\".join(x) for x in itertools.permutations(a, k)]\n['AB', 'AC', 'AD', 'BA', 'BC'...
[ 9, 6 ]
[]
[]
[ "combinatorics", "iterator", "python" ]
stackoverflow_0008341963_combinatorics_iterator_python.txt
Q: use IDs instead of instances to create new objects with foreign keys I want to create a new Django ORM object with three foreign keys. I got the IDs of the foreign rows already, and I mean - that's all I need to fill the foreign key columns in my new row, right? However, I don't seem able to create the new row wit...
use IDs instead of instances to create new objects with foreign keys
I want to create a new Django ORM object with three foreign keys. I got the IDs of the foreign rows already, and I mean - that's all I need to fill the foreign key columns in my new row, right? However, I don't seem able to create the new row without hitting the DB three times to instantiate objects out of those IDs. S...
[ "You need to use the double-underscore notation in this case\neg\na = models.Object1.get_or_create(f__pk=foreign_object_id)\n\n" ]
[ 1 ]
[]
[]
[ "django", "foreign_keys", "python" ]
stackoverflow_0008341938_django_foreign_keys_python.txt
Q: How to get all values in django models? Suppose I got some queryset say of length 100 query_objs=[q1,q2,...,q100] based on the some criteria. How can I filter out this query set say is_admin=True. I know this query set has is_admin=True 10 times. A: you can filter your queryset before calling values Entry.obje...
How to get all values in django models?
Suppose I got some queryset say of length 100 query_objs=[q1,q2,...,q100] based on the some criteria. How can I filter out this query set say is_admin=True. I know this query set has is_admin=True 10 times.
[ "you can filter your queryset before calling values\nEntry.objects.filter(is_admin=True).values_list('id', flat=True).order_by('id')\n\n", "The goal would be to design your app so that the queryset is not evaluated until after the last filter is applied by your function.\neg\nqs = Entry.objects.filter(...whatever...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008339712_django_python.txt