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: deallocating memory for objects returned to python through ctypes I am using ctypes for extending my c functions in MyDll to python. from ctypes import cdll libX = cdll.LoadLibrary("d:\\MyTestProject\\debug\\MyDll.dll") further in the .py file i have a class the methods of which call the functions in MyDll thro...
deallocating memory for objects returned to python through ctypes
I am using ctypes for extending my c functions in MyDll to python. from ctypes import cdll libX = cdll.LoadLibrary("d:\\MyTestProject\\debug\\MyDll.dll") further in the .py file i have a class the methods of which call the functions in MyDll through ctypes. Class MyTestClass: def __init__(self,id): ...
[ "I typically handle this by adding an extern destroy object function that I can pass the pointer back to and delete it.\nCPP:\nSomeClass* createObj()\n{\n return new SomeClass();\n}\n\nvoid destroyObj(SomeClass* pObj){\n delete pObj;\n pObj = NULL;\n}\n\nH:\nextern \"C\" {\n SomeClass* createObj();\n void de...
[ 4 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0007398575_ctypes_python.txt
Q: How to get Inserted or selected row id in postgres using python My postgres query is: query = """INSERT INTO statustable(value) SELECT '%s' WHERE NOT EXISTS (SELECT id, value FROM statustable WHERE value = '%s') RETURNING id""" % (status, status) cursor_postgres.execute(query)...
How to get Inserted or selected row id in postgres using python
My postgres query is: query = """INSERT INTO statustable(value) SELECT '%s' WHERE NOT EXISTS (SELECT id, value FROM statustable WHERE value = '%s') RETURNING id""" % (status, status) cursor_postgres.execute(query) conn_postgres.commit() statusId = cursor_postgres.fetchone()...
[ "I can't say I fully understand your motivation for insisting on a single query. I think your best bet is to have two simple queries:\n\nSELECT id FROM statustable WHERE value = '%s'. This gives you the id if the entry exists, in which case skip step 2;\nINSERT INTO statustable(value) VALUES('%s') RETURNING id. Thi...
[ 10 ]
[]
[]
[ "postgresql", "python", "upsert" ]
stackoverflow_0007474176_postgresql_python_upsert.txt
Q: Python: String counting memory error Based on the suggestions I received in this forum, I am using the following code (example) to count strings. phrase_words = ['red car', 'no lake', 'newjersey turnpike'] lines = ['i have a red car which i drove on newjersey', 'turnpike. when i took exit 39 there was no', 'lake. ...
Python: String counting memory error
Based on the suggestions I received in this forum, I am using the following code (example) to count strings. phrase_words = ['red car', 'no lake', 'newjersey turnpike'] lines = ['i have a red car which i drove on newjersey', 'turnpike. when i took exit 39 there was no', 'lake. i drove my car on muddy roads which turned...
[ "This algorithm needs only two lines in memory at a time. It assumes that no phrase will span three lines:\nfrom itertools import tee, izip\nfrom collections import defaultdict\n\ndef pairwise(iterable): # recipe from itertools docs\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(...
[ 5, 3 ]
[]
[]
[ "memory", "python", "string" ]
stackoverflow_0007475387_memory_python_string.txt
Q: python libraries in a computer cluster I'm having a problem for python to find the installed libraries when I run it in a computer cluster. When I try, e.g., to load numpy in the script: #file: /home/foo/test.py import numpy print numpy.__version__ on the server, I get this: foo@abax:~$ python test.py 1.4.1...
python libraries in a computer cluster
I'm having a problem for python to find the installed libraries when I run it in a computer cluster. When I try, e.g., to load numpy in the script: #file: /home/foo/test.py import numpy print numpy.__version__ on the server, I get this: foo@abax:~$ python test.py 1.4.1 but when I try to run the same in a node w...
[ "First things to check:\n\nPrint PYTHONPATH on both the frontal server and the cluster nodes, to make sure there is no inconsistency\nPrint numpy.__file__ on the frontal server, to check where it finds numpy. Then explore the filesystem of the cluster nodes a bit to see if numpy can be found in the same place (if n...
[ 1 ]
[]
[]
[ "cluster_computing", "python", "remote_access", "rsh" ]
stackoverflow_0007475590_cluster_computing_python_remote_access_rsh.txt
Q: GqlQuery from GoogleAppEngine returns empty list Here is my query: currentID = 7 deck = range(0,3) similarIDs = db.GqlQuery('SELECT * FROM itemSet WHERE jokeID=:1 AND position IN :2', currentID, deck[:3]).fetch(100) Here is my model: class itemSet(db.Model): jokeID = db.IntegerProperty() jokeID2 = db.IntegerPrope...
GqlQuery from GoogleAppEngine returns empty list
Here is my query: currentID = 7 deck = range(0,3) similarIDs = db.GqlQuery('SELECT * FROM itemSet WHERE jokeID=:1 AND position IN :2', currentID, deck[:3]).fetch(100) Here is my model: class itemSet(db.Model): jokeID = db.IntegerProperty() jokeID2 = db.IntegerProperty() position = db.IntegerProperty() When I execute ...
[ "The following code with your GqlQuery statements works for me.\n item = itemSet()\n item.jokeID = 7\n item.jokeID2 = 1\n item.position = 0\n item.put()\n item = itemSet()\n item.jokeID = 7\n item.jokeID2 = 2\n item.position = 1\n item.put()\n\n currentID = 7\n deck = range(0,3)\...
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "gql", "gqlquery", "python" ]
stackoverflow_0007472390_google_app_engine_google_cloud_datastore_gql_gqlquery_python.txt
Q: Help with understanding with_cursor and queries I thought I understood the concept of cursors and queries based on http://code.google.com/appengine/docs/python/datastore/queryclass.html but apparently it is not so based on what I'm doing in code. I have 310 items in my datastore and I want to iterate over them in...
Help with understanding with_cursor and queries
I thought I understood the concept of cursors and queries based on http://code.google.com/appengine/docs/python/datastore/queryclass.html but apparently it is not so based on what I'm doing in code. I have 310 items in my datastore and I want to iterate over them in small batch sizes of 100: query = Event.all() query....
[ "The .count() is indeed foiling you. To see why, create a second, identical query, apply the saved cursor to it, and see what happens.\nBy the way, __key__ order is implicit.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007475589_google_app_engine_python.txt
Q: Program abruptly stops and throws URLERROR from poster.encode import multipart_encode from poster.streaminghttp import register_openers def picscrazy(str,int): register_openers() datagen, headers = multipart_encode({"imagefile[]": open(str, "rb")}) request = urllib2.Request("h...
Program abruptly stops and throws URLERROR
from poster.encode import multipart_encode from poster.streaminghttp import register_openers def picscrazy(str,int): register_openers() datagen, headers = multipart_encode({"imagefile[]": open(str, "rb")}) request = urllib2.Request("http://www.picscrazy.com/process.php", datagen, ...
[ "If you can't display the header coming back from the server, then, your server has simply cut you off.\nIt may be your request is bad -- but that's unlikely.\nIt may be that you've exceeded bandwidth restrictions. \nIt may be that your requests appear to be a DDOS attack because they're happening too frequently.\...
[ 2 ]
[]
[]
[ "poster", "python" ]
stackoverflow_0007475733_poster_python.txt
Q: Python CGI: How to split large output into pages? How do i split the python-cgi output into pages. sample loop structure: While 1: if x is true: c.execute("select m from n where id=%s") gene=c.fetchall() print "%s", (gene), else: print "NA" if y is true: c.execute("select p from q where id=%s") ...
Python CGI: How to split large output into pages?
How do i split the python-cgi output into pages. sample loop structure: While 1: if x is true: c.execute("select m from n where id=%s") gene=c.fetchall() print "%s", (gene), else: print "NA" if y is true: c.execute("select p from q where id=%s") protein=c.fetchall() print "%s", (protein), else: ...
[ "A rough sketch how to proceed:\n\nYou have to code a parameter page into your url, which indicates: \"show the page number page\". This is something like http://xxx.abc.de/genes?page=3, and you have to modify your script to retrieve this parameter. This can be done with http://docs.python.org/library/urlparse.html...
[ 3, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0007476409_cgi_python.txt
Q: need an explanation of python packages and modules I am writing my first python script and this package/module thing has me going nuts. Lets start with my folder layout builder.py -buildModule\__init__.py -buildModule\AppList.py -buildModule\BuildClass.py -buildModule\ConfigSystem.py -buildModule\MenuSystem.py -b...
need an explanation of python packages and modules
I am writing my first python script and this package/module thing has me going nuts. Lets start with my folder layout builder.py -buildModule\__init__.py -buildModule\AppList.py -buildModule\BuildClass.py -buildModule\ConfigSystem.py -buildModule\MenuSystem.py -buildModule\Singleton.py ok, so my __init__.py looks lik...
[ "You need to change import Singleton to from Singleton import Singleton (or as Alex suggested change @Singleton to @Singleton.Singleton.\nIn general you should use qualified imports to avoid namespace collisions, e.g., import SomeModule with a call like SomeModule.SomeClass or for brevity something like import Some...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007476742_python.txt
Q: TKinter process is not drawing Labels, Buttons, and Entry Fields... What am I doing wrong? I'm a full time student, taking my first class in python. This is so strange, it was working, and now, it is no longer showing the buttons, labels, and entry fields. I'm sure it was something I removed or added, but, I'm at ...
TKinter process is not drawing Labels, Buttons, and Entry Fields... What am I doing wrong?
I'm a full time student, taking my first class in python. This is so strange, it was working, and now, it is no longer showing the buttons, labels, and entry fields. I'm sure it was something I removed or added, but, I'm at a loss. Any ideas? All suggestions are appreciated. from Tkinter import * import tkFont import ...
[ "Your main() function setup code isn't working properly. I'm not sure how you had it set up before, but one way to get it working is this:\ndef main():\n \"\"\"Run the main program\"\"\"\n root = Tk()\n gui = BouncyGUI()\n gui.pack()\n root.mainloop()\n\n", "there is an error in your code when com...
[ 1, 0, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007475941_python_tkinter.txt
Q: Custom django admin forms for bbcode input I'm writing a django website, and I want to use the built in admin interface to allow admins to edit some of the content. So they don't have to learn any html, I want them to be able to format the content using simple bbcode tags. I've written a pair of functions to conve...
Custom django admin forms for bbcode input
I'm writing a django website, and I want to use the built in admin interface to allow admins to edit some of the content. So they don't have to learn any html, I want them to be able to format the content using simple bbcode tags. I've written a pair of functions to convert bbcode to and from html markup. Call them htm...
[ "You could have two separate fields in you model - one for html and one for bbcode. Make the html one not show up in the admin interface (by using the exclude property of the ModelAdmin class), so your admins only see and edit the bbcode field. You can get the html content by overriding the model's save method - pl...
[ 1 ]
[]
[]
[ "bbcode", "django", "python" ]
stackoverflow_0007476958_bbcode_django_python.txt
Q: Enigmatic TypeError with QThread usage I have a QThread which runs, but will often need to be killed, then recreated. The problem is I'm getting an untraceable TypeError that pops up and I have no idea what's causing it. I presume I'm not exiting the thread properly or destroying it properly or some such sillyness...
Enigmatic TypeError with QThread usage
I have a QThread which runs, but will often need to be killed, then recreated. The problem is I'm getting an untraceable TypeError that pops up and I have no idea what's causing it. I presume I'm not exiting the thread properly or destroying it properly or some such sillyness, but I just haven't a clue what's causing i...
[ "Well, as error states clearly: You are sending self.doFunction just one parameter (the string \"AllDone\" in this case):\nself.emit(SIGNAL('string'), 'AllDone')\n\nbut, I'll take a wild guess (since you didn't share the definition of doFunction) that it is defined as taking two parameters. So, anytime you emit the...
[ 2 ]
[]
[]
[ "multithreading", "pyqt", "python" ]
stackoverflow_0007477029_multithreading_pyqt_python.txt
Q: pyparsing with ebnf and whitespaces I'm using http://pyparsing.wikispaces.com/file/view/ebnf.py to convert my ebnf definition. ebnf def looks like this: TEST = A, SPACE, A; A = "AA" | "BB"; SPACE = " "; if I load the file and try to parse a string like: e = ebnf.parse(ebnf_file) e['TEST'].leaveWhitespace().parse...
pyparsing with ebnf and whitespaces
I'm using http://pyparsing.wikispaces.com/file/view/ebnf.py to convert my ebnf definition. ebnf def looks like this: TEST = A, SPACE, A; A = "AA" | "BB"; SPACE = " "; if I load the file and try to parse a string like: e = ebnf.parse(ebnf_file) e['TEST'].leaveWhitespace().parseString('AA BB') # same without leaveWhite...
[ "The leaveWhitespace() has to be applied to the original whitespace-containing tag, so try the following:\ne = ebnf.parse(ebnf_file)\ne['SPACE'] = e['SPACE'].leaveWhitespace()\ne['TEST'].parseString('AA BB')\n\n" ]
[ 1 ]
[]
[]
[ "ebnf", "pyparsing", "python" ]
stackoverflow_0007476676_ebnf_pyparsing_python.txt
Q: Running scripts whose purpose is to change shell variables with subprocess.popen I have a series of scripts I am automating the calling of in python with subprocess.Popen. Basically, I call script A, then script B, then script C and so forth. Script A sets a bunch of local shell variables, with commands such as s...
Running scripts whose purpose is to change shell variables with subprocess.popen
I have a series of scripts I am automating the calling of in python with subprocess.Popen. Basically, I call script A, then script B, then script C and so forth. Script A sets a bunch of local shell variables, with commands such as set SOME_VARIABLE=SCRIPT_A, set PATH=%SCRIPT_A:/=\;%PATH%. Script B and C then need to ...
[ "You can use the env argument to Popen with a python dictionary containing the variables then you don't need to run the command that just sets variables.\n", "if 'script A' get generated by another process, you will either need to change the other process so the output file is in a format that you can source (imp...
[ 0, 0, 0 ]
[]
[]
[ "popen", "python", "windows" ]
stackoverflow_0007152172_popen_python_windows.txt
Q: Printing in a loop I have the following file I'm trying to manipulate. 1 2 -3 5 10 8.2 5 8 5 4 0 6 4 3 2 3 -2 15 -3 4 0 2 4 2.33 2 1 1 1 2.5 0 0 2 6 0 8 5 The file just contains numbers. I'm trying to write a program to subtract the rows from each other and print the results to a fil...
Printing in a loop
I have the following file I'm trying to manipulate. 1 2 -3 5 10 8.2 5 8 5 4 0 6 4 3 2 3 -2 15 -3 4 0 2 4 2.33 2 1 1 1 2.5 0 0 2 6 0 8 5 The file just contains numbers. I'm trying to write a program to subtract the rows from each other and print the results to a file. My program is below a...
[ "Append a , to the end of your print statement and it will not print a newline, and then when you exit the for loop add an additional print to move to the next row:\nfor j in range (0,1):\n ...\n\n print Px,Py,Pz,\nprint\n\nAssuming all rows have the same number of columns, you can get the number of columns b...
[ 5, 1, 0 ]
[]
[]
[ "for_loop", "printing", "python" ]
stackoverflow_0007474976_for_loop_printing_python.txt
Q: What is this featureless Python exception? I have a script containing a section similar to this, on Python 2.6: import sys list_id='cow' prev=[0,'cow'] try: if list_id==prev[1]: print '{0} is the same as {1}'.format(list_id,prev[1]) sys.exit(0) except: print 'exception occurred, exiting w...
What is this featureless Python exception?
I have a script containing a section similar to this, on Python 2.6: import sys list_id='cow' prev=[0,'cow'] try: if list_id==prev[1]: print '{0} is the same as {1}'.format(list_id,prev[1]) sys.exit(0) except: print 'exception occurred, exiting with error' sys.exit(1) I noticed that thoug...
[ "sys.exit() raises SystemExit, which is what you're seeing.\nAs to why it doesn't inherit from Exception:\n\nThe exception inherits from BaseException instead of StandardError or\n Exception so that it is not accidentally caught by code that catches\n Exception. This allows the exception to properly propagate up ...
[ 6, 3, 2 ]
[]
[]
[ "exception", "python", "python_2.6" ]
stackoverflow_0007477533_exception_python_python_2.6.txt
Q: Mac Python "Installation step failed: run postflight script" I'm new to Python development, and in trying to get Aptana Studio Setup, I seemed to have messed up my Python install. So I followed the uninstall MacPython instructions here http://homepages.cwi.nl/~jack/macpython/uninstall.html ...and now I'm trying t...
Mac Python "Installation step failed: run postflight script"
I'm new to Python development, and in trying to get Aptana Studio Setup, I seemed to have messed up my Python install. So I followed the uninstall MacPython instructions here http://homepages.cwi.nl/~jack/macpython/uninstall.html ...and now I'm trying to install Python again. From what I can tell, GAE needs you to hav...
[ "OK, based on your information about /usr/bin/python failing (I was afraid that might be the case!), it appears there are problems with your Apple-supplied system Python. Perhaps you mistakenly deleted something in /System/Library/Frameworks/Python.frameworks, which is where the Apple-supplied Python resides and s...
[ 3, 0 ]
[]
[]
[ "google_app_engine", "installation", "python" ]
stackoverflow_0007473762_google_app_engine_installation_python.txt
Q: Learning classes but having an odd issue that I am sure is simple So I am learning how to use classes and python and I am creating a simple program to perform arithmetic operations with rational numbers. I am creating a class called ArithmeticOperations. In this class I have a main function definition which prompt...
Learning classes but having an odd issue that I am sure is simple
So I am learning how to use classes and python and I am creating a simple program to perform arithmetic operations with rational numbers. I am creating a class called ArithmeticOperations. In this class I have a main function definition which prompts the user for the numerator and denominator of 2 rational numbers, the...
[ "In the method call, there is no need to explicitly specify self. Just call: self.product(n1,d1,n2,d2);, for the desired behavior.\nClass methods will always have this extra self first argument, so that you can refer to the self inside the method body. Note also that unlike this in languages such as java (and many ...
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0007477614_python.txt
Q: why do I get a blank tkinter window? so when i run this code and click the button: from Tkinter import * import thread class App: def __init__(self, master): print master def creatnew(): admin=Tk() lab=Label(admin,text='Workes') lab.pack() admin...
why do I get a blank tkinter window?
so when i run this code and click the button: from Tkinter import * import thread class App: def __init__(self, master): print master def creatnew(): admin=Tk() lab=Label(admin,text='Workes') lab.pack() admin.minsize(width=250, height=250) ...
[ "Don't use threads. It's confusing the Tkinter mainloop. For a second window create a Toplevel window.\nYour code with minimal modifications:\nfrom Tkinter import *\n# import thread # not needed\n\nclass App:\n def __init__(self, master):\n print master\n\n def creatnew(): # recommend making this...
[ 4 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007477157_python_tkinter.txt
Q: Precise Event Synchronization with Python I have a multinode network of VMs spread across several machines, one management VM and 7-15 worker VMs. I would like to run an NTP server on the management VM and have all the worker VMs synchronize with the mangament VM. From there I plan on having a python process on e...
Precise Event Synchronization with Python
I have a multinode network of VMs spread across several machines, one management VM and 7-15 worker VMs. I would like to run an NTP server on the management VM and have all the worker VMs synchronize with the mangament VM. From there I plan on having a python process on each worker VM spawn a new thread at at arbitary...
[ "If you can run an NTP server on the management VM, you can hit that NTP server with pure python code to get the \"master\" time, and then use that as a base for offset calculations.\n>>> import ntplib,datetime\n>>> x = ntplib.NTPClient()\n>>> datetime.datetime.utcfromtimestamp(x.request('master server').tx_time)\n...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007477162_python.txt
Q: TabularInlines readonly fields are deleteable I'm using TabularInlines for administrate many-to-many relationships in the django admin. When some conditions are met, I want to make the inline read only. To achieve this I override the get_readonly_fields() method from the BaseModelAdmin. This works like a charm, wi...
TabularInlines readonly fields are deleteable
I'm using TabularInlines for administrate many-to-many relationships in the django admin. When some conditions are met, I want to make the inline read only. To achieve this I override the get_readonly_fields() method from the BaseModelAdmin. This works like a charm, with the only problem, that the read only fields are ...
[ "I think what you want to do is set has_delete_permission(self, obj=None). That will allow you to decide when you can and cannot delete an entire inline.\n" ]
[ 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007176746_django_django_admin_python.txt
Q: using an asymptote for program completion This question could be answered in a language-agnostic fashion, but I am using python (fyi). I am running an infinite loop which needs to terminate when during the last minute <10 new objects are discovered. Eg: while True: newobjs = dig_more_objects(obj) if less ...
using an asymptote for program completion
This question could be answered in a language-agnostic fashion, but I am using python (fyi). I am running an infinite loop which needs to terminate when during the last minute <10 new objects are discovered. Eg: while True: newobjs = dig_more_objects(obj) if less than 10 newobjs have been discovered over the ...
[ "Here's a rough stab at it -- depending on the nature of dig_more_objects you may need to adjust the condition:\nimport time\nresults = []\nwhile True:\n mark = time.time()\n newobjs = dig_more_objects(obj)\n elapsed = time.time() - mark\n results.append((newobjs, elapsed))\n count = 0\n threshhol...
[ 1, 0, 0 ]
[]
[]
[ "exit_code", "python" ]
stackoverflow_0007477644_exit_code_python.txt
Q: how to force use of python 2.6_64bit in Mac OsX.6 for a single shell session? I'm trying to run the bioinformatics program Stampy, which requires the 64-bit installation of python 2.6. I can launch the 64-bit installation by typing arch -x86_64 /usr/bin/python2.6 but when I run a Stampy command from within the sh...
how to force use of python 2.6_64bit in Mac OsX.6 for a single shell session?
I'm trying to run the bioinformatics program Stampy, which requires the 64-bit installation of python 2.6. I can launch the 64-bit installation by typing arch -x86_64 /usr/bin/python2.6 but when I run a Stampy command from within the shell, eg: ./stampy.py -G c_elegans.WS225.dna.fa I get the following error: Stampy ...
[ "There's a few solutions:\n\nYou can run stampy.py with arch:\narch -x86_64 ./stampy.py -G ...\n\nYou can run stampy.py via python with arch:\narch -x86_64 python stampy.py -G ...\n\nYou can use the VERSIONER_PYTHON_PREFER_32_BIT environment variable:\nVERSIONER_PYTHON_PREFER_32_BIT=yes ./stampy.py -G ...\n\nYou ca...
[ 4, 1 ]
[]
[]
[ "64_bit", "bioinformatics", "python" ]
stackoverflow_0007475988_64_bit_bioinformatics_python.txt
Q: Grab a keyword and the text between keywords in Python Firt thing I'd like to say is this place has helped me more than I could ever repay. I'd like to say thanks to all that have helped me in the past :). I am trying to devide up some text from a specific style message. It is formated like this: DATA|1|TEXT1|ST...
Grab a keyword and the text between keywords in Python
Firt thing I'd like to say is this place has helped me more than I could ever repay. I'd like to say thanks to all that have helped me in the past :). I am trying to devide up some text from a specific style message. It is formated like this: DATA|1|TEXT1|STUFF: some random text||||| DATA|2|TEXT1|THINGS: some random ...
[ "\nGeneral tip: Don't try to build up strings accretively like this:\nmy_output = my_output + ' ' + word\n\ninstead, make my_output a list, append word to the list, and\nthen, at the very end, do a single join: my_output = '\n'.join(my_output). (See text_to_message code below for an example.)\nUsing join is the rig...
[ 1 ]
[]
[]
[ "for_loop", "keyword", "python", "search" ]
stackoverflow_0007477864_for_loop_keyword_python_search.txt
Q: fd duplicate from python to child process i think i have a problem with a ttyUSB device that caused from having 2 open ttyUSB fd's at the same time from different processes. it goes like this: i have a main python process, which opens several ttyUSB fd's, read, write, close, and open processes (with popen) to hand...
fd duplicate from python to child process
i think i have a problem with a ttyUSB device that caused from having 2 open ttyUSB fd's at the same time from different processes. it goes like this: i have a main python process, which opens several ttyUSB fd's, read, write, close, and open processes (with popen) to handle each ttyUSB (of course after the fd was clos...
[ "By default, any file descriptors that a process has open when it forks/execs (which happens during a popen()) are inherited by the child process. If this isn't what you want to happen, you will need to either manually close the file descriptors after forking, or set the fds as close-on-exec using fcntl(fd, F_SETFD...
[ 0 ]
[]
[]
[ "linux", "linux_kernel", "process", "python" ]
stackoverflow_0007477954_linux_linux_kernel_process_python.txt
Q: Import a module in Python only if it doesn't already exist I want to use a module, e.g. BeautifulSoup, in my Python code, so I usually add this to the top of the file: from BeautifulSoup import BeautifulSoup However, when I distribute the module I'm writing, others may not have BeautifulSoup, so I'll just include...
Import a module in Python only if it doesn't already exist
I want to use a module, e.g. BeautifulSoup, in my Python code, so I usually add this to the top of the file: from BeautifulSoup import BeautifulSoup However, when I distribute the module I'm writing, others may not have BeautifulSoup, so I'll just include it in my directory structure like so: Mode LastW...
[ "Usually the following pattern is used to handle this situation in Python.\nFirst rename your BeautifulSoup module something else, e.g. MyBeautifulSoup\nThen:\ntry:\n import BeautifulSoup # Standard\nexcept ImportError:\n import MyBeautifulSoup as BeautifulSoup # internal distribution\n\n" ]
[ 16 ]
[]
[]
[ "module", "python" ]
stackoverflow_0007478075_module_python.txt
Q: Continuing a Loop and Moving On (Python) I have a 'while' loop in my Python app (v2.7) which basically communicates with a Bluetooth GPS device and the loop continues for as long as there is data being received. In essence, the while loop looks like this:- > data = "" > > if data == None: > print "Connection ...
Continuing a Loop and Moving On (Python)
I have a 'while' loop in my Python app (v2.7) which basically communicates with a Bluetooth GPS device and the loop continues for as long as there is data being received. In essence, the while loop looks like this:- > data = "" > > if data == None: > print "Connection Failed" else: > print "Connection Establis...
[ "Yeah, because you're essentially going to be doing two things at the same time, you'll have to create a new thread (using threading) or perhaps more simply a new process (using multiprocessing or just os.fork)\nThe easiest thing to do is to put this part in a function, and use multiprocessing or threading to start...
[ 0 ]
[ "received = \"\"\nwhile True:\n data = socket.recv(1024)\n if not data:\n break # ends the while loop\n received+=data\n\ndo_stuff(received)\n\n" ]
[ -1 ]
[ "loops", "python", "python_multithreading", "while_loop" ]
stackoverflow_0007478020_loops_python_python_multithreading_while_loop.txt
Q: Python import problem in command line mode I have the following code structure running perfectly fine in my IDE(Aptana Studio): /ProjectName/ /lib /src /Module1 /Module2 /Module3 __init__.py pyClass.py ##Python Class /main main.py main.py ...
Python import problem in command line mode
I have the following code structure running perfectly fine in my IDE(Aptana Studio): /ProjectName/ /lib /src /Module1 /Module2 /Module3 __init__.py pyClass.py ##Python Class /main main.py main.py : import Module3.pyClass as pc myClass=pc.pyCla...
[ "The src directory isn't in the python module search path if you run it from the main directory. You'll need to either run the script from the src directory (a wrapper script, or move it) or add the src directory to sys.path. This is probably what you want. Here's how:\nimport os\nimport sys\nsys.path.append(os.pat...
[ 12 ]
[]
[]
[ "importerror", "python" ]
stackoverflow_0007478282_importerror_python.txt
Q: Merging Two Outer Lists Based on Iterated Inner List Value I have two lists of lists - i.e. [['1', 'expired', 'test', '0'], ['31', 'active', 'test', '1']] as well as [['1', 'Andrew', 'Alexander'], ['31', 'John', 'Smith']] Lets call them list1 and list2 I want to merge list1 and list2, but ONLY when (note, this i...
Merging Two Outer Lists Based on Iterated Inner List Value
I have two lists of lists - i.e. [['1', 'expired', 'test', '0'], ['31', 'active', 'test', '1']] as well as [['1', 'Andrew', 'Alexander'], ['31', 'John', 'Smith']] Lets call them list1 and list2 I want to merge list1 and list2, but ONLY when (note, this is pseudocode, trying to figure out how to program this in Python...
[ "If you want [[1, 'a'], [2, 'b']] and [[1, 'c'], [3, 'd']] merged to [[1, 'a', 'c'], [2, 'b'], [3, 'd']]:\nfrom collections import defaultdict\ndict1_2 = defaultdict(list)\ndict1_2.update((item[0], item[1:]) for item in list1)\nfor item in list2:\n dict1_2[item[0]].append(item[1:])\n\nif you want them merged to ...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "iteration", "list", "python" ]
stackoverflow_0007477167_iteration_list_python.txt
Q: Matrix multiplication for sparse matrices in Python I want to multiply a sparse matrix A, with a matrix B which has 0, -1, or 1 as elements. To reduce the complexity of the matrix multiplication, I can ignore items if they are 0, or go ahead and add the column without multiplication if the item is 1, or subs. if i...
Matrix multiplication for sparse matrices in Python
I want to multiply a sparse matrix A, with a matrix B which has 0, -1, or 1 as elements. To reduce the complexity of the matrix multiplication, I can ignore items if they are 0, or go ahead and add the column without multiplication if the item is 1, or subs. if it's -1. The discussion about this is here: Random project...
[ "Have you looked at scipy.sparse? There's no point in re-inventing the wheel, here. Sparse matricies are a fairly standard thing. \n(In the example, I'm using a 300000x4 matrix for easier printing after the multiplication. A 300000x1000 matrix shouldn't be any problem, though. This will be much faster than mult...
[ 11 ]
[]
[]
[ "matrix", "multidimensional_array", "numpy", "python" ]
stackoverflow_0007477733_matrix_multidimensional_array_numpy_python.txt
Q: Equality of Python classes using slots Another question provides a nice, simple solution for implementing a test for equality of objects. I'll repeat the answer for context: class CommonEqualityMixin(object): def __eq__(self, other): return (isinstance(other, self.__class__) and self.__di...
Equality of Python classes using slots
Another question provides a nice, simple solution for implementing a test for equality of objects. I'll repeat the answer for context: class CommonEqualityMixin(object): def __eq__(self, other): return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) def __ne__(self...
[ "import operator\n\nclass CommonEqualityMixin(object):\n\n __slots__ = ()\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n if self.__slots__ == other.__slots__:\n attr_getters = [operator.attrgetter(attr) for attr in self.__slots__]\n ret...
[ 10, 1 ]
[]
[]
[ "class", "equality", "python", "slots" ]
stackoverflow_0004522617_class_equality_python_slots.txt
Q: Create a tree-style directory listing in Python I am trying to list directories and files (recursivley) in a directory with python: ./rootdir ./file1.html ./subdir1 ./file2.html ./file3.html ./subdir2 ./file4.html Now I can list the directories and files just fine (borrowed it from here). But I wo...
Create a tree-style directory listing in Python
I am trying to list directories and files (recursivley) in a directory with python: ./rootdir ./file1.html ./subdir1 ./file2.html ./file3.html ./subdir2 ./file4.html Now I can list the directories and files just fine (borrowed it from here). But I would like to list it in the following format and ORDER...
[ "Try the following:\nfor path, dirs, files in os.walk(\".\"):\n print path\n for file in files:\n print os.path.join(path, file)\n\nYou do not need to print entries from dirs because each directory will be visited as you walk the path, so you will print it later with print path.\n" ]
[ 5 ]
[]
[]
[ "filesystems", "python" ]
stackoverflow_0007478477_filesystems_python.txt
Q: Python implementation of Singleton code goes first: def singleton(cls): instances = {} def get_instance(): if cls not in instances: instances[cls] = cls() return instances[cls] return get_instance @singleton class A: #... Ok, the code above is an implementation of Sing...
Python implementation of Singleton
code goes first: def singleton(cls): instances = {} def get_instance(): if cls not in instances: instances[cls] = cls() return instances[cls] return get_instance @singleton class A: #... Ok, the code above is an implementation of Singleton, I saw this implementation in anot...
[ "When you call MyClass() after it's been decorated, you're right -- you're not actually calling a class, you're calling a function.\nThat function calls the class if cls not in instances and caches it, then returns the cached instance.\nIn other words, there is no reason MyClass() has to call the class directly -- ...
[ 1, 1 ]
[]
[]
[ "decorator", "python", "singleton" ]
stackoverflow_0007478627_decorator_python_singleton.txt
Q: How to reference numpy array objects? I have numpy array: >>> data dtype([('date', '|O4'), ('value', '<f8')] where date object is Python datetime.date object which consists of all days in one year: [2010-1-1, ..., 2010-12-31] and value object is value data for corresponding date. How can I return value data ...
How to reference numpy array objects?
I have numpy array: >>> data dtype([('date', '|O4'), ('value', '<f8')] where date object is Python datetime.date object which consists of all days in one year: [2010-1-1, ..., 2010-12-31] and value object is value data for corresponding date. How can I return value data only for, let's say, September?
[ "You could use a boolean array to index data:\nimport numpy as np\nimport datetime as dt\ndates=[dt.date(2010,1,1)+dt.timedelta(days=i) for i in range(365)]\nvalues=range(365)\ndata=np.array(zip(dates,values),dtype=[('dates','object'),('value','<f8')])\n\n(data['dates']>=dt.date(2010,9,1)) & (data['dates']<dt.date(...
[ 4 ]
[]
[]
[ "indexing", "numpy", "python" ]
stackoverflow_0007478759_indexing_numpy_python.txt
Q: Python double backslash issue I'm using python scripts to send hundreds of thousands of insert queries to an sql server belonging to another system. An example of my inserts: "INSERT INTO ImportData (ISBNORISSNORURL, FILENAME, PDFLOCATIONS, PROCESSED) VALUES('0442019521', 'pinto_1995_245_hires.pdf', 'I:\\Collect...
Python double backslash issue
I'm using python scripts to send hundreds of thousands of insert queries to an sql server belonging to another system. An example of my inserts: "INSERT INTO ImportData (ISBNORISSNORURL, FILENAME, PDFLOCATIONS, PROCESSED) VALUES('0442019521', 'pinto_1995_245_hires.pdf', 'I:\\Collect and Process Data\\Licensing Scheme...
[ "The only reason that string would not have its double backslashes convert to single backslashes is if it is a raw string -- check how it's being built.\nEdit\nOkay, now that you have actual code posted -- there are no double backslashes. The problem is happening during the str(dict.keys()) -- it's putting in all ...
[ 1, 1 ]
[]
[]
[ "python", "sql_server" ]
stackoverflow_0007478306_python_sql_server.txt
Q: Python Parallel Processing Amazon EC2 or Alternatives? I'm working on running a Memory/CPU intensive project on a cloud service, from my Googling and research it looks like I should use Amazon EC2 as there are guides it using MPI - however, reading up on stackoverflow about people's comparison of EC2 with rackspac...
Python Parallel Processing Amazon EC2 or Alternatives?
I'm working on running a Memory/CPU intensive project on a cloud service, from my Googling and research it looks like I should use Amazon EC2 as there are guides it using MPI - however, reading up on stackoverflow about people's comparison of EC2 with rackspace, joyent, etc, I was wondering if this is really the best c...
[ "Your requirements are too vague for a specific response. It is unlikely you are going to be able to elaborate them sufficiently for anybody to provide an authoritative answer.\nFortunately for you, many Infrastructure as a Service platforms like AWS and Rackspace let you test things out extremely inexpensively (l...
[ 1 ]
[]
[]
[ "amazon_ec2", "cloud", "multithreading", "parallel_processing", "python" ]
stackoverflow_0007478803_amazon_ec2_cloud_multithreading_parallel_processing_python.txt
Q: Data Structures - lists This is homework but the lesson gives me the answer already. I'm having trouble putting the words from the answer to the line of code #Calculate all the primes below 1000 result = [1] candidates = range(3, 1000) base = 2 product = base while candidates: while product < 10...
Data Structures - lists
This is homework but the lesson gives me the answer already. I'm having trouble putting the words from the answer to the line of code #Calculate all the primes below 1000 result = [1] candidates = range(3, 1000) base = 2 product = base while candidates: while product < 1000: if product in c...
[ "At the start of each of the while candidates: loops, product equals base. Then in that loop you have another loop, while products < 1000. At the end of this loop you increment product by base. So product goes through each multiple of base. You then remove all the values of product which is where you \"remove multi...
[ 1 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0007478915_data_structures_python.txt
Q: do I need to define an PyMODINIT_FUNC for Boost.Python to expose a C++ class? I have libboost installed via Ubuntu. The boost version is 1.42. I've followed the example on the Boost website: #include <string> struct World { void set(std::string msg) { this->msg = msg; } std::string greet() { return msg; }...
do I need to define an PyMODINIT_FUNC for Boost.Python to expose a C++ class?
I have libboost installed via Ubuntu. The boost version is 1.42. I've followed the example on the Boost website: #include <string> struct World { void set(std::string msg) { this->msg = msg; } std::string greet() { return msg; } std::string msg; }; then created the idl: #include <boost/python.hpp> using n...
[ "ok, I found out why this wasn't working. My C++ class was in one file, and my IDL was in another. Because it didn't look like python OR C++ to me, I thought it belonged in separate file. So the IDL stuff was never getting picked up.\nOnce I put it all together in World.cpp, everything worked as expected! Very smoo...
[ 0 ]
[]
[]
[ "boost", "c++", "python" ]
stackoverflow_0007472245_boost_c++_python.txt
Q: How to access the request.user in a Piston classmethod I have a model which contains a ManyToMany to User to keep track of which users have 'favorited' a particular model instance. In my API for this model, when requested by an authenticated user, I'd like to include an 'is_favorite' boolean. However, it seems tha...
How to access the request.user in a Piston classmethod
I have a model which contains a ManyToMany to User to keep track of which users have 'favorited' a particular model instance. In my API for this model, when requested by an authenticated user, I'd like to include an 'is_favorite' boolean. However, it seems that any api fields that aren't straight model attributes must ...
[ "I am not aware of the piston API, but how about using the thread locals middleware to access the request\nadd this to middleware\ntry: \n from threading import local \nexcept ImportError: ...
[ 0, 0 ]
[]
[]
[ "django", "django_piston", "python" ]
stackoverflow_0003580653_django_django_piston_python.txt
Q: How can I make my program execute a function from a keyboard shortcut? How can I do it, even if my application.exe is not the focused window ? For example, like the Windows+D shortcut... Works everywhere... I want that ALT+1 does a function, ALT+2 does another one, and so on... A: You mean like this? A: You ne...
How can I make my program execute a function from a keyboard shortcut?
How can I do it, even if my application.exe is not the focused window ? For example, like the Windows+D shortcut... Works everywhere... I want that ALT+1 does a function, ALT+2 does another one, and so on...
[ "You mean like this?\n", "You need to use pyHook.\n", "I have a pyHook example on my site. http://fadedbluesky.com/2011/using-pyhook-to-block-windows-key/\nI originally wrote this to block keys in a game written using pygame. You should be able to easily adapt it to other windows programs.\n" ]
[ 2, 1, 1 ]
[]
[]
[ "keyboard", "python", "shortcut" ]
stackoverflow_0002339165_keyboard_python_shortcut.txt
Q: Python and Functions I'll admit it, I am very new to python and need some help. I am trying to convert a very simple calculator from c++ to python. Here is the code so far: x = 0 y = 0 sign = '+' def getnum(prompt, number): number = input(prompt) def getsign(prompt, sign): sign = raw_input(prompt) pr...
Python and Functions
I'll admit it, I am very new to python and need some help. I am trying to convert a very simple calculator from c++ to python. Here is the code so far: x = 0 y = 0 sign = '+' def getnum(prompt, number): number = input(prompt) def getsign(prompt, sign): sign = raw_input(prompt) print sign def calc(string, ...
[ "There are a number of issues. \nLet's look at them in the interactive Python interpreter, which is an invaluable tool when you're experimenting with Python.\nFirstly, getnum() doesn't do what you think it does...\n>>> def getnum(prompt, number):\n... number = input(prompt)\n...\n>>> x = 0\n>>> getnum(\"Enter f...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "function", "python" ]
stackoverflow_0007478798_function_python.txt
Q: python: key combinations such óíúéáöïò with pyhook I'm learning about pyhook as keylogger and coding some examples. I dont know how to log key sequences like óíúö because the result thats something like this -> ´´i´´o anyone knows how to solve this issue ? thx you. A: I have an example on my site that allows yo...
python: key combinations such óíúéáöïò with pyhook
I'm learning about pyhook as keylogger and coding some examples. I dont know how to log key sequences like óíúö because the result thats something like this -> ´´i´´o anyone knows how to solve this issue ? thx you.
[ "I have an example on my site that allows you to see a lot of the information that pyHook provides. http://fadedbluesky.com/2011/using-pyhook-to-block-windows-key/\nPerhaps it can help you find the ScanCode for the key you want.\n" ]
[ 0 ]
[]
[]
[ "keylogger", "pyhook", "python" ]
stackoverflow_0005195811_keylogger_pyhook_python.txt
Q: Google App Engine upgrade error I was trying to upgrade to 1.5.4 and I downloaded the new version from the download page and now when I click the browse button on the Launcher I get and ascii error. Does anyone know what is going on? This is the error: Traceback (most recent call last): File "C:\Program Files ...
Google App Engine upgrade error
I was trying to upgrade to 1.5.4 and I downloaded the new version from the download page and now when I click the browse button on the Launcher I get and ascii error. Does anyone know what is going on? This is the error: Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\google\...
[ "That's the code path for loading the script: file specified in app.yaml. It expects to find 7-bit clean ascii, but is finding something else.\nAny chance that the python script specified by script: (which appears to be ting.py) got garbled?\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007479272_google_app_engine_python.txt
Q: Python on website to connect to phone connected to computer I know the title is a bit off, but what I'm asking is if it is possible to have a python script on my website that can detect if my Android phone is connected to the computer Im using to view the page. I don't know if this is possible since I think python...
Python on website to connect to phone connected to computer
I know the title is a bit off, but what I'm asking is if it is possible to have a python script on my website that can detect if my Android phone is connected to the computer Im using to view the page. I don't know if this is possible since I think python is server-side, but maybe this is possible to do with JavaScript...
[ "What you're looking for isn't possible and should not be possible for security concerns. Do you want someone knowing what devices you have connected to your computer? You're essentially wanting a device sniffer but a website would not be capable of accessing the client's machine in this manner to access the desi...
[ 1, 1 ]
[]
[]
[ "android", "django", "javascript", "python" ]
stackoverflow_0007478590_android_django_javascript_python.txt
Q: Escaping special characters in filepaths using SQLAlchemy I'm storing filenames and filepaths in MySQL. Retrieving them from the database using LIKE expressions requires that I escape all allowed filename chars that collide with MySQL special chars. I'm happy to simply use Python's string.replace() method, but w...
Escaping special characters in filepaths using SQLAlchemy
I'm storing filenames and filepaths in MySQL. Retrieving them from the database using LIKE expressions requires that I escape all allowed filename chars that collide with MySQL special chars. I'm happy to simply use Python's string.replace() method, but was wondering if there was a more standard or built-in method of...
[ "SQLAlchemy do sanitize for you if you will use regular queries. Maybe the problem that you use like clause. Like require addition escape for such symbols: _%. Thus you will need replace methods if you want to quote like expression.\n" ]
[ 0 ]
[ "Why do you need to escape the file paths? As far as you are not manually writing select / insert queries, SQLAlchemy will take care of the escaping when it generates the query internally.\nThe file paths can be inserted as they are into the database.\n", "As I know there isn’t what you are looking for in SQLAlch...
[ -3, -3, -4 ]
[ "escaping", "filepath", "mysql", "python", "sqlalchemy" ]
stackoverflow_0006713715_escaping_filepath_mysql_python_sqlalchemy.txt
Q: Installing python ldap module under cygwin I am trying to install the basic ldap python module under cygwin. The following is failing: %easy_install ldap Searching for ldap... .. No local packages or download links found for ldap I am using cherrypy for an app which is running fine in Ubuntu, and planning to port...
Installing python ldap module under cygwin
I am trying to install the basic ldap python module under cygwin. The following is failing: %easy_install ldap Searching for ldap... .. No local packages or download links found for ldap I am using cherrypy for an app which is running fine in Ubuntu, and planning to port it to cygwin so I can run the app under my Win7...
[ "Another stackoverflow page came to rescue: python-ldap OS X 10.6 and Python 2.6\nThe final solution:\npip install python-ldap==2.3.13\n\nNoting it here so people facing this in cygwin can use this post.\n", "Are you sure it's not easy_install python-ldap you want?\nThe Django LDAP authorization middleware is mi...
[ 9, 0 ]
[]
[]
[ "cygwin", "python" ]
stackoverflow_0007466959_cygwin_python.txt
Q: python operator precedence of in and comparison The following comparisons produce True: >>> '1' in '11' True >>> ('1' in '11') == True True And with the parentheses the other way, I get a TypeError: >>> '1' in ('11' == True) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: argum...
python operator precedence of in and comparison
The following comparisons produce True: >>> '1' in '11' True >>> ('1' in '11') == True True And with the parentheses the other way, I get a TypeError: >>> '1' in ('11' == True) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: argument of type 'bool' is not iterable So how do I get F...
[ "The Python manual says in and == are of equal precedence. Thus, they're evaluated from left to right by default, but there's also chaining to consider. The expression you put above ('1' in '11' == True) is actually being evaluated as...\n('1' in '11') and ('11' == True)\n\nwhich of course is False. If you don't kn...
[ 21, 9, 2 ]
[ "What happen here?\n'1' in '11' == True ==> False\n\nis the same that:\n'1' in ('11' == True)\n\nbut\n('11' == True) ==> False\n\nand\n'1' in False\n\nis not defined.\n" ]
[ -4 ]
[ "python" ]
stackoverflow_0007479808_python.txt
Q: How to Convert Json Value of Http Post Parameter to Python Dict in Django? I am using Django to receive and process push notifications from the foursquare real-time api. Each checkin is pushed as a POST request to my server containing a single parameter named checkin. I am trying to grab the value of the checkin p...
How to Convert Json Value of Http Post Parameter to Python Dict in Django?
I am using Django to receive and process push notifications from the foursquare real-time api. Each checkin is pushed as a POST request to my server containing a single parameter named checkin. I am trying to grab the value of the checkin parameter and convert it to a python dict. However, calling json.loads always res...
[ "Try json.loads(checkin_json) instead of json.load(request.POST). Notice the extra 's'.\n", "change checkin = json.load(request.POST) to checkin = json.loads(checkin_json)\n" ]
[ 4, 0 ]
[ "On python, boolean values are Capitalized (first letter is uppercase): True/False. \nCheck this.\nEDIT:\nPay attentiot at this lines:\n\"primary\": true\n }\n],\n\"verified\": true,\n\nBoth \"true\" values are lowercase and need to be capitalized\n" ]
[ -1 ]
[ "api", "django", "foursquare", "json", "python" ]
stackoverflow_0007479919_api_django_foursquare_json_python.txt
Q: Does pymysql (a python module) support use_result like MySQLdb? I use pymysql in my project , and need use_result to fetch rows? There is a fetchmany function in pymysql . Is it the same as use_result ? A: mysql_use_result() + mysql_fetch_row() is used in mysql to fetch the data 1 row at a time and store it cli...
Does pymysql (a python module) support use_result like MySQLdb?
I use pymysql in my project , and need use_result to fetch rows? There is a fetchmany function in pymysql . Is it the same as use_result ?
[ "mysql_use_result() + mysql_fetch_row() is used in mysql to fetch the data 1 row at a time and store it client side.\nIn pymysql, you can use the fetchone() function for this purpose. You can also use fetchmany() to fetch a subset of rows, and fetchall() to store the whole result clientside - like mysql_store_resul...
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0007479602_mysql_python.txt
Q: Python script to find word frequencies of a given document I am looking for a simple script that can find frequencies of words for a given document (probably by using portable stemmer). Is there any library or simple script that does this process? A: use nltk import nltk YOUR_STRING = "Your words" words = [w f...
Python script to find word frequencies of a given document
I am looking for a simple script that can find frequencies of words for a given document (probably by using portable stemmer). Is there any library or simple script that does this process?
[ "use nltk\nimport nltk\n\nYOUR_STRING = \"Your words\"\n\nwords = [w for w in YOUR_STRING.split()]\nfreq_dist = nltk.FreqDist(words)\n\ntokens = freq_dist.keys()\n\n#50 most frequent\nmost_frequent = tokens[:50]\n\n#50 least frequent\nleast_frequent = tokens[-50:]\n\n", "You should be able to count words. Use a ...
[ 2, 0 ]
[]
[]
[ "information_retrieval", "python" ]
stackoverflow_0007480000_information_retrieval_python.txt
Q: Can anyone help me figure out the parsing error in this code? The output of this code is quite similar but not exactly what it's supposed to be. The code is: def printMultiples(n): i = 1 while (i <= 10): print(n*i, end = ' ') i += 1 n = 1 while (i<= 3): printMultiples(n) n += 1 Th...
Can anyone help me figure out the parsing error in this code?
The output of this code is quite similar but not exactly what it's supposed to be. The code is: def printMultiples(n): i = 1 while (i <= 10): print(n*i, end = ' ') i += 1 n = 1 while (i<= 3): printMultiples(n) n += 1 The output is: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 ...
[ "add an empty print at the end of the printMultiples, outside the while (i <= 10): loop.\n", "Your problem is that you are not printing a new line after each list of multiples. You could solve this by putting at the end of your printMultiples function outside of the loop the line\nprint()\n\n", "To make the col...
[ 1, 0, 0, 0 ]
[]
[]
[ "numpy", "python", "python_3.x" ]
stackoverflow_0007480065_numpy_python_python_3.x.txt
Q: What migration order does South follow across different apps? I've recently begun using South for migrations in my Django project. All was going well until recently when I ran into a peculiar issue. I have two apps in my project, say, App-A and App-B. A model in App-A has a foreign key to a model in App-B. When I'...
What migration order does South follow across different apps?
I've recently begun using South for migrations in my Django project. All was going well until recently when I ran into a peculiar issue. I have two apps in my project, say, App-A and App-B. A model in App-A has a foreign key to a model in App-B. When I've been trying to build my system, I ran syndb which created all th...
[ "This explained it https://south.readthedocs.io/en/latest/dependencies.html.\n\nMigrations for apps are nice ‘n all, but when you start writing a\nlarge project, with a lot of apps, you realise you have foreign key\nrelationships between apps and working out what order migrations would\nneed to be applied in for ea...
[ 16, 12 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0007474745_django_django_south_python.txt
Q: Capture body content in Mako? Is it possible to get the rendered body content from within a Mako template? What I mean is that I can display the body using ${self.body()}, but what if I want to do something to it first? A: Apparently what I was looking for is the capture function. From the docs: The other way t...
Capture body content in Mako?
Is it possible to get the rendered body content from within a Mako template? What I mean is that I can display the body using ${self.body()}, but what if I want to do something to it first?
[ "Apparently what I was looking for is the capture function. From the docs:\n\nThe other way to buffer the output of a def or any Mako callable is by\n using the built-in capture function. This function performs an\n operation similar to the above buffering operation except it is\n specified by the caller.\n\n${\...
[ 4, 1 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0007479572_mako_python.txt
Q: How can I add all values in a list of dictionaries? Is there a simple way of getting the total price of all the fruits in a list of dictionaries in Python? [{'name':'apple','price':10},{'name':'banana','price':5},{'name':'grapes','price':15}] A: Try the following line: sum(item['price'] for item in list)
How can I add all values in a list of dictionaries?
Is there a simple way of getting the total price of all the fruits in a list of dictionaries in Python? [{'name':'apple','price':10},{'name':'banana','price':5},{'name':'grapes','price':15}]
[ "Try the following line:\nsum(item['price'] for item in list)\n\n" ]
[ 8 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007480572_dictionary_python.txt
Q: How to update the cookie in a request header? I'm a newbie to python / web development and am working on a script logging in the google account with urllib2 and cookielib. Currently I get stuck by the 'Set-Cookie' staff. In the very beginning, I'm using httplib to send request. When I post a login request, the re...
How to update the cookie in a request header?
I'm a newbie to python / web development and am working on a script logging in the google account with urllib2 and cookielib. Currently I get stuck by the 'Set-Cookie' staff. In the very beginning, I'm using httplib to send request. When I post a login request, the response headers contain a dozen of 'Set-Cookie' entr...
[ "Here you can find an example on how to do this. The idea is to have a cookie jar storing all the collected cookies. The jar gets used by urllib2's opener. I hope this helps.\n" ]
[ 0 ]
[]
[]
[ "cookies", "http", "python" ]
stackoverflow_0007480055_cookies_http_python.txt
Q: Storing more than one key value in a tuple with python? I'm new to Python and still learning. I was wondering if there was a standard 'best practice' for storing more than one key value in a tuple. Here's an example: I have a value called 'red' which has a value of 3 and I need to divide it by a number (say 10). I...
Storing more than one key value in a tuple with python?
I'm new to Python and still learning. I was wondering if there was a standard 'best practice' for storing more than one key value in a tuple. Here's an example: I have a value called 'red' which has a value of 3 and I need to divide it by a number (say 10). I need to store 3 values: Red (the name), 3 (number of times i...
[ "The syntax for tuples is: (a,b,c).\nIf you want a dictionary with multiple values you can have a list as the value: {'red':[3,1]}.\nYou may want to also consider named tuples, or even classes. This will allow you to name the fields instead of accessing them by index, which will make the code more clear and structu...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007481051_python.txt
Q: Django error 'too many values to unpack' in objects.get(id) I have url like this http://gagandeepdesk/2690/ which I am filtering with urls.py file and sending 2690 as one of the parameters to the function. my urls.py filter looks like this, url(r'^(\d+)/', 'scango.scanner.views.download'), And that function looks...
Django error 'too many values to unpack' in objects.get(id)
I have url like this http://gagandeepdesk/2690/ which I am filtering with urls.py file and sending 2690 as one of the parameters to the function. my urls.py filter looks like this, url(r'^(\d+)/', 'scango.scanner.views.download'), And that function looks like this, def download(request, MediaId): media = Media.obj...
[ " (r'^(?P<MediaId>\\d+)/$', 'scango.scanner.views.download')\n\nMaybe try this instead?\nThis is an example of named groups.\n\nIn Python regular expressions, the syntax for named regular expression\n groups is (?Ppattern), where name is the name of the group and\n pattern is some pattern to match.\n\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007481172_django_python.txt
Q: Numeric function for log of sum in Python Given log(a) and log(b), I want to compute log(a+b) (in a numerically stable way). I wrote a little function for this: def log_add(logA,logB): if logA == log(0): return logB if logA<logB: return log_add(logB,logA) return log( 1 + math.exp(logB-l...
Numeric function for log of sum in Python
Given log(a) and log(b), I want to compute log(a+b) (in a numerically stable way). I wrote a little function for this: def log_add(logA,logB): if logA == log(0): return logB if logA<logB: return log_add(logB,logA) return log( 1 + math.exp(logB-logA) ) + logA I wrote a program where this is ...
[ "Note: Best answer until now is to simply use numpy.logaddexp(logA,logB).\nWhy exactly do you compare with log(0)? This is equal to -numpy.inf, in this case you come to log(1 + math.exp(-inf-logB) ) + logB Which reduces itself to logB. This call always will give an warning message which is extremely slow.\nI could ...
[ 8 ]
[ "def log_add(logA, logB): \n return math.log(math.exp(logA) + math.exp(logB))\n\nis too slow? or inaccurate?\n" ]
[ -1 ]
[ "logarithm", "numerical_computing", "python" ]
stackoverflow_0007480996_logarithm_numerical_computing_python.txt
Q: create table using python objects I'm using sqlite3 in a Python script to extract data from a client's spreadsheet. My client is planning to add on to the spreadsheet, so my sqlite code should generate its columns based on the headers I extract from the first line. How do I do this? This is my naive attempt: im...
create table using python objects
I'm using sqlite3 in a Python script to extract data from a client's spreadsheet. My client is planning to add on to the spreadsheet, so my sqlite code should generate its columns based on the headers I extract from the first line. How do I do this? This is my naive attempt: import sqlite3 conn = sqlite3.connect('./...
[ "I think, csv module of python can help you to extract file data.\nFirst, convert your spreadsheet in csv format (save as csv command) with appropriate delimiter.\nthen, try below code snippet:\nimport csv\nfile_ptr = open('filename.csv','r');\nfields = range(0, total number of columns in file header)\nfile_data = ...
[ 1 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0007479444_python_sqlite.txt
Q: What is a good way to simulate particle movement? I am trying to simulate the following: 10 balls that are moving in an area of fixed dimensions Whenever two or more balls come into a proximity range of say 40m, I want an event to be triggered My idea is to utilize a movement trace with different properties to ...
What is a good way to simulate particle movement?
I am trying to simulate the following: 10 balls that are moving in an area of fixed dimensions Whenever two or more balls come into a proximity range of say 40m, I want an event to be triggered My idea is to utilize a movement trace with different properties to guide the movement of the balls and study how each of t...
[ "I'm suspecting what you are looking for is collision detection and/or response algorithms. You might find this question and answer doing almost exactly the same as your scenario. For good explanation of underlying physics and math I find these old articles from Chris Hecker very useful.\n", "For physics (moving ...
[ 1, 0, 0 ]
[]
[]
[ "physics", "python", "simulation" ]
stackoverflow_0007481375_physics_python_simulation.txt
Q: Why commit not give changes if we use session.begin_nested of SQLAlchemy? I have table in mysql and engine is InnoDB. System Configuration mysql --version mysql Ver 14.14 Distrib 5.1.58, for redhat-linux-gnu (x86_64) using readline 5.1 python --version Python 2.7 file: test.py from sqlalchemy import create_engi...
Why commit not give changes if we use session.begin_nested of SQLAlchemy?
I have table in mysql and engine is InnoDB. System Configuration mysql --version mysql Ver 14.14 Distrib 5.1.58, for redhat-linux-gnu (x86_64) using readline 5.1 python --version Python 2.7 file: test.py from sqlalchemy import create_engine engine = create_engine('mysql://test:test@localhost/test1', echo=True) from...
[ "EDIT: since the answer has been accepted, I edited to make it more clear in the view of a new information as defined by comments below.\nUnless you use autocommit=True, the transaction is started automatically, and therefore you do not need to call session.begin() explicitly.\n" ]
[ 3 ]
[]
[]
[ "mysql", "python", "session", "sqlalchemy" ]
stackoverflow_0007481115_mysql_python_session_sqlalchemy.txt
Q: django conditional url verify_exists I have 3 url fields defined in my model as follows: image_1 = models.URLField(max_length=100, verify_exists=True, blank=True) image_2 = models.URLField(max_length=100, verify_exists=True, blank=True) image_3 = models.URLField(max_length=100, verify_exists=True, blank=True) My ...
django conditional url verify_exists
I have 3 url fields defined in my model as follows: image_1 = models.URLField(max_length=100, verify_exists=True, blank=True) image_2 = models.URLField(max_length=100, verify_exists=True, blank=True) image_3 = models.URLField(max_length=100, verify_exists=True, blank=True) My question is, is there a way I can test whe...
[ "What django does is it use's the URLValidator to see if the url is valid or not.\nwhat you could is use the same validations which is present in django.core \nEDIT:\nFor example lets say you have to validate if django official website with url https://www.djangoproject.com/, exists or not. the code would simply lo...
[ 5 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007481746_django_django_models_python.txt
Q: Pootle - issues exporting properties files I am using pootle for localization. I imported source translations from Java properties files. the property file looks like: STR_TEXT1 = Hello Than I imported other language files. I paid translators to translate those other languages. Now I need to export those translat...
Pootle - issues exporting properties files
I am using pootle for localization. I imported source translations from Java properties files. the property file looks like: STR_TEXT1 = Hello Than I imported other language files. I paid translators to translate those other languages. Now I need to export those translations from pootle back to JAVA property files. P...
[ "Pootle should export you files as Latin1 not UTF-8, it will escape non-Latin characters using \\uXXXX syntax. Newer Pootle's allow you to export in UTF-8.\nThe best is to attach your source and translated files to a bug over at bugs.locamotion.org so that the Pootle developers can look at your source files.\nThe ...
[ 0 ]
[]
[]
[ "java", "localization", "pootle", "python", "translation" ]
stackoverflow_0007389649_java_localization_pootle_python_translation.txt
Q: Convert string "list" to an object How would you convert this to an object that you can iterate through [{u'pk': u'1', u'quantity': u'2', u'name': u'3mm aliminum sheet', u'size': u'300x322'},{u'pk': u'2', u'quantity': u'1', u'name': u'2mm aliminum sheet', u'size': u'300x322'}] This data is saved as above in a Ch...
Convert string "list" to an object
How would you convert this to an object that you can iterate through [{u'pk': u'1', u'quantity': u'2', u'name': u'3mm aliminum sheet', u'size': u'300x322'},{u'pk': u'2', u'quantity': u'1', u'name': u'2mm aliminum sheet', u'size': u'300x322'}] This data is saved as above in a CharField() in my Django model. Now I need...
[ "Don't do that. Use a JSONField - for an example implementation see here - and store the content as valid JSON, rather than a stringified dict.\n", "s = \"[{u'pk': u'1', u'quantity': u'2', u'name': u'3mm aliminum sheet', u'size': u'300x322'},{u'pk': u'2', u'quantity': u'1', u'name': u'2mm aliminum sheet', u'size'...
[ 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007482802_django_python.txt
Q: Django form for multiple models failed to return HttpResponse I am going mad trying to figure this problem out. I have a form which has multiple models. Basically someone writes a story and then puts their username in and this username is associated with that story. It's all pretty basic...apparently not for djang...
Django form for multiple models failed to return HttpResponse
I am going mad trying to figure this problem out. I have a form which has multiple models. Basically someone writes a story and then puts their username in and this username is associated with that story. It's all pretty basic...apparently not for django. Aside from searching for hours to find something that helps with...
[ "This has nothing to do with multiple models or inserts. The issue should be obvious: you have a set of nested if statements, and only one return right at the most deeply nested bit. What happens if it's not a POST, or if form a is not valid, or form p is not valid? Django expects a view to return a response in all...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007482496_django_python.txt
Q: Python 2.7: Cannot use subparsers with argparse on Solaris I installed python2.7 on a Solaris server, and am working on a Python script using argparse to retrieve command line options. Everything worked greate until I started using subparsers. The script fails giving this error: AttributeError: 'ArgumentParser' o...
Python 2.7: Cannot use subparsers with argparse on Solaris
I installed python2.7 on a Solaris server, and am working on a Python script using argparse to retrieve command line options. Everything worked greate until I started using subparsers. The script fails giving this error: AttributeError: 'ArgumentParser' object has no attribute 'add_subpasers' Here's a short copy of th...
[ "line 2: you wrote parser.add_subpasers instead of parser.add_subparsers...\n", "Yes, you have a typo - it's add_subparsers not add_subpasers in line 3 of your script.\n" ]
[ 2, 1 ]
[]
[]
[ "argparse", "python", "solaris" ]
stackoverflow_0007482959_argparse_python_solaris.txt
Q: MySQL queries in python taking a lot of time, postgres queries work fine I am using a time profiler for optimizing my python script. It turns out that mysql queries are taking lot of time in my python scripts. There are total of only 19 queries. These 19 mysql queries take over 7.44 secs as reported by cProfile. ...
MySQL queries in python taking a lot of time, postgres queries work fine
I am using a time profiler for optimizing my python script. It turns out that mysql queries are taking lot of time in my python scripts. There are total of only 19 queries. These 19 mysql queries take over 7.44 secs as reported by cProfile. Following is the complete script footprint, with mysql query and respective qu...
[ "Probably you forgot to create an index on (foreign_key, somecolumn) resulting in MySQL needing to perform a full table scan to find the data. You can see this by running with EXPLAIN:\nEXPLAIN SELECT column FROM table WHERE foreign_key = 1 AND somecolumn='val1'\n\n", "have you tried enabling the slow queries log...
[ 3, 0 ]
[]
[]
[ "mysql", "performance", "python" ]
stackoverflow_0007483261_mysql_performance_python.txt
Q: How to crawl links to a particular domain by searching on Google? I have a corpus of lyrics of Indian songs and need to tag them with their year of release for an experiment I am working on. There is a website(lyricsindia.net), which has an exhaustive database of these lyrics with years, but unfortunately the lyri...
How to crawl links to a particular domain by searching on Google?
I have a corpus of lyrics of Indian songs and need to tag them with their year of release for an experiment I am working on. There is a website(lyricsindia.net), which has an exhaustive database of these lyrics with years, but unfortunately the lyrics cannot be searched on the website. Instead, when I google with part ...
[ "Your search string could be a part of the url with Scrapy. something like google.com?q=my+string\nOr, you can retrieve the search form, and fill it with your string, something like :\nreturn [FormRequest.from_response(response,\n formdata={'search': 'you\\'re search string'},\n callback=self....
[ 0 ]
[]
[]
[ "data_mining", "python", "scrapy", "web_crawler" ]
stackoverflow_0007483118_data_mining_python_scrapy_web_crawler.txt
Q: Cleaning memory after loading data from a JSON I am loading a JSON file to parse it and convert it (only a part of the JSON) to a CSV. So at the end of the method I would free the space of the loaded JSON. Here is the method: def JSONtoCSV(input,output): outputWriter = csv.writer(open(output,'wb'), delimiter=',...
Cleaning memory after loading data from a JSON
I am loading a JSON file to parse it and convert it (only a part of the JSON) to a CSV. So at the end of the method I would free the space of the loaded JSON. Here is the method: def JSONtoCSV(input,output): outputWriter = csv.writer(open(output,'wb'), delimiter=',') jsonfile = open(input).read() data = loads(...
[ "del data\n\nshould do it if you only have one reference. Keep in mind this will happen automatically when the current scope ends (the function returns).\nAlso, you don't need to keep the jsonfile string around, you can just\ndata = json.load(open(input))\n\nto read the JSON data directly from the file.\nIf you wan...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "json", "python" ]
stackoverflow_0007272205_json_python.txt
Q: How can I send a user registration confirmation email using Tornado and MongoDB? I'm working with Tornado and MongoDB and I would like to send a confirmation email to the user when he creates an account in my application. For the moment, I use a simple XHTML page with a form and I send information to my MongoDB da...
How can I send a user registration confirmation email using Tornado and MongoDB?
I'm working with Tornado and MongoDB and I would like to send a confirmation email to the user when he creates an account in my application. For the moment, I use a simple XHTML page with a form and I send information to my MongoDB database using Tornado. I would like to have an intermediate step which sends an email t...
[ "What you need is an activation URL. The activation URL contains a unique ID, a UUID perhaps, which is verified when the user clicks the activation URL.\nTo avoid storing the user data in the database, you could store the user data in the activation URL sent to the user:\nimport urllib\ndata = urllib.urlencode({'na...
[ 8, 6 ]
[]
[]
[ "email", "python", "tornado" ]
stackoverflow_0005862238_email_python_tornado.txt
Q: Clone a module and make changes to the copy Is it possible to copy a module, and then make changes to the copy? To phrase another way, can I inherit from a module, and then override or modify parts of it? A: To phrase another way, can I inherit from a module, and then override or modify parts of it? Yes. import...
Clone a module and make changes to the copy
Is it possible to copy a module, and then make changes to the copy? To phrase another way, can I inherit from a module, and then override or modify parts of it?
[ "\nTo phrase another way, can I inherit from a module, and then override or modify parts of it?\n\nYes.\nimport module\n\nYou can use stuff from module or override stuff in your script.\nYou can also do this to create a \"derived\" module.\nCall this \"module_2\".\nfrom module import *\n\nWhich imports everything. ...
[ 3, 0 ]
[]
[]
[ "copy", "inheritance", "module", "python", "python_3.x" ]
stackoverflow_0007483022_copy_inheritance_module_python_python_3.x.txt
Q: Metaclass conflict, multiple inheritance, and instance as parent I've been messing around with the dark arts of Python and there's something I'd like help understanding. Given a class Foo, here's some ways I attempted to inherit from it: class A(Foo) — Works, unsurprizingly class B(Foo()) — works provided Foo has...
Metaclass conflict, multiple inheritance, and instance as parent
I've been messing around with the dark arts of Python and there's something I'd like help understanding. Given a class Foo, here's some ways I attempted to inherit from it: class A(Foo) — Works, unsurprizingly class B(Foo()) — works provided Foo has an appropriate __new__ method (which I provided) class C(Foo(), Foo) ...
[ "When you \"inherent from an instance\", what you're really doing is a strange way of using a metaclass. Normally, class objects are instances of type. In the case of class B above, it inherits from an instance of Foo. This is exactly what would happen if you defined a class with Foo as its metaclass, and then inhe...
[ 5 ]
[]
[]
[ "inheritance", "metaclass", "python" ]
stackoverflow_0007483328_inheritance_metaclass_python.txt
Q: Error in email sending during testcase in django? I have a simple django application which allows users to add a new user.Whenever we created a new user,a mail will send to that respective email-id (what we gave while creating a new user).If i have added any new user with email say xxxx@xxxx.com,a mail will send s...
Error in email sending during testcase in django?
I have a simple django application which allows users to add a new user.Whenever we created a new user,a mail will send to that respective email-id (what we gave while creating a new user).If i have added any new user with email say xxxx@xxxx.com,a mail will send succesfully to xxxx@xxxx.com.I have no problem here. But...
[ "You appear to be writing something that isn't Python.\nThat __init__ method does nothing. Remove it.\nIn fact, remove the class altogether. This isn't Java: if you're not storing state or encapsulating functionality, there's no reason to have a class. Just use the send_email function on its own.\n" ]
[ 0 ]
[]
[]
[ "django", "python", "testcase" ]
stackoverflow_0007482799_django_python_testcase.txt
Q: Python Apps and Python Interpreter? I'm wondering how many python interpreter would be executed for distinct python apps? Say I have 6 different python apps up and running, so does that mean there are 6 different python interpreters are running for each of them? A: when executing a python script, you have 1 inte...
Python Apps and Python Interpreter?
I'm wondering how many python interpreter would be executed for distinct python apps? Say I have 6 different python apps up and running, so does that mean there are 6 different python interpreters are running for each of them?
[ "when executing a python script, you have 1 interpreter running per process executing.\n\nif your application executes in a single process, you have 1 interpreter executing for each instance of your application. \nif your application launches multiple processes, then you get additional interpreters for each process...
[ 5, 1, 1 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0007482493_python_scripting.txt
Q: Django SyntaxError at / Non-ASCII character '\xe6' in file I am getting this error: SyntaxError at / Non-ASCII character '\xe6' in file pointed to my forms.py file which has some chinese characters I have to put # -*- coding: utf-8 -*- at the start the forms.py file before it would work I thought Django handles e...
Django SyntaxError at / Non-ASCII character '\xe6' in file
I am getting this error: SyntaxError at / Non-ASCII character '\xe6' in file pointed to my forms.py file which has some chinese characters I have to put # -*- coding: utf-8 -*- at the start the forms.py file before it would work I thought Django handles everything in unicode? What's wrong?
[ "Nothing is wrong. You have done the correct thing. If you want to use non-ASCII characters in your code, you need to tell Python what encoding you are using.\nThis has nothing to do with Django, or Unicode. \n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007483839_django_python.txt
Q: Python - the zipfile module doesn't seem to work with passwords I've been trying to implement a very simple script, extracting zip files that are password protected. I have created a simple zip file (test.zip) with the password "1234" containing 2 text files (1.txt, 2.txt) and i wrote this script: import zipfile ...
Python - the zipfile module doesn't seem to work with passwords
I've been trying to implement a very simple script, extracting zip files that are password protected. I have created a simple zip file (test.zip) with the password "1234" containing 2 text files (1.txt, 2.txt) and i wrote this script: import zipfile PASSWORD = "1234" zip = zipfile.ZipFile("test.zip", "r") zip.setpass...
[ "As indicated in a comment it could be a problem with your encryption mode.\nUsing 7-zip to create the zip file using AES-256 I get the same error as yours. With ZypCrypto encryption it works OK.\nPyCrust 0.9.8 - The Flakiest Python Shell\nPython 2.6.7 (r267:88850, Jun 27 2011, 13:20:48) [MSC v.1500 64 bit (AMD64)]...
[ 12, 6 ]
[]
[]
[ "python" ]
stackoverflow_0007483138_python.txt
Q: How to rename files containing Korean characters in python I want to rename more than 100 files in windows 7, all of them have korean/hangul characters. But os.rename() doesn't work with these files. WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect I'm using python 2.6.5...
How to rename files containing Korean characters in python
I want to rename more than 100 files in windows 7, all of them have korean/hangul characters. But os.rename() doesn't work with these files. WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect I'm using python 2.6.5 and os.listdir() for getting the filenames which gives me somet...
[ "Which version of Python?\nWhat is your locale?\nYou are using os.rename(src, dst) ... what does print repr(src) give you for a typical file? Use print(ascii(src)) with Python 3.x.\nHow are you getting src for each file? If it is some kind of \"get me all the files in some-folder\" gadget, have you supplied some-fo...
[ 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0007483502_python_windows.txt
Q: App Engine: 13 StringPropertys vs. 1 StringListProperty (w.r.t. indexing/storage and query performance) A bit of background first: GeoModel is a library I wrote that adds very basic geospatial indexing and querying functionality to App Engine apps. It is similar in approach to geohashing. The equivalent location h...
App Engine: 13 StringPropertys vs. 1 StringListProperty (w.r.t. indexing/storage and query performance)
A bit of background first: GeoModel is a library I wrote that adds very basic geospatial indexing and querying functionality to App Engine apps. It is similar in approach to geohashing. The equivalent location hash in GeoModel is called a 'geocell.' Currently, the GeoModel library adds 13 properties (location_geocell__...
[ "You're correct that there's no significant overhead per-index - 13n entries in one index is more or less equivalent to n entries in 13 indexes. There's a total index count limit of 100, though, so this eats up a fair chunk of your available indexes.\nThat said, using a ListProperty is definitely a far superior app...
[ 5, 1, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0001220794_google_app_engine_google_cloud_datastore_python.txt
Q: Yum : How to retrieve option value from repositories configuration using python I have instance of YumRepository class. Is there a way to retrieve the option from configuration file of a repository, that I've added manually ? Standard options are available as attributes of YumRepository instance e.g. rep.mirrorli...
Yum : How to retrieve option value from repositories configuration using python
I have instance of YumRepository class. Is there a way to retrieve the option from configuration file of a repository, that I've added manually ? Standard options are available as attributes of YumRepository instance e.g. rep.mirrorlist - is the list of mirrors Manually added option name in repositories config file is...
[ "You have two options: either hack RepoConf class before initializing yum, or use direct access to RawConfigParser object. The latter is quite simple:\nfoo = repo.cfg.get(repo.id, 'foo')\n\nFirst option is more complicated, but more universal:\nfrom yum import config, YumBase\n\nconfig.RepoConf.foo = config.Option(...
[ 0 ]
[]
[]
[ "python", "yum" ]
stackoverflow_0007483215_python_yum.txt
Q: python - remove dictionary from list if exists I am trying to remove a dictionary from a list if it already exists but it doesn't seem to be working. Can anyone see what I am doing wrong or advise me what I should be doing new_dict = {'value': 'some value', 'key': 'someKey'} if new_dict in my_list: my_list.re...
python - remove dictionary from list if exists
I am trying to remove a dictionary from a list if it already exists but it doesn't seem to be working. Can anyone see what I am doing wrong or advise me what I should be doing new_dict = {'value': 'some value', 'key': 'someKey'} if new_dict in my_list: my_list.remove(new_dict) new_list is a list of dictionaries w...
[ "If new_dict is \"definitely\" in my_list, then my_list.remove(new_dict) should do the trick (i.e., no need for the if new_dict in my_list, that just slows it down).\n", "my_list = [1,{'value':'some value', 'key' :'somekey'}, 2, {'z':'z', 'x': 'x'}]\nnew_dict = {'value':'some value', 'key' :'somekey'}\n#new_dict ...
[ 8, 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007484562_python.txt
Q: Why don't Python class method decorators receive the method as a bound method? When I create a decorator for a class method, it always receives the method as of type "function". However, when I play around with things a bit, I only get back bound methods: class Test(object): def save(self): print "Save...
Why don't Python class method decorators receive the method as a bound method?
When I create a decorator for a class method, it always receives the method as of type "function". However, when I play around with things a bit, I only get back bound methods: class Test(object): def save(self): print "Save called" def func(self): print "Func called" And then: >>> type(Test.fu...
[ "This is impossible; you'd have to use a class decorator or metaclass instead. Decorator syntax\nclass Foo(object):\n @dec\n def bar(self): pass\n\nmeans\nclass Foo(object)\n def bar(self): pass\n bar = dec(bar)\n\nwhere a class definition is processed as: execute the body, then gather the definitions a...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007484501_python.txt
Q: Run code at Pyramid shutdown Pyramid supports an ApplicationCreated event. However I can't find any ApplicationDestroyed/ApplicationShutdown event. Is it at all possible do execute a function upon shutdown. Do I have any choice other than to go further up my stack: ie. I'm using gevent inside uWSGI. It might be po...
Run code at Pyramid shutdown
Pyramid supports an ApplicationCreated event. However I can't find any ApplicationDestroyed/ApplicationShutdown event. Is it at all possible do execute a function upon shutdown. Do I have any choice other than to go further up my stack: ie. I'm using gevent inside uWSGI. It might be possible to get gevent or uWSGI to r...
[ "Pyramid does not support any shutdown event.\nHowever Python has a atexit event, that runs on interpreter shutdown\nhttp://docs.python.org/library/atexit.html\nimport atexit\n\n@atexit.register\ndef goodbye():\n print \"You are now leaving the Python sector.\"\n\n" ]
[ 2 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0007484366_pyramid_python.txt
Q: Best starting point for multiple selection in file/folder tree structure wxPython I'm looking to create a window with two panels, with a collapsible folder browser in the left panel and a list of files in the right panel that are contained in the selected folder on the left (similar to nautilus or an older windows...
Best starting point for multiple selection in file/folder tree structure wxPython
I'm looking to create a window with two panels, with a collapsible folder browser in the left panel and a list of files in the right panel that are contained in the selected folder on the left (similar to nautilus or an older windows explorer). Both the folders on the left and files on the right need a check box beside...
[ "I've got it all working now. I used CustomTreeCtrl for the tree and a list control that has multi inheritance from ListCtrl and CheckListCtrlMixin for the report like list with check boxes.\nI can share the code if anyone's interested\n", "There isn't a built-in file explorer. The GenericDirCtrl or one of the ot...
[ 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007443076_python_wxpython.txt
Q: Django nginx admin media I am currently testing moving from Apache mod_wsgi to Nginx and FastCGI I have prepared the whole installation and currently testing it on a CentOS 5.4 box that runs Django 1.1.2 In my old Apache configuration I had and alias setup for /media/ and also one called /mediaadmin/ Which is disp...
Django nginx admin media
I am currently testing moving from Apache mod_wsgi to Nginx and FastCGI I have prepared the whole installation and currently testing it on a CentOS 5.4 box that runs Django 1.1.2 In my old Apache configuration I had and alias setup for /media/ and also one called /mediaadmin/ Which is displayed below. Alias /media/ "/w...
[ "Try the following config:\nlocation /mediaadmin/ {\n alias /opt/python2.6/lib/python2.6/site-packages/django/contrib/admin/media/;\n expires max;\n add_header Cache-Control public;\n}\n\nI changed the path to /django/contrib/admin/media/ as I guess our admin media files are in this folder as normal.\nHint...
[ 4, 0 ]
[]
[]
[ "django", "django_media", "django_settings", "nginx", "python" ]
stackoverflow_0007484612_django_django_media_django_settings_nginx_python.txt
Q: Thread Safety with Template Tags After reading this document about thread safety, I am left feeling that there is something missing in the documentation, or my reading of it, or my reasoning. Let's give a simple example: class HelloWorldNode(template.Node): def render(self, context): return "O HAI LOL"...
Thread Safety with Template Tags
After reading this document about thread safety, I am left feeling that there is something missing in the documentation, or my reading of it, or my reasoning. Let's give a simple example: class HelloWorldNode(template.Node): def render(self, context): return "O HAI LOL" @register.tag(name="hello_world") de...
[ "Got it with closer reading of this.\nThe template is compiled when it is loaded. Any arguments passed into the tag function are 'static'. They are either literal strings, or they are strings which are used as identifiers to look up bound variables in the render context. \nTherefore the Node object is instantiated ...
[ 1 ]
[]
[]
[ "concurrency", "django", "django_templates", "python" ]
stackoverflow_0007483490_concurrency_django_django_templates_python.txt
Q: Urllib2 - Django - Broken Pipe I am new to Django and I am experiencing some troubles posting data to a django webapp. On the django side I have a form (backed by couchdb - couchdbkit django ext.). On the client side I post data with urllib2, in bulk (going through a list of data to post one by one) data = urllib....
Urllib2 - Django - Broken Pipe
I am new to Django and I am experiencing some troubles posting data to a django webapp. On the django side I have a form (backed by couchdb - couchdbkit django ext.). On the client side I post data with urllib2, in bulk (going through a list of data to post one by one) data = urllib.urlencode(param) req = urllib2.Reque...
[]
[]
[ "Some times I found weird errors and quick connection resets using development server (like in your log). If your application is about http, REST and webservices you should use Apache or Gunicorn so you feel a more realistic enviroment while developing.\n" ]
[ -1 ]
[ "django", "python", "urllib2" ]
stackoverflow_0007484678_django_python_urllib2.txt
Q: How to create a GUI from DTD? I have xml configs which are very complex. They are validated using dtds. I am looking for some application which reads the dtds and provides a GUI interface to write xmls. So that we don't have to write xmls by hand. If there is nothing existing already, how to start with developing ...
How to create a GUI from DTD?
I have xml configs which are very complex. They are validated using dtds. I am looking for some application which reads the dtds and provides a GUI interface to write xmls. So that we don't have to write xmls by hand. If there is nothing existing already, how to start with developing one?
[ "did you try Eclipse?\nYou can edit XML files according to the DTD.\nIf your audience is not development oriented, you can have a look to Editix XML Editor (the free version is already fully usable) or Notepad++ (a strange mix between the classic windows notepad and eclipse ;) ).\nOtherwise, if you want to write co...
[ 2, 0 ]
[]
[]
[ "dtd", "python", "user_interface", "xml" ]
stackoverflow_0007481529_dtd_python_user_interface_xml.txt
Q: using a list as values to a format string without having to list each item separately def createSVGStyleTransformationMatrix(self, transformMatrix): return "matrix(%f %f %f %f %f %f)"%(transformMatrix[0],transformMatrix[1],transformMatrix[2],transformMatrix[3],transformMatrix[4],transformMatrix[5]) As all the...
using a list as values to a format string without having to list each item separately
def createSVGStyleTransformationMatrix(self, transformMatrix): return "matrix(%f %f %f %f %f %f)"%(transformMatrix[0],transformMatrix[1],transformMatrix[2],transformMatrix[3],transformMatrix[4],transformMatrix[5]) As all the substitutions are from the same list and in sequence I was hoping there was a neater way t...
[ "Alternatively, use the str.format method (version 2.6+), which is preferred over string interpolation(%) in Python 3.x:\nreturn \"matrix(%f %f %f %f %f %f)\".format(*transformMatrix)\n\nThe * instructs the Python interpreter to unpack the arguments from a list or tuple.\n", "If len(transformMatrix) == 6, then yo...
[ 6, 5, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007485140_python.txt
Q: Matplotlib: Rotating a figure (patch) and applying colors in python I want to apply different transformations to a patch, including rotating and changing the fill color. Hier is the piece of code already inspired by Matplotlib: rotating a patch import numpy as np import matplotlib.pyplot as plt import matplotlib....
Matplotlib: Rotating a figure (patch) and applying colors in python
I want to apply different transformations to a patch, including rotating and changing the fill color. Hier is the piece of code already inspired by Matplotlib: rotating a patch import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib as mpl from matplotlib.collections i...
[ "I get this figure:\n\nwhen I comment out the +ax.transData from the transform definition:\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib as mpl\nfrom matplotlib.collections import PatchCollection\n\nfig = plt.figure()\nax = fig.add_subplot(111)\n\nmyAn...
[ 2 ]
[]
[]
[ "matplotlib", "patch", "python", "transform" ]
stackoverflow_0007467631_matplotlib_patch_python_transform.txt
Q: Relationship of metaclass's "__call__" and instance's "__init__"? Say I've got a metaclass and a class using it: class Meta(type): def __call__(cls, *args): print "Meta: __call__ with", args class ProductClass(object): __metaclass__ = Meta def __init__(self, *args): print "ProductClas...
Relationship of metaclass's "__call__" and instance's "__init__"?
Say I've got a metaclass and a class using it: class Meta(type): def __call__(cls, *args): print "Meta: __call__ with", args class ProductClass(object): __metaclass__ = Meta def __init__(self, *args): print "ProductClass: __init__ with", args p = ProductClass(1) Output as follows: Meta: ...
[ "There is a difference in OOP between extending a method and overriding it, what you just did in your metaclass Meta is called overriding because you defined your __call__ method and you didn't call the parent __call__. to have the behavior that you want you have to extend __call__ method by calling the parent meth...
[ 8, 4 ]
[]
[]
[ "metaclass", "python" ]
stackoverflow_0007485324_metaclass_python.txt
Q: Python - splitting a list into a known number of lists with a numeric name I'm working with python 2.5.1 . I have a list ('coll') with 122 values. I want to split it into 15 lists, where the first list will get the first nine values (coll[0-8]), and will be called 'coll_1', the second list will be called 'coll_2'...
Python - splitting a list into a known number of lists with a numeric name
I'm working with python 2.5.1 . I have a list ('coll') with 122 values. I want to split it into 15 lists, where the first list will get the first nine values (coll[0-8]), and will be called 'coll_1', the second list will be called 'coll_2' and have values 9-17 and so on... how do I do that? EDIT: the values in the...
[ "This is just asking for trouble. Why not just create a list of those lists?\ncolls = [coll[9*i:9*(i+1)] for i in range(15)]\n\nThis way you can access each of them without going through dynamic execution, local variables inspection, or things like that.\n", "Use locals to get a dictionary of the local variables ...
[ 3, 0, 0 ]
[]
[]
[ "list", "python", "split" ]
stackoverflow_0007485350_list_python_split.txt
Q: What is the function for each Python data structures? There are so many data structures in python. some times I thought some of them may be useless, the only needed is list. Any one can tell me what is the function of each python data structures? A: the only needed is list I assume you talk about collections, b...
What is the function for each Python data structures?
There are so many data structures in python. some times I thought some of them may be useless, the only needed is list. Any one can tell me what is the function of each python data structures?
[ "\nthe only needed is list\n\nI assume you talk about collections, because lists without atomic values to put into lists are worthless. Still, there are lots of things lists don't work well for. Of course, if you never (or so rarely elegance and performance doesn't matter) need to [better choices in brackets]...\n\...
[ 2, 1 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0007485694_data_structures_python.txt
Q: HTML form click in Objective C - like using mechanize in Python I have this code in Python that was quite simple to do with mechanize to just go into a URL and click the submit button: from mechanize import ParseResponse, urlopen, urljoin response = urlopen("http://www.somesite.com/somepage") forms = ParseRespons...
HTML form click in Objective C - like using mechanize in Python
I have this code in Python that was quite simple to do with mechanize to just go into a URL and click the submit button: from mechanize import ParseResponse, urlopen, urljoin response = urlopen("http://www.somesite.com/somepage") forms = ParseResponse(response, backwards_compat=False) form = forms[0] print urlopen(fo...
[ "Check this site: http://allseeing-i.com/ASIHTTPRequest/\nIt is not actually what you want, but you can send the POST/GET values to the form action page.\nif you have a page http://test.com/form.php with following form:\n<form name=\"login\" method=\"POST\" action=\"action.php\">\n <input name=\"username\"><br /...
[ 2 ]
[]
[]
[ "forms", "mechanize", "objective_c", "python" ]
stackoverflow_0007485837_forms_mechanize_objective_c_python.txt
Q: Tkinter import problem I suspect I've got something very simple wrong here but I can't spot what. The following code: import Tkinter as Tk Tk.tkMessageBox.showerror(message='some error') gives: AttributeError: 'module' object has no attribute 'tkMessageBox' Widgets (e.g. Button, Entry) work ok. Interactively I g...
Tkinter import problem
I suspect I've got something very simple wrong here but I can't spot what. The following code: import Tkinter as Tk Tk.tkMessageBox.showerror(message='some error') gives: AttributeError: 'module' object has no attribute 'tkMessageBox' Widgets (e.g. Button, Entry) work ok. Interactively I get the same result, and also...
[ "I think you meant this:\nimport tkMessageBox\ntkMessageBox.showerror(message='some error')\n\n" ]
[ 3 ]
[]
[]
[ "python", "tkinter", "tkmessagebox" ]
stackoverflow_0007486113_python_tkinter_tkmessagebox.txt
Q: Lazyboy AttributeError while saving to cassandra Hey Stackoverflow comm, I'm trying to write to my cassandra database but something is going wrong.. Some datas: I'm using Python 2.7 on Ubuntu (11.04), cassandra 0.8.4 and lazyboy 0.7.5. While I want to write to cassandra I get Traceback (most recent call last): Fil...
Lazyboy AttributeError while saving to cassandra
Hey Stackoverflow comm, I'm trying to write to my cassandra database but something is going wrong.. Some datas: I'm using Python 2.7 on Ubuntu (11.04), cassandra 0.8.4 and lazyboy 0.7.5. While I want to write to cassandra I get Traceback (most recent call last): File "/home/kq/protoWorkspace/indexer/src/database.py", l...
[ "Mainline lazyboy only supports Cassandra 0.6. I recommend using pycassa instead. Pycassa is maintained by DataStax and fully supports the latest Cassandra features.\nIf you must use lazyboy, there is a fork that supports Cassandra 0.7 (which is compatible with 0.8) but development does not look very active (last...
[ 2 ]
[]
[]
[ "attributeerror", "cassandra", "python" ]
stackoverflow_0007468089_attributeerror_cassandra_python.txt
Q: How can I capture the output from a shell command in Python? What I need to do is the following: in a Python script spawn, say the ls --colors=always / Linux command, and read its output. The important part of this is that I need the output to keep all the ANSI escape sequences (colors and such) to later translat...
How can I capture the output from a shell command in Python?
What I need to do is the following: in a Python script spawn, say the ls --colors=always / Linux command, and read its output. The important part of this is that I need the output to keep all the ANSI escape sequences (colors and such) to later translate these sequences into HTML. I heard that Python pty module can do...
[ "import subprocess as sub\n\nprocess = sub.Popen(\"ls --colors=always /\", stdout=sub.PIPE, stderr=sub.PIPE)\noutput, errors = process.communicate()\n\nNow all the data you want should be in output - including the ANSI escape sequences.\n" ]
[ 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0007486300_python_subprocess.txt
Q: Django inlineformsets and general noobishness I'm sorry to ask two questions about similar topics in one day but my noobishness with django has just completely taken over. Basically I have two models: class Story(models.Model): title = models.CharField(max_length=1000) text = models.CharField(max_length=50...
Django inlineformsets and general noobishness
I'm sorry to ask two questions about similar topics in one day but my noobishness with django has just completely taken over. Basically I have two models: class Story(models.Model): title = models.CharField(max_length=1000) text = models.CharField(max_length=5000) date = models.DateField(default=datetime.da...
[ "An inline formset is not required in your example. I'd use that only if I needed to submit several stories at once for a given author. \nAlso there are things that I'd change about your models.\ntitle = models.CharField(max_length=1000)\ntext = models.CharField(max_length=5000)\n\nA TextField might be more appropr...
[ 1 ]
[]
[]
[ "django", "inline_formset", "python" ]
stackoverflow_0007485825_django_inline_formset_python.txt
Q: How can I reconnect a socket after a broken pipe? The program connects to a server, and when the connection is closed by the server, if I try to reconnect it says: socket.error: [Errno 9] Bad file descriptor If I close the socket in the client and then i try to reconnect, it says: socket.error: [Errno 106] Transpo...
How can I reconnect a socket after a broken pipe?
The program connects to a server, and when the connection is closed by the server, if I try to reconnect it says: socket.error: [Errno 9] Bad file descriptor If I close the socket in the client and then i try to reconnect, it says: socket.error: [Errno 106] Transport endpoint is already connected. Is there a way to re...
[ "Assuming this is a connection oriented socket:\nNo. You have to close the old one and create a new socket, \n", "If the file descriptor is bad then you will need to release that resource and create a new socket. This will get you a new file descriptor.\nIf the connection terminated abnormally, you will have to w...
[ 14, 3 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0007486561_python_sockets.txt
Q: Test for substrings with diacritics in strings I'm testing in Python if certain string contains something as follows if substr in str: do_something() The problem is when substr contains letter with diacritics and other non usual characters. How would you recommend to do tests with such letters? thank you A: I...
Test for substrings with diacritics in strings
I'm testing in Python if certain string contains something as follows if substr in str: do_something() The problem is when substr contains letter with diacritics and other non usual characters. How would you recommend to do tests with such letters? thank you
[ "I do not know of any problems specific to diacritics in Python. The following works for me:\n u\"ł\" in u\"źdźbło\"\n >>> True\n\nEdit:\nu\"ł\" in u\"źdźblo\"\n>>> False \n\nThe matching is exact. If diacritics-insensitive matching is what you want, specify this in your question and see Fredrik's answer.\nEdit2: Y...
[ 2, 0 ]
[]
[]
[ "diacritics", "python", "string", "substring" ]
stackoverflow_0007486552_diacritics_python_string_substring.txt
Q: IntegrityError at /admin/app/price_list/add/ (1048, "Column 'business_id_id' cannot be null") i am working with django to create three tables that define a store, it's item list and a price list. In the 'price_list' model i created Foreign key links to the other two tables that i later use to create a compisite pr...
IntegrityError at /admin/app/price_list/add/ (1048, "Column 'business_id_id' cannot be null")
i am working with django to create three tables that define a store, it's item list and a price list. In the 'price_list' model i created Foreign key links to the other two tables that i later use to create a compisite primary key using the unique together option. It all validates without an error but when i try to cha...
[ "I suspect you're missing a capital B in the foreign key definition for \"businessID\" on Price_List.\nI'm not sure but I think the whole \"related_name='businessID'\" argument is unnecessary since you're wanting to create a foreign key to the primary key of the Businesses table.\nTry it - it might work!\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007485545_django_python.txt