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:
Inserting manytomany field into db
I'd like to insert individual squawks into the Room object so I can insert into the database. How do I do this?
I tried, Room(squawk=squawk object), but this doesn't appear to work.
class Squawk(models.Model):
username = models.ForeignKey(User)
message = models.CharField(... | Inserting manytomany field into db | I'd like to insert individual squawks into the Room object so I can insert into the database. How do I do this?
I tried, Room(squawk=squawk object), but this doesn't appear to work.
class Squawk(models.Model):
username = models.ForeignKey(User)
message = models.CharField(max_length=160)
time = models.DateTi... | [
"from django.shortcuts import get_object_or_404\n\n# get Room instance by id or raise 404 page if not found\nroom = get_object_or_404(Room,pk = id)\n# add squawk to many-to-many relation\nroom.squawks.add(squawk_object)\n\nhttps://docs.djangoproject.com/en/dev/ref/models/relations/\n"
] | [
2
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0007864536_database_django_python.txt |
Q:
Formbuild with Pylons?
Is using formbuild with pylons, when you have pretty customized needs, actually easier than manually creating your own form html?
A:
I really prefer plain html, but it's super easy
populate a select with a syntax like this:
def foo(self):
c.countries = Model.get(Country)....
return R... | Formbuild with Pylons? | Is using formbuild with pylons, when you have pretty customized needs, actually easier than manually creating your own form html?
| [
"I really prefer plain html, but it's super easy \npopulate a select with a syntax like this: \ndef foo(self):\n c.countries = Model.get(Country)....\nreturn Render('foo.html')\n\nTemplate:\n${h.field(\n \"Country:\",\n h.select(\n \"country\",\n id='country',\n options = c.countries,\n selecte... | [
1,
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0005558388_pylons_python.txt |
Q:
How to send binary post data via HTTP?
I already have binary data read from a file. Most of the examples I see online link directly to the file, and upload the whole file. I am looking how to upload the binary data that I already have from another source via HTTP POST in python.
A:
Alternatively:
req = urllib2.R... | How to send binary post data via HTTP? | I already have binary data read from a file. Most of the examples I see online link directly to the file, and upload the whole file. I am looking how to upload the binary data that I already have from another source via HTTP POST in python.
| [
"Alternatively:\nreq = urllib2.Request(\"http://example.com\", data, {'Content-Type': 'application/octet-stream'})\nurllib2.urlopen(req)\n\nThat also shows how you can specify the Content-Type of the data.\n",
"I'm not sure what online examples you're looking at, but urllib2.urlopen takes the data to post as a ch... | [
7,
0
] | [] | [] | [
"binary",
"http",
"post",
"python"
] | stackoverflow_0007864803_binary_http_post_python.txt |
Q:
Find expression in python
String example: 'file_name.c: 120' or 'file_name.m: 312'
Target: find exactly '.c:' or '.m:' using regular expression.
Since it's confusing issue, I would to get a good tutorial for regular expression if someone knows.
Ron.
A:
import re
string = 'file_name.c: 120'
find = re.findall("(\.... | Find expression in python | String example: 'file_name.c: 120' or 'file_name.m: 312'
Target: find exactly '.c:' or '.m:' using regular expression.
Since it's confusing issue, I would to get a good tutorial for regular expression if someone knows.
Ron.
| [
"import re\nstring = 'file_name.c: 120'\nfind = re.findall(\"(\\.[cm])*\", string)\nfind = filter(None, find)\nprint find\n\nI prefer using findall as I am guessing you may be looking for more than one example.\n",
"There's an introduction to regular expressions (in Python) here: http://docs.python.org/howto/rege... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007864877_python_regex.txt |
Q:
Correct python re regex
I tried to make regex to validate phone number in format +38(0XX)XXX-XX-XX or 0XX-XXX-XX-XX. My regex is: '^(\+38)*(\(*0\d{2}\)*)[-|\s](\d{3})[-|\s]((\d{2})-|\s)+$'. And it's not matched any way. I reread re syntax a couple of times, can't get how to make it right.
A:
UPDATE: Making the r... | Correct python re regex | I tried to make regex to validate phone number in format +38(0XX)XXX-XX-XX or 0XX-XXX-XX-XX. My regex is: '^(\+38)*(\(*0\d{2}\)*)[-|\s](\d{3})[-|\s]((\d{2})-|\s)+$'. And it's not matched any way. I reread re syntax a couple of times, can't get how to make it right.
| [
"UPDATE: Making the regex to match strictly as per the comments.\nThis regex should work according to your requirements\n^((\\+38)?\\(0\\d{2}\\)|0\\d{2})[-\\s]\\d{3}([-\\s]\\d{2}){2}$\n\nThis matches +38(022)-333-33-44, (022)-333-33-44 and 022-333-33-44\n",
"This is an another option. It looks for exact formats t... | [
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007864993_python_regex.txt |
Q:
python os.path.join on windows ignores first path element?
Consider the following:
>>> from django.conf import settings
>>> import os
>>> settings.VIRTUAL_ENV
'C:/Users/Marcin/Documents/oneclickcos'
>>> settings.EXTRA_BASE
'/oneclickcos/'
>>> os.path.join(settings.VIRTUAL_ENV,settings.EXTRA_BASE)
'/oneclickcos/'
... | python os.path.join on windows ignores first path element? | Consider the following:
>>> from django.conf import settings
>>> import os
>>> settings.VIRTUAL_ENV
'C:/Users/Marcin/Documents/oneclickcos'
>>> settings.EXTRA_BASE
'/oneclickcos/'
>>> os.path.join(settings.VIRTUAL_ENV,settings.EXTRA_BASE)
'/oneclickcos/'
As you can imagine, I neither expect nor want the concatenation ... | [
"That's pretty much how os.path.join is defined (quoting the docs):\n\nIf any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away\n\nAnd I'd say it's usually a good thing, as it avoids creating invalid paths. If you want to avoid... | [
8,
4
] | [] | [] | [
"operating_system",
"path",
"python",
"windows"
] | stackoverflow_0007865293_operating_system_path_python_windows.txt |
Q:
"scripting" vim using python with greater granularity
I'm attempting to write a python script that can automate vim, but the python vim interface doesn't give me enough power to do everything I need. I want to communicate with vim as if my script were a tty (able to issue "visual mode" instructions etc). As far a... | "scripting" vim using python with greater granularity | I'm attempting to write a python script that can automate vim, but the python vim interface doesn't give me enough power to do everything I need. I want to communicate with vim as if my script were a tty (able to issue "visual mode" instructions etc). As far as vim is concerned, my script is a human running xterm (or ... | [
"All non-vimscript interfaces are cursed: the only way to communicate with vim (unless you want to edit/get contents of a buffer which is available using buffer object) are execute (vim.command(string) in python) and eval (vim.eval(string) in python), both requiring serializing arguments. If you want to just start ... | [
1
] | [] | [] | [
"linux",
"python",
"scripting",
"tty",
"vim"
] | stackoverflow_0007839551_linux_python_scripting_tty_vim.txt |
Q:
Instantiating class retains references
In Python, I instantiate a class twice and store them into 2 different variables. Why does the second object contain a copy of the first object? I know it's a copy because I change the values in one object and it does not change the other. Example:
I have the following class:... | Instantiating class retains references | In Python, I instantiate a class twice and store them into 2 different variables. Why does the second object contain a copy of the first object? I know it's a copy because I change the values in one object and it does not change the other. Example:
I have the following class:
class HistoricalData:
dataPoints = {}
... | [
"You've declared a class variable, not an instance variable.\nClass variables are shared among all instances of the class. This means that when you update one HistoricalData object, you update them all.\nInstance variables are local to each instance of a class. These are typically initialised in the __init__() spec... | [
10
] | [] | [] | [
"class",
"object",
"python",
"reference"
] | stackoverflow_0007865451_class_object_python_reference.txt |
Q:
Concatenate httpresponse objects django
I am developing a website with django and want to keep a common template for header and footer. The contents of the header and footer vary with respect to the user logged in. So is there a way where i could use:
header=render_to_response('header.html',{....})
footer=... | Concatenate httpresponse objects django | I am developing a website with django and want to keep a common template for header and footer. The contents of the header and footer vary with respect to the user logged in. So is there a way where i could use:
header=render_to_response('header.html',{....})
footer=render_to_response('footer.html',{....})
... | [
"Harsh, concatenating HttpResponse objects is not the way to do it. Django's (and I believe, reasonable) approach recommends using templates including and inheritance. Please, take a look at {% block %}, {% include %} and {% extend %} template tags here. \nIn your case the way to implement template inheritance look... | [
4,
1
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0007865457_django_django_templates_django_views_python.txt |
Q:
Extracting content BETWEEN a regex python?
Is there a simple method to pull content between a regex? Assume I have the following sample text
SOME TEXT [SOME MORE TEXT] value="ssss" SOME MORE TEXT
My regex is:
compiledRegex = re.compile('\[.*\] value=("|\').*("|\')')
This will obviously return the entire [SOME... | Extracting content BETWEEN a regex python? | Is there a simple method to pull content between a regex? Assume I have the following sample text
SOME TEXT [SOME MORE TEXT] value="ssss" SOME MORE TEXT
My regex is:
compiledRegex = re.compile('\[.*\] value=("|\').*("|\')')
This will obviously return the entire [SOME MORE TEXT] value="ssss", however I only want ss... | [
"This is what capturing groups are designed to do.\ncompiledRegex = re.compile('\\[.*\\] value=(?:\"|\\')(.*)(?:\"|\\')') \nmatches = compiledRegex.match(sampleText)\ncapturedGroup = matches.group(1) # grab contents of first group\n\nThe ?: inside the old groups (the parentheses) means that the group is now a non-c... | [
2,
0
] | [] | [] | [
"matching",
"parsing",
"python",
"regex",
"text_extraction"
] | stackoverflow_0007864180_matching_parsing_python_regex_text_extraction.txt |
Q:
Compiling an IronPython WPF project to exe: Missing dlls
I want to compile my IronPython WPF based app into a .exe file. I looked up the net for solutions and found this on SO:
Compiling an IronPython WPF project to exe.
I found this modified pyc.py file better than the original as I do not have to pass the names ... | Compiling an IronPython WPF project to exe: Missing dlls | I want to compile my IronPython WPF based app into a .exe file. I looked up the net for solutions and found this on SO:
Compiling an IronPython WPF project to exe.
I found this modified pyc.py file better than the original as I do not have to pass the names of all the files in the project to pyc at the command line. Wh... | [
"You should add\nimport clr\nclr.AddReference('IronPython.Wpf')\n\nAnd make sure you put IronPython.Wpf.dll, from the IronPython's install directory in the same directory as your main script.\nI'm still getting an Exception related with STA Threads, but that's for other question.\nEdit: Look at this for the STA err... | [
4
] | [] | [] | [
"ironpython",
"python",
"visual_studio_2010",
"wpf"
] | stackoverflow_0007214222_ironpython_python_visual_studio_2010_wpf.txt |
Q:
GUI forms editor
I recently installed PTVS as I come from C# and I am used to Visual Studio.
I though that PTVS had a GUI creation support like Windows Forms in C#, I am pretty disappointed as I need to program several Windows applications, and I like python.
Is there any plugin to add this functionality to PTVS? ... | GUI forms editor | I recently installed PTVS as I come from C# and I am used to Visual Studio.
I though that PTVS had a GUI creation support like Windows Forms in C#, I am pretty disappointed as I need to program several Windows applications, and I like python.
Is there any plugin to add this functionality to PTVS? do they plan to progra... | [
"From what I'm reading here and here PTVS has WPF support if you use IronPython. Here's a page that may be helpful too http://wiki.python.org/moin/GuiProgramming. Personally I'd use Qt with PyQt or PySide, you can use QtDesigner to make your forms.\n",
"I always thought #develop was a good IDE with a good forms e... | [
5,
1
] | [] | [] | [
"ide",
"ptvs",
"python",
"user_interface",
"visual_studio"
] | stackoverflow_0007865376_ide_ptvs_python_user_interface_visual_studio.txt |
Q:
Is there a Django app that can give me easy friend importing AND invite from Facebook, Twitter, and Gmail?
Super easy django app that just lets people click "Facebook", and then invite AND import their friends
A:
Take a look at the pinax (http://pinaxproject.com/). They have a lot of reusable apps and one of tho... | Is there a Django app that can give me easy friend importing AND invite from Facebook, Twitter, and Gmail? | Super easy django app that just lets people click "Facebook", and then invite AND import their friends
| [
"Take a look at the pinax (http://pinaxproject.com/). They have a lot of reusable apps and one of those provide mechanism for inviting friends from openid based sites (i.e. facebook)\n"
] | [
1
] | [] | [] | [
"django",
"facebook",
"gmail",
"python"
] | stackoverflow_0004475930_django_facebook_gmail_python.txt |
Q:
Python 2.6 regular expression mechanisms?
I am learning regular expression and I would like to check the mechanisms that python is using.
I have the regex:
s = re.findall(ur"\d+\.?\d+", "123,45.567 78").
First I thought that the result was going to be only 45.567
When I run it, I got all the numbers including the... | Python 2.6 regular expression mechanisms? | I am learning regular expression and I would like to check the mechanisms that python is using.
I have the regex:
s = re.findall(ur"\d+\.?\d+", "123,45.567 78").
First I thought that the result was going to be only 45.567
When I run it, I got all the numbers including the decimal (["123", "45.567", "78"]) but it is no... | [
"\\d+\\.?\\d+ will always also match \\d+\\d+ since the . is optional (maybe you now see why it matches all). So it can backtrack as much as the constraints allow.\n",
"From the documentation of findall (emphasis mine):\n\nReturn all non-overlapping matches of pattern in string, as a list of strings.\n\nIt seems ... | [
4,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007865958_python_regex.txt |
Q:
Scrapy: use a different .cfg file
By default Scrapy uses scrapy.cfg in the projects root.
Is there a way to tell it to use a different .cfg file?
A:
No this is the default behavior.See this source.
A:
As v01d said there's no way to explicitly tell scrapy to use a scrapy.cfg wherever you want it to be in the... | Scrapy: use a different .cfg file | By default Scrapy uses scrapy.cfg in the projects root.
Is there a way to tell it to use a different .cfg file?
| [
"No this is the default behavior.See this source. \n",
"As v01d said there's no way to explicitly tell scrapy to use a scrapy.cfg wherever you want it to be in the directory tree but if you look at the implementation of closest_scrapy_cfg - https://github.com/scrapy/scrapy/blob/master/scrapy/utils/conf.py#L24 - y... | [
0,
0
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0007765388_python_scrapy.txt |
Q:
Python 2.7.2 global variables + tkinter
I'm having some problems with the global variables:
#Dev by Mkee
import Tkinter as tk
import sys, random
globvar = 0
class Shuffle(object):
def __init__(self,master=None):
self.master=master
self.text=tk.Label(master, text="Type in something:")
se... | Python 2.7.2 global variables + tkinter | I'm having some problems with the global variables:
#Dev by Mkee
import Tkinter as tk
import sys, random
globvar = 0
class Shuffle(object):
def __init__(self,master=None):
self.master=master
self.text=tk.Label(master, text="Type in something:")
self.box=tk.Entry(master)
self.buttn = ... | [
"\nTo make the Label update, set textvariable=self.globvar, where\nself.globvar = tk.StringVar(). The Label text is updated by calling self.globvar.set.\nChange command=self.calc() to command=self.calc (without\nparentheses). With parentheses, self.calc() is called at the time\nself.buttn is defined. And command ge... | [
4
] | [] | [] | [
"global_variables",
"python",
"python_2.7",
"tkinter"
] | stackoverflow_0007865682_global_variables_python_python_2.7_tkinter.txt |
Q:
xml2array in python
the file.xml contains the following data structure:
<table>
<row>
<x>10</x>
<t>10:00</t>
</row>
<row>
<x>20</x>
<t>10:05</t>
</row>
</table>
I have hundred of x,t pairs. I need to plot x vs. t.
I would be thankful if you can help me to solve the problem with python and matplotlib.... | xml2array in python | the file.xml contains the following data structure:
<table>
<row>
<x>10</x>
<t>10:00</t>
</row>
<row>
<x>20</x>
<t>10:05</t>
</row>
</table>
I have hundred of x,t pairs. I need to plot x vs. t.
I would be thankful if you can help me to solve the problem with python and matplotlib.
| [
"import lxml.etree as ET\nimport matplotlib.pyplot as plt\n\ntext='''\\\n<table>\n <row>\n <x>10</x>\n <t>10:00</t>\n</row>\n<row>\n <x>20</x>\n <t>10:05</t>\n</row>\n</table>\n'''\n\ndef convert_t(text):\n a,b=map(float,t.split(':'))\n return a+b/60.0\n\ndoc=ET.fromstring(text)\nx=[float(x) for x in ... | [
2
] | [] | [] | [
"lxml",
"matplotlib",
"python"
] | stackoverflow_0007866337_lxml_matplotlib_python.txt |
Q:
Performance of scipy.weave.inline
I am a Python novice who is trying to learn a bit about this fantastic programming language. I have tried using scipy.weave.inline to speed up some computation. Just to learn a bit, I tried to implement a matrix multiplication using scipy.weave.inline. I have not included any erro... | Performance of scipy.weave.inline | I am a Python novice who is trying to learn a bit about this fantastic programming language. I have tried using scipy.weave.inline to speed up some computation. Just to learn a bit, I tried to implement a matrix multiplication using scipy.weave.inline. I have not included any error handling - just trying it out to bett... | [
"You implemented a naive matrix multiplication algorithm, which scipy.weave compiles to fast machine code.\nHowever, there are non-obvious, more CPU cache efficient algorithms for matrix multiplication (which usually split the matrix into blocks and deal with those), and additional speed can be gained with CPU-spec... | [
7
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0007861930_performance_python.txt |
Q:
python code understanding
I have following code
def compare_and_swap(x, a, b):
if x[a] > x[b]:
x[a], x[b] = x[b], x[a]
def oddeven_merge(x, lo, hi, r):
step = r * 2
if step < hi - lo:
oddeven_merge(x, lo, hi, step)
oddeven_merge(x, lo + r, hi, step)
for i in range(lo + ... | python code understanding | I have following code
def compare_and_swap(x, a, b):
if x[a] > x[b]:
x[a], x[b] = x[b], x[a]
def oddeven_merge(x, lo, hi, r):
step = r * 2
if step < hi - lo:
oddeven_merge(x, lo, hi, step)
oddeven_merge(x, lo + r, hi, step)
for i in range(lo + r, hi - r, step):
c... | [
"This equivalent to \nfor(int i=lo+r;i<(hi-r);i+=step)\n\nin C (or C++, Java, C#, etc.)\n(Note: this will only work if step is positive. If step is negative - i.e. lo+r>hi-r, you need change the check to i>(hi-r))\nWhat it does is start a counter at lo+r, move it by step units until the counter equals or steps past... | [
3,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007866081_python.txt |
Q:
Invite Facebook Friends using Django/Python
I need to create an input that looks uses autoSuggest to lookup my friends list and send their 'facebook id' to a Django/Python script. I've completes this without a hitch.
Eg: http://f.cl.ly/items/1J0F3i062n1M0a131T3c/Screen%20Shot%202011-10-20%20at%205.34.35%20PM.png
B... | Invite Facebook Friends using Django/Python | I need to create an input that looks uses autoSuggest to lookup my friends list and send their 'facebook id' to a Django/Python script. I've completes this without a hitch.
Eg: http://f.cl.ly/items/1J0F3i062n1M0a131T3c/Screen%20Shot%202011-10-20%20at%205.34.35%20PM.png
BUT, what to do with this 'facebook id' array on t... | [
"The common way to achieve this kind of behaviour is using the Requests Dialog, easy, client side javascript implementation. You can read about it in the official facebook docs:\nhttp://developers.facebook.com/docs/reference/dialogs/requests/\nIf you want you can call a callback js function after dialog completes ... | [
1
] | [] | [] | [
"django",
"django_facebook",
"facebook",
"facebook_graph_api",
"python"
] | stackoverflow_0007832021_django_django_facebook_facebook_facebook_graph_api_python.txt |
Q:
Parse a unicode string in python to a dictionary
I'm sure that this is both extremely easy and a combination of other questions on SO but I can't find the right answer.
I have a unicode string: u"word1 word2 word3..." It will always be in the same format. I want to parse it into a dictionary that will always have ... | Parse a unicode string in python to a dictionary | I'm sure that this is both extremely easy and a combination of other questions on SO but I can't find the right answer.
I have a unicode string: u"word1 word2 word3..." It will always be in the same format. I want to parse it into a dictionary that will always have the same keys:
"key1:word1 key2:word2 key3:word3..."
H... | [
"Try this:\nkeys = ['key1', 'key2', 'key3']\nwords = u'word1 word2 word3'\nvals = words.split()\n\nd = dict(zip(keys, vals))\n\nAnd then, if you want to retrieve the key/value pairs in a string like the one in your example:\n' '.join(sorted(k + ':' + v for k,v in d.items()))\n\n"
] | [
2
] | [] | [] | [
"dictionary",
"python",
"unicode"
] | stackoverflow_0007866785_dictionary_python_unicode.txt |
Q:
Python split() without removing the delimiter
This code almost does what I need it to..
for line in all_lines:
s = line.split('>')
Except it removes all the '>' delimiters.
So,
<html><head>
Turns into
['<html','<head']
Is there a way to use the split() method but keep the delimiter, instead of removing it?
... | Python split() without removing the delimiter | This code almost does what I need it to..
for line in all_lines:
s = line.split('>')
Except it removes all the '>' delimiters.
So,
<html><head>
Turns into
['<html','<head']
Is there a way to use the split() method but keep the delimiter, instead of removing it?
With these results..
['<html>','<head>']
| [
"d = \">\"\nfor line in all_lines:\n s = [e+d for e in line.split(d) if e]\n\n",
"If you are parsing HTML with splits, you are most likely doing it wrong, except if you are writing a one-shot script aimed at a fixed and secure content file. If it is supposed to work on any HTML input, how will you handle some... | [
76,
39,
21,
1
] | [] | [] | [
"delimiter",
"python",
"split"
] | stackoverflow_0007866128_delimiter_python_split.txt |
Q:
Storing VT100 escape codes in an XML file
I'm writing a Python program that logs terminal interaction (similar to the script program), and I'd like to store the log in XML format.
The problem is that the terminal interaction includes VT100 escape codes. Python doesn't complain if I write the data to a file as UTF... | Storing VT100 escape codes in an XML file | I'm writing a Python program that logs terminal interaction (similar to the script program), and I'd like to store the log in XML format.
The problem is that the terminal interaction includes VT100 escape codes. Python doesn't complain if I write the data to a file as UTF-8 encoded, e.g.:
...
pid, fd = pty.fork()
if p... | [
"Your problem is not that the control codes aren't proper UTF-8, they are, it's just ASCII ESC and friends are not proper XML characters, even inside a CDATA section.\nThe only valid XML characters in XML 1.0 which have values less than U+0020 are U+0009 (tab), U+000A (newline) amd U+000D (carriage return). If you ... | [
2,
1
] | [
"Did you try put your data inside a CDATA section ? this should prevent the parser to try to read the content of the tag.\nhttp://en.wikipedia.org/wiki/CDATA\n"
] | [
-1
] | [
"python",
"tty",
"unicode",
"vt100",
"xml"
] | stackoverflow_0007859378_python_tty_unicode_vt100_xml.txt |
Q:
python: container for card catalog - sqlite, dict, other?
I'm developing a card catalog type application and Python and am trying to decide how to store the data. Not a web app. I don't expect a large app or a massive amount of data.
One alternative is a pickled dictionary. For example {id1: {author1, title1}, i... | python: container for card catalog - sqlite, dict, other? | I'm developing a card catalog type application and Python and am trying to decide how to store the data. Not a web app. I don't expect a large app or a massive amount of data.
One alternative is a pickled dictionary. For example {id1: {author1, title1}, id2: {author2, title2}} (reality would be a bit more complex). ... | [
"Sqlite3 is a rock solid choice.\nIf you only need a key/value store, the shelve module offers and easy-to-use dictionary like API.\n"
] | [
1
] | [] | [] | [
"database",
"python",
"shelve",
"sqlite"
] | stackoverflow_0007866889_database_python_shelve_sqlite.txt |
Q:
List standard Python library moduled and appropriate submodules?
Is there, hopefully, an easy way to list Python standard library modules and class submodules?
I read this question but it's not working for me, not because it lists all available modules (can be tweaked to avoid, I know) but it does not include subm... | List standard Python library moduled and appropriate submodules? | Is there, hopefully, an easy way to list Python standard library modules and class submodules?
I read this question but it's not working for me, not because it lists all available modules (can be tweaked to avoid, I know) but it does not include submodules. Like for example it lists module urllib but without submodule ... | [
"To drill into submodules use the inspect and pyclbr modules. Those are the same support tools used by pydoc, help, and sphinx.\nGood luck with your tooltip maker.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007866538_python.txt |
Q:
How should i understand built-in function bin(x)?
bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
So if i want to get bin from Cadilac what should i do with this string an... | How should i understand built-in function bin(x)? |
bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
So if i want to get bin from Cadilac what should i do with this string and __index__() method? How to syntaticly proper compose... | [
"This should get you started:\n>>> for c in \"Cadillac\":\n... n = ord(c) # convert the character to a number\n... print '{0:08b}'.format(n) # show the number with 8 binary digits\n... \n01000011\n01100001\n01100100\n01101001\n01101100\n01101100\n01100001\n01100011\n\n",
"car = \"Cadill... | [
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0007866384_python.txt |
Q:
Python - inverting a bitmap image without using ImgOps 'invert' or other built-in functions
I'd like to know how to invert an image in Python using PIL except that i can't use 'invert' or 'convert' or any other 'easy' ways of doing it.
any help would be appreciated. thanks :)
A:
take a look at im.load()
pix = i... | Python - inverting a bitmap image without using ImgOps 'invert' or other built-in functions | I'd like to know how to invert an image in Python using PIL except that i can't use 'invert' or 'convert' or any other 'easy' ways of doing it.
any help would be appreciated. thanks :)
| [
"take a look at im.load()\npix = im.load()\nprint pix[x, y]\npix[x, y] = value\n\n",
"Invert an RGB tuple like this:\nred, green, blue = pixel\nred = 256 - red\ngreen = 256 - green\nblue = 256 - blue\npixel = red, green, blue\n\n"
] | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007864381_python.txt |
Q:
WSGI - Set content type to JSON
I'm crazy green to WSGI on Google App Engine (GAE).
How do I set the content type to JSON? This is what I have so far:
class Instructions(webapp.RequestHandler):
def get(self):
response = {}
response["message"] = "This is an instruction object"
self.res... | WSGI - Set content type to JSON | I'm crazy green to WSGI on Google App Engine (GAE).
How do I set the content type to JSON? This is what I have so far:
class Instructions(webapp.RequestHandler):
def get(self):
response = {}
response["message"] = "This is an instruction object"
self.response.out.write(json.dumps(response))... | [
"You can set the proper Content-Type with something like this:\nself.response.headers['Content-Type'] = \"application/json\"\nself.response.out.write(json.dumps(response))\n\nWSGI is not a framework but a specification; the framework you are currently using is the webapp framework.\nThere's nothing sophisticated an... | [
14,
2,
1
] | [] | [] | [
"google_app_engine",
"python",
"rest",
"wsgi"
] | stackoverflow_0005773619_google_app_engine_python_rest_wsgi.txt |
Q:
python. If a program stops, a new instance must start
Windows 7 64bit, python26
I run a minecraft server, but sometimes the program is stoped for different reasons. I would like a new instance to start when that happens.
The following code works for notepad.exe, but keeps spawning new minecraft_servers even tho th... | python. If a program stops, a new instance must start | Windows 7 64bit, python26
I run a minecraft server, but sometimes the program is stoped for different reasons. I would like a new instance to start when that happens.
The following code works for notepad.exe, but keeps spawning new minecraft_servers even tho the previous one didnt' stop. Why? And what should I do?
I'm ... | [
"It is unclear why threading is involved in the process restarter.\nDoes this work for you:\nwhile True:\n proc = subprocess.Popen(\"C:\\\\Users\\\\Bo\\\\AppData\\\\Roaming\\\\.minecraf\\\\Minecraft_Server.exe\")\n proc.wait()\n print 'Minecraft_Server process terminated. Restarting now'\n\nSuggestions:\n... | [
3
] | [] | [] | [
"execute",
"multithreading",
"process",
"python",
"wait"
] | stackoverflow_0007866816_execute_multithreading_process_python_wait.txt |
Q:
ImportError: No module named _multiprocessing
I programmed a python application (used wxPython; py2exe; python 2.6).
Now my code is using the multiprocessing module. It works! (IDE)
When I try to build this code I got no problems.
But when I execute this built .exe file I got this error:
Traceback (most recent ca... | ImportError: No module named _multiprocessing | I programmed a python application (used wxPython; py2exe; python 2.6).
Now my code is using the multiprocessing module. It works! (IDE)
When I try to build this code I got no problems.
But when I execute this built .exe file I got this error:
Traceback (most recent call last): File "myprogram.py", line 800, in
... | [
"I think you need to add the line freeze_support() after your main code.... Here is the main link to the docs multiprocessing freeze support\nAlso these 2 questions mention the same thing stackoverflow ques and multiprocessing and pyqt\nDo tell if it works for you...........\n"
] | [
1
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0007866312_py2exe_python.txt |
Q:
Locked sqlite database when debugging
Often happens that I debug a python application connecting to sqlite database and during debugging the connection is not closed.
When I debug it next time, the database is locked, so I can't connect to it so I have to edit source code, close connection before the place where e... | Locked sqlite database when debugging | Often happens that I debug a python application connecting to sqlite database and during debugging the connection is not closed.
When I debug it next time, the database is locked, so I can't connect to it so I have to edit source code, close connection before the place where exception database is locked occur, comment ... | [
"The database is locked to other connections when a transaction is in progress. You can find documentation about SQLite locking here.\nHowever you can still access the database via the connection that has locked it. You can stick that in a global variable or something similar while debugging.\n"
] | [
1
] | [] | [] | [
"locking",
"python",
"sqlite"
] | stackoverflow_0007827728_locking_python_sqlite.txt |
Q:
Split numpy array object into two different size vectors using C
I have
X as input --- this is dtype object
this is of following structure
x=[[1,2,3,4...n elements],[1 element],[1,2,...m elements],[1 element]]
To mimic the input...
>>> from numpy import *
>>> x=array([array([1,2,3,4,5]),array([1]),array([1,2,3,4,5... | Split numpy array object into two different size vectors using C | I have
X as input --- this is dtype object
this is of following structure
x=[[1,2,3,4...n elements],[1 element],[1,2,...m elements],[1 element]]
To mimic the input...
>>> from numpy import *
>>> x=array([array([1,2,3,4,5]),array([1]),array([1,2,3,4,5,6,7,8]),array([1])],dtype=object)
>>> x
array([[1 2 3 4 5], [1], [1 2... | [
"Originally you had an array of four arrays. The following line extracts it into four array variables:\na,b,c,d=x[0],x[1],x[2],x[3]\nIf you need native Python objects instead of numpy arrays, use list comprehension:\nobjs = [y for y in a]\n"
] | [
1
] | [] | [] | [
"c",
"numpy",
"python",
"python_c_api"
] | stackoverflow_0006902740_c_numpy_python_python_c_api.txt |
Q:
extracting numbers in a string
How to extract all the numbers in a string?
For example, consider a string "66,55,66,57". I want to extract each numbers into separate variables and perform integer arithmetic.
A:
You can use a list comprehension along with str.split to break up the string and convert it to integer... | extracting numbers in a string | How to extract all the numbers in a string?
For example, consider a string "66,55,66,57". I want to extract each numbers into separate variables and perform integer arithmetic.
| [
"You can use a list comprehension along with str.split to break up the string and convert it to integers:\n>>> string = \"66,55,66,57\"\n>>> numbers = [int(x) for x in string.split(\",\")]\n\n>>> print numbers\n[66, 55, 66, 57]\n\nThen you can do whatever you want with that list. For example:\n>>> sum(numbers)\n24... | [
9,
4,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007867457_python_string.txt |
Q:
Need help in getting my logic right , python
So Here is my problem.
I want to check if a site has had any recent comments done on it.
Usually wordpress sites have their comment feed in this pattern www.site.com/comments/feed
Now the problem is each wp site can be in many formats of rss or atom with different field... | Need help in getting my logic right , python | So Here is my problem.
I want to check if a site has had any recent comments done on it.
Usually wordpress sites have their comment feed in this pattern www.site.com/comments/feed
Now the problem is each wp site can be in many formats of rss or atom with different fields.
I am currently working on the logic on how I ca... | [
"Very simple solution I can think of is md5 digest.\n\nOpen an URL using urllib and fetch the lines and convert to string.\nCreate a md5 digest of the values and store it in a file.\nNext time do the same and check the result from the file.\nYou need to use urllib and hashlib modules.\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007867977_python.txt |
Q:
Difference between ctypes' use_errno parameter to shared library classes and function prototypes?
The shared library classes CDLL, OleDLL, WinDLL each take the use_errno parameter. So do the function prototypes, CFUNCTYPE, WINFUNCTYPE. When and to which group do I pass use_errno=True and why?
A:
Here's the bug t... | Difference between ctypes' use_errno parameter to shared library classes and function prototypes? | The shared library classes CDLL, OleDLL, WinDLL each take the use_errno parameter. So do the function prototypes, CFUNCTYPE, WINFUNCTYPE. When and to which group do I pass use_errno=True and why?
| [
"Here's the bug tracker for it's inclusion:\n\nThis patch adds new calling conventions to ctypes foreign functions by\n passing 'errno=True' or 'GetLastError=True' to the CDLL or WinDLL\n constructor.\nIf CDLL(..., errno=True) or WinDLL(..., errno=True) is used, the\n function objects available in the CDLL or Wi... | [
0
] | [] | [] | [
"ctypes",
"errno",
"function_prototypes",
"python",
"shared_libraries"
] | stackoverflow_0007831077_ctypes_errno_function_prototypes_python_shared_libraries.txt |
Q:
Minimizing python function that has numpy array as argument
I'm new to python, and I have the following problem: I am trying to minimize a python function that has a numpy array as one of its arguments. When I use scipy.optimize.fmin, it turns my array into a list (which results in the function failing to evaluate... | Minimizing python function that has numpy array as argument | I'm new to python, and I have the following problem: I am trying to minimize a python function that has a numpy array as one of its arguments. When I use scipy.optimize.fmin, it turns my array into a list (which results in the function failing to evaluate). Is there an optimization function that does accept numpy array... | [
"Here is an example using optimize.fmin which comes from the scipy tutorial:\nimport scipy.optimize as optimize\ndef rosen(x):\n \"\"\"The Rosenbrock function\"\"\"\n return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)\nx0 = [1.3, 0.7, 0.8, 1.9, 1.2]\nxopt = optimize.fmin(rosen, x0, xtol=1e-8, disp=T... | [
4
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0007868254_numpy_python_scipy.txt |
Q:
python: re.sub's replace function doesn't accept extra arguments - how to avoid global variable?
I'm trying to increment all timestamps (of the form 'HH:MM:SS') in a text file by a number of seconds specified by a command-line parameter to my program.
Here's a simplified version of my effort so far:
import re
from... | python: re.sub's replace function doesn't accept extra arguments - how to avoid global variable? | I'm trying to increment all timestamps (of the form 'HH:MM:SS') in a text file by a number of seconds specified by a command-line parameter to my program.
Here's a simplified version of my effort so far:
import re
from datetime import datetime, timedelta
time_diff = timedelta(seconds=10)
def replace_time(matchobj):
... | [
"You can wrap a function in a closure like this:\ndef increment_by(time_diff):\n def replace_time(matchobj):\n if matchobj.group(1) not in [None, '']:\n return (datetime.strptime(matchobj.group(1), \"%H:%M:%S\") + time_diff).strftime(\"%H:%M:%S\")\n return replace_time\n\ntime_diff = timedel... | [
15,
1
] | [] | [] | [
"global_variables",
"python"
] | stackoverflow_0007868554_global_variables_python.txt |
Q:
python wsgi on windows 7
having followed this thread 3891996/setting-python-path-in-windows-xampp-using-wsgi and gotten xampp to run apache smoothly, when I try to access a sample page created, I get this response:
Access forbidden!
You don't have permission to access the requested object. It is either read-protec... | python wsgi on windows 7 | having followed this thread 3891996/setting-python-path-in-windows-xampp-using-wsgi and gotten xampp to run apache smoothly, when I try to access a sample page created, I get this response:
Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the ser... | [
"The presentation:\nhttp://code.google.com/p/modwsgi/wiki/WhereToGetHelp?tm=6#Conference_Presentations\nexplains the two common reasons you would get that message.\nThe second part of the message suggests the Apache service doesn't have ability to read the directories down to where the WSGI script file is.\n"
] | [
0
] | [] | [] | [
"python",
"wsgi",
"xampp"
] | stackoverflow_0007866205_python_wsgi_xampp.txt |
Q:
Python: Using AND and OR with .FIND() method
imagine I type the following code into the interpreter:
var1 = 'zuuzuu'
now suppose i type:
var1.find('a')
the interpreter returns -1. which i understand because the substring has not been found. but please help me understand this:
var1.find('a' or 'z') #case 1
retur... | Python: Using AND and OR with .FIND() method | imagine I type the following code into the interpreter:
var1 = 'zuuzuu'
now suppose i type:
var1.find('a')
the interpreter returns -1. which i understand because the substring has not been found. but please help me understand this:
var1.find('a' or 'z') #case 1
returns -1
but
var1.find('a' and 'z') #case 2
returns ... | [
"Expression 'a' or 'z' always yields 'a'. Expression 'a' and 'z' always yields 'z'. It's not some kind of DSL for making queries into containers, it's a simple boolean expression (and find is called with its result). If you want to say \"is there 'a' or 'z' in the string\", you need to do\nvar1.find('a') != -1 or v... | [
8,
2
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007868891_python_string.txt |
Q:
Progress gauge in status bar, using Cody Precord's ProgressStatusBar
I am attempting to create a progress gauge in the status bar for my application, and I'm using the example in Cody Precord's wxPython 2.8 Application Development Cookbook. I've reproduced it below.
For now I simply wish to show the gauge and have... | Progress gauge in status bar, using Cody Precord's ProgressStatusBar | I am attempting to create a progress gauge in the status bar for my application, and I'm using the example in Cody Precord's wxPython 2.8 Application Development Cookbook. I've reproduced it below.
For now I simply wish to show the gauge and have it pulse when the application is busy, so I assume I need to use the Star... | [
"I was advised to answer my own question, maybe it'll help others. This problem seems to be a platform (Linux?) specific problem. See joaquin's answer and accompanying comments.\nIt can be solved by calling Update() on the frame itself after each call to SetProgress(), as in this example\nimport time\nimport wx\n\n... | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0005277858_python_wxpython.txt |
Q:
Py3k MySQL driver for SQL Alchemy
I'm trying to find MySQL driver written in Python 3 which I may bind to SQL Alchemy. So it should be compatiable with DB-API 2.
The only driver which can connect to MySQL db in this one. But I cannot bind it with SQL Alchemy.
So, are there any other drivers which I can use?
A:
o... | Py3k MySQL driver for SQL Alchemy | I'm trying to find MySQL driver written in Python 3 which I may bind to SQL Alchemy. So it should be compatiable with DB-API 2.
The only driver which can connect to MySQL db in this one. But I cannot bind it with SQL Alchemy.
So, are there any other drivers which I can use?
| [
"oursql is compatible with Python3 and may bind to SQL Alchemy. It is not written in Python3, but then, neither is mypysql.\n"
] | [
2
] | [] | [] | [
"mysql",
"python",
"python_3.x",
"sql",
"sqlalchemy"
] | stackoverflow_0007869022_mysql_python_python_3.x_sql_sqlalchemy.txt |
Q:
epydoc hide some class functions?
I have some methods in my class which are only meant to be used by other methods of the class. I've prefixed their names with '_'. Can I hide those functions from epydoc? Is it a good idea?
Should I use '_' or double underscore? To be honest I didn't get the difference after readi... | epydoc hide some class functions? | I have some methods in my class which are only meant to be used by other methods of the class. I've prefixed their names with '_'. Can I hide those functions from epydoc? Is it a good idea?
Should I use '_' or double underscore? To be honest I didn't get the difference after reading about them in some places. Should th... | [
"If you want to hide all private methods and private variables, pass option '--no-private' to epydoc.\nNote that - for epydoc - a method or variable is private if:\n\nits name starts with an underscore '_' and\nits name does not end with an underscore '_' and\nyou did not include its name in the special all diction... | [
7
] | [] | [] | [
"docstring",
"epydoc",
"private",
"python"
] | stackoverflow_0007649571_docstring_epydoc_private_python.txt |
Q:
patching a local instance
consider I have the following code in python module a.py:
def func():
obj = Obj()
# Some code that uses obj
Is there a way to monkey patch obj without making it a function argument?
Reason: In the context of the code itself it should not be an argument, however in the context of ... | patching a local instance | consider I have the following code in python module a.py:
def func():
obj = Obj()
# Some code that uses obj
Is there a way to monkey patch obj without making it a function argument?
Reason: In the context of the code itself it should not be an argument, however in the context of testing and system simulations ... | [
"# if func() is defined in `a.py`\nimport a\n\noldObj, a.Obj = a.Obj, MockObj\na.func()\na.Obj = oldObj\n\n"
] | [
2
] | [] | [] | [
"monkeypatching",
"python"
] | stackoverflow_0007867875_monkeypatching_python.txt |
Q:
Is there a way to import a group of functions from a namespace "as" something (without the *)?
Rather than defining
from numpy import cos as cos
from numpy import arccos as arccos
and so on, can I do something like
trigfunctions = ('cos','arccos','sin','arcsin','tan','arctan')
for method in trigfunctions:
se... | Is there a way to import a group of functions from a namespace "as" something (without the *)? | Rather than defining
from numpy import cos as cos
from numpy import arccos as arccos
and so on, can I do something like
trigfunctions = ('cos','arccos','sin','arcsin','tan','arctan')
for method in trigfunctions:
setattr(HERE,method,getattr(numpy,method))
Where HERE is either global space (or possibly, local func... | [
"If you mean importing with the same name, simply leave off the as:\nfrom numpy import cos, arccos, sin, arcsin, tan, arctan\n\nBeyond that, you can use globals() to get the symbol table for the current module:\nme=globals();\ntrigfunctions = ('cos','arccos','sin','arcsin','tan','arctan')\nfor method in trigfunctio... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0007869406_python.txt |
Q:
Why don't processes die after page load? - Django
It seems logical to me that processes should die and memory be cleared after the python scripts have run and the HTTP response has been sent.
however It seems I have four processes running, one of which is using over 100MB of memory.
It seems like way too much for ... | Why don't processes die after page load? - Django | It seems logical to me that processes should die and memory be cleared after the python scripts have run and the HTTP response has been sent.
however It seems I have four processes running, one of which is using over 100MB of memory.
It seems like way too much for what I am doing. Is there some garbage collector settin... | [
"mod_wsgi keeps loaded python process in memory to speed up any further requests. That is absolutely normal/\n"
] | [
2
] | [] | [] | [
"django",
"garbage_collection",
"memory",
"python"
] | stackoverflow_0007869624_django_garbage_collection_memory_python.txt |
Q:
passing **settings info to unittest from nose
I'm running my unit tests using nose.
I have .ini files such as production.ini, development.ini, local.ini. Finally, I have a test.ini file which looks like:
[app:main]
use = config:local.ini
# Add additional test specific configuration options as necessary.
sqlalche... | passing **settings info to unittest from nose | I'm running my unit tests using nose.
I have .ini files such as production.ini, development.ini, local.ini. Finally, I have a test.ini file which looks like:
[app:main]
use = config:local.ini
# Add additional test specific configuration options as necessary.
sqlalchemy.url = sqlite:///%(here)s/tests.db
In my test cl... | [
"You will need to parse the settings from the INI file yourself. Pylons used to do this automatically for you by just hard-coding a load for \"test.ini\". The two options you have are 1) just load the INI settings via settings = paste.deploy.appconfig('test.ini') or 2) loading the actual WSGI app yourself, like if ... | [
7
] | [] | [] | [
"pyramid",
"python"
] | stackoverflow_0007864285_pyramid_python.txt |
Q:
inheriting config file settings in pyramid
Is a setup like this not possible?
production.ini file:
[app:main]
use = egg:my_project
... various settings ...
[server:main]
...
development.ini file:
[app:main]
use = config:production.ini#main
... override some production settings ...
Then I try starting my deve... | inheriting config file settings in pyramid | Is a setup like this not possible?
production.ini file:
[app:main]
use = egg:my_project
... various settings ...
[server:main]
...
development.ini file:
[app:main]
use = config:production.ini#main
... override some production settings ...
Then I try starting my development server and get:
No section 'main' (pref... | [
"It is possible to inherit INI files, but the inheritance only works on a section-by-section basis. So if you don't explicitly tell \"test.ini\" to inherit the [server:main] section, then it won't. The docs on all of this are via the PasteDeploy package although it's not entirely obvious.\nI've never actually seen ... | [
6
] | [] | [] | [
"paster",
"pyramid",
"python"
] | stackoverflow_0007864519_paster_pyramid_python.txt |
Q:
Python - SCP vs SSH for multiple computers and multiple files
Python 2.4.x (cannot install any non-stock modules).
Question for you all. (assuming use of subprocess.popen)
Say you had 20 - 30 machines - each with 6 - 10 files on them that you needed to read into a variable.
Would you prefer to scp into each machi... | Python - SCP vs SSH for multiple computers and multiple files | Python 2.4.x (cannot install any non-stock modules).
Question for you all. (assuming use of subprocess.popen)
Say you had 20 - 30 machines - each with 6 - 10 files on them that you needed to read into a variable.
Would you prefer to scp into each machine, once for each file (120 - 300 SCP commands total), reading each... | [
"Depending on the size of the file, you can possibly do something like:\n...\nfiles= \"file1 file2 ...\"\nmyvar = \"\"\nfor tm in machine_list\n myvar = myvar+ subprocess.check_output([\"ssh\", \"user@\" + tm, \"/bin/cat \" + files]);\n...\n\nfile1 file2 etc are space delimited. Assuming all are unix boxes... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"scp",
"ssh"
] | stackoverflow_0007869552_python_scp_ssh.txt |
Q:
Halt a recursively called function
I'm trying to halt the for loop below once values (x,y) or (z,2) have been returned so that the value i doesn't keep increasing, and simply halts when the if or elif condition is first
def maxPalindrome(theList):
# students need to put some logic here
maxcomplist = theLi... | Halt a recursively called function | I'm trying to halt the for loop below once values (x,y) or (z,2) have been returned so that the value i doesn't keep increasing, and simply halts when the if or elif condition is first
def maxPalindrome(theList):
# students need to put some logic here
maxcomplist = theList[:]
maxcomplist.reverse()
cont... | [
"As I wrote in a comment already: that function isn't a recursive one at all.\nRecursion means, that a function calls itself to complete it's purpose. This call can be indirect, meaning that the function uses helper function that will call the first function again.\nBut your code doesn't cover both cases.\nA recurs... | [
1,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0007869482_python_recursion.txt |
Q:
Make the worker thread wait for user input in GUI thread? Python/PyQt
I have a multi-threaded application written in Python in which one thread "takes care" of the GUI, and the other is the worker thread. At one point however, the worker thread, in the midst of processing data, emits a signal with a QString which ... | Make the worker thread wait for user input in GUI thread? Python/PyQt | I have a multi-threaded application written in Python in which one thread "takes care" of the GUI, and the other is the worker thread. At one point however, the worker thread, in the midst of processing data, emits a signal with a QString which connects to the display_image() function in the GUI thread. The display_ima... | [
"The easiest way to communicate between threads is with the Queue module. Have the GUI thread put an \"okay\" value and have the worker do a blocking get to receive the okay signal.\n"
] | [
2
] | [] | [] | [
"multithreading",
"pyqt",
"python"
] | stackoverflow_0007869892_multithreading_pyqt_python.txt |
Q:
Finding how many times a digit is in a number
This is currently what I'm at, I'm stuck with how to find how many times the digit was in the number, using the for loop. If anyone has any basic ideas, I'm new to python, so I'm not too knowledgeable about this language.
#Assignment 6
#Start out with print instructio... | Finding how many times a digit is in a number | This is currently what I'm at, I'm stuck with how to find how many times the digit was in the number, using the for loop. If anyone has any basic ideas, I'm new to python, so I'm not too knowledgeable about this language.
#Assignment 6
#Start out with print instructions
print """
This program will take a Number and Di... | [
">>> '123123123123111'.count('3')\n4\n\n",
"Your code is syntactically invalid in its current stage,\nif d == digit\n count +=1\nelse\n count +=0\n\nis missing colons:\nif d == digit:\n count +=1\nelse:\n count +=0 # or just pass, or better, skip the whole else tree\n\nApart from that, it works, altho... | [
5,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007869836_python.txt |
Q:
python || backup statement
In Javascript, I can assign a value like this so:
var i = p || 4
Obviously if p isn't defined it will resort to 4. Is there a more elegant version of this operation in Python than a try: / except: combo?
try:
i = p
except:
i = 4
A:
People sometime use Python's or-operator for t... | python || backup statement | In Javascript, I can assign a value like this so:
var i = p || 4
Obviously if p isn't defined it will resort to 4. Is there a more elegant version of this operation in Python than a try: / except: combo?
try:
i = p
except:
i = 4
| [
"People sometime use Python's or-operator for this purpose:\ndef f(p=None):\n i = p or 4\n ...\n\nThe relies on a \"unique to Python\" aspect of the or-operator to return the value that makes the expression true (rather than just returning True or False).\nAnother option that affords more flexibility is to us... | [
6,
3,
3,
1,
1
] | [] | [] | [
"python",
"variables"
] | stackoverflow_0007869861_python_variables.txt |
Q:
Python keeps ouputting "none"
Whenever I try to run this code:
def isPalindrome( theSubList ):
theSubListtest = theSubList[0:]
if len(theSubListtest) <= 1:
return True
elif len(theSubListtest) == 2:
x = theSubListtest[0]
y = theSubListtest[1]
if (x == y):
ret... | Python keeps ouputting "none" | Whenever I try to run this code:
def isPalindrome( theSubList ):
theSubListtest = theSubList[0:]
if len(theSubListtest) <= 1:
return True
elif len(theSubListtest) == 2:
x = theSubListtest[0]
y = theSubListtest[1]
if (x == y):
return True
else:
... | [
"Whoops.\nif (first == last):\n return isPalindrome(theSubListtest)\nelse:\n return False\n\n",
"You forgot a return. Change these lines:\nif (first == last):\n isPalindrome(theSubListtest)\n\nto\nif (first == last):\n return isPalindrome(theSubListtest)\n\nand the code will work as expected.\n"
] | [
4,
1
] | [] | [] | [
"boolean",
"palindrome",
"python",
"python_2.7"
] | stackoverflow_0007870067_boolean_palindrome_python_python_2.7.txt |
Q:
What do I need to import to gain access to my models?
I'd like to run a script to populate my database. I'd like to access it through the Django database API.
The only problem is that I don't know what I would need to import to gain access to this.
How can this be achieved?
A:
Import your settings module too
imp... | What do I need to import to gain access to my models? | I'd like to run a script to populate my database. I'd like to access it through the Django database API.
The only problem is that I don't know what I would need to import to gain access to this.
How can this be achieved?
| [
"Import your settings module too\nimport os\nos.environ[\"DJANGO_SETTINGS_MODULE\"] = \"mysite.settings\"\n\nfrom mysite.polls.models import Poll, Choice\n\nshould do the trick.\n",
"This is what I have at the top of one my data loading scripts.\nimport string\nimport sys\ntry:\n import settings # Assumed to b... | [
13,
6,
5,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000182229_django_python.txt |
Q:
Boto (Python)- reversed bucket list
Does anyone know how to get reversed bucket list.
bucketList = self.bucket.list(PREFIX)
bucketList.reverse()
does not work.
Thanks,
Ron.
A:
The reason that you can't do a reverse of bucket.list() is because that method actually returns a generator rather than the actual list.... | Boto (Python)- reversed bucket list | Does anyone know how to get reversed bucket list.
bucketList = self.bucket.list(PREFIX)
bucketList.reverse()
does not work.
Thanks,
Ron.
| [
"The reason that you can't do a reverse of bucket.list() is because that method actually returns a generator rather than the actual list. This is much more efficient and also allows boto to handle all of the paging of results behind the scenes.\nIf you really want to reverse it you could collect all of the element... | [
5
] | [] | [] | [
"amazon_s3",
"boto",
"bucket",
"list",
"python"
] | stackoverflow_0007784092_amazon_s3_boto_bucket_list_python.txt |
Q:
Exporting one list into another
So I want to export the data from one list into another so I can mess with it and still have an untouched copy of the original data. I know you can do this with list splicing but I have to export the data from the first list only after an index value of i that is determined by a fun... | Exporting one list into another | So I want to export the data from one list into another so I can mess with it and still have an untouched copy of the original data. I know you can do this with list splicing but I have to export the data from the first list only after an index value of i that is determined by a function previously defined. How would I... | [
"Slice using i.\nnewlist = oldlist[i:]\n\n",
"Splicing works. If x is your list, and f is your function, then\nnewlist = x[f():]\n\nis your new list\n"
] | [
3,
0
] | [] | [] | [
"indexing",
"list",
"python",
"python_2.7"
] | stackoverflow_0007870442_indexing_list_python_python_2.7.txt |
Q:
How can i change the size of the "worm" in my game?
Possible Duplicate:
How would i change the width of the snake in my “snake game”?
Im using python and pygame:
How can i change the width of the "worm" in my game? So far the snake is only 1 pixel wide how can i change the width to be 3 or 4 pixels wide?
class W... | How can i change the size of the "worm" in my game? |
Possible Duplicate:
How would i change the width of the snake in my “snake game”?
Im using python and pygame:
How can i change the width of the "worm" in my game? So far the snake is only 1 pixel wide how can i change the width to be 3 or 4 pixels wide?
class Worm:
def __init__(self, surface):
self.surfa... | [
"Grow it thicker with\n self.body.insert(0, (self.x, self.y))\n self.body.insert(0, (self.x, self.y+1))\n self.body.insert(0, (self.x, self.y-1))\n self.body.insert(0, (self.x+1, self.y))\n self.body.insert(0, (self.x-1, self.y))\n ... # corner cases if they are important\n\ndraw() will automatically take in th... | [
2,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0007870392_pygame_python.txt |
Q:
How do I parse the JSON array when trying to load facebook friends into Google App Engine facebook example?
I am just starting out on an idea of a Google App engine app that interacts with Facebook. All my coding experience is number crunching in Matlab, which is so high level, a lot of real coders haven't even h... | How do I parse the JSON array when trying to load facebook friends into Google App Engine facebook example? | I am just starting out on an idea of a Google App engine app that interacts with Facebook. All my coding experience is number crunching in Matlab, which is so high level, a lot of real coders haven't even heard of it. I am attempting to extend the example provided by facebook here. So far, the only thing I've tried ... | [
"\nI think I should be turning this JSON array into a python dictionary but I don't know how. \n\nsimplejson is included in app-engine, in django's utils package.\nfrom django.utils import simplejson as json\n\ndef your_method(ars):\n # do what ever you are doing...\n dict_of_friends = json.loads(json_string)\n... | [
4,
0,
0
] | [] | [] | [
"facebook",
"google_app_engine",
"json",
"python"
] | stackoverflow_0004355762_facebook_google_app_engine_json_python.txt |
Q:
Read from file and instanciate new class based on file input
I'm trying to store a file which encode an id of a class, read the file and call the class so that ->
in the files the data will be stored like
id_class:(arguments)
than the read file will look up from a list of file the right class to invoque and pass ... | Read from file and instanciate new class based on file input | I'm trying to store a file which encode an id of a class, read the file and call the class so that ->
in the files the data will be stored like
id_class:(arguments)
than the read file will look up from a list of file the right class to invoque and pass the arguments.
something like this:
class foo:
id = 1
... | [
"I changed both create methods - they were missing parenthesis, without them no new instances of the object were created. Also, I changed the class_dict so it won't call the create methods, instead I defer the instantiation to the moment the class_dict is accessed: class_dict[index](). The modified code looks like ... | [
1
] | [] | [] | [
"data_structures",
"file",
"python"
] | stackoverflow_0007870589_data_structures_file_python.txt |
Q:
Create Function to replace index in string with index in list, then save those values into an HTML file.
Ok so basically I have a csv file with different values. I want each line from the csv needs to create a new html file. Each value in the line of the csv needs to replace the values1 - 7 in the html. I've tr... | Create Function to replace index in string with index in list, then save those values into an HTML file. | Ok so basically I have a csv file with different values. I want each line from the csv needs to create a new html file. Each value in the line of the csv needs to replace the values1 - 7 in the html. I've tried to create a function to handle this, but I can't get it to change the values in the html. I can change th... | [
"Python passes parameters by a scheme they refer to as \"Call-By-Object.\" When you reassign the string in your replacehtml function, this doesn't change the original html string because strings are an immutable type.\nFastest fix is probably to change the string to a return of the function.\ndef replacehtml(html, ... | [
0
] | [] | [] | [
"csv",
"html",
"python"
] | stackoverflow_0007870694_csv_html_python.txt |
Q:
Manipulating Lists within lists in python
I'm having trouble wrapping my head around dealing with lists within lists in python (I am rather new at programming).
Now how would I access each nested list position and then manipulate the position of the nested list's values to, for example, change their order while ma... | Manipulating Lists within lists in python | I'm having trouble wrapping my head around dealing with lists within lists in python (I am rather new at programming).
Now how would I access each nested list position and then manipulate the position of the nested list's values to, for example, change their order while maintaining the position of the nested list in th... | [
"Use a list comprehension to get the new elements, and optionally slice-assign to replace the existing elements in the list.\nnew_aList = [list(reversed(x)) for x in aList]\naList[:] = [list(reversed(x)) for x in aList]\n\n",
"You could reverse each item like this\n>>> aList = [\n... [1,2,3,4,3,2],\n... [... | [
9,
4,
2,
1
] | [] | [] | [
"nested_lists",
"python"
] | stackoverflow_0007870008_nested_lists_python.txt |
Q:
set.add() returning error
I am trying to add items to an empty set from a list after checking if the page is rooted with the isRooted function.
uniqueUrl = set()
for url in urlList:
if(isRooted(rootURL,url[0])):
uniqueURL.add(url[0])
This is the error I am recieving:
Traceback (most recent call last):... | set.add() returning error | I am trying to add items to an empty set from a list after checking if the page is rooted with the isRooted function.
uniqueUrl = set()
for url in urlList:
if(isRooted(rootURL,url[0])):
uniqueURL.add(url[0])
This is the error I am recieving:
Traceback (most recent call last):
File "<stdin>", line 1, in <mo... | [
"Caps are different in the two variables.\n"
] | [
1
] | [] | [] | [
"python",
"set"
] | stackoverflow_0007870881_python_set.txt |
Q:
Dealing with timezones for sending sms -python /django
I need to send sms globally to different timezones to each customer registered online
The messages are scheduled to be send each month.
I have the country details of each cutomer . I would be writing a python script and add it to cronjobs for sending sms.
The... | Dealing with timezones for sending sms -python /django | I need to send sms globally to different timezones to each customer registered online
The messages are scheduled to be send each month.
I have the country details of each cutomer . I would be writing a python script and add it to cronjobs for sending sms.
The issue I am facing is knowing a safe time ( sometime during ... | [
"You probably want to store each user's timezone in your database and then you can change a particular datetime object's timezone by using datetime.astimezone(tz) . \nNow deciding what a good time to to sms them is entirely up to you. \n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007870966_python.txt |
Q:
Python - can someone tell me what these two lines do?
I'm trying to convert this Python code to C. But for the life of me, I can't figure out what this line here does. The rest of the program seems simple.
self.payload = "\x02\x00%s%s" % (
pack(">b", length),
"".join(random.choice(string.printable) for i i... | Python - can someone tell me what these two lines do? | I'm trying to convert this Python code to C. But for the life of me, I can't figure out what this line here does. The rest of the program seems simple.
self.payload = "\x02\x00%s%s" % (
pack(">b", length),
"".join(random.choice(string.printable) for i in range(length)))
If anybody could give me a rough idea of... | [
"First line:\n\nThe correct translation of length = random.randint(18, 20) is int length = rand() % 3 + 18.\n\nNow let's dissect the dense second line piece by piece.\n\n\"\\x02\\x00%s%s\" % (x, y) means to substitute the format string with the given arguments (like sprintf()). In this case it means concatenating t... | [
5
] | [] | [] | [
"c",
"python",
"string"
] | stackoverflow_0007871138_c_python_string.txt |
Q:
Pygame: Drawing Ellipse or Rectangle based on Constructor Argument
I don't know if this is the correct website, but you guys have been so helpful before, I wanted to get your advice on a problem I'm having with Python and Pygame.
I am making a simple game, and only recently begun learning Python (loving it so far)... | Pygame: Drawing Ellipse or Rectangle based on Constructor Argument | I don't know if this is the correct website, but you guys have been so helpful before, I wanted to get your advice on a problem I'm having with Python and Pygame.
I am making a simple game, and only recently begun learning Python (loving it so far) and at the moment, I having a sprite constructor which I am using. Thi... | [
"In the Block constructor, you call self.image.fill(color). That will fill the sprite's entire image with that color, so you get a rectangle.\nThe example code you have calls self.image.set_colorkey(white) after doing the fill, so that when it gets drawn, the background fill is transparent. That's probably the fa... | [
2,
1
] | [] | [] | [
"constructor",
"pygame",
"python",
"sprite"
] | stackoverflow_0007870146_constructor_pygame_python_sprite.txt |
Q:
Python `aggdraw` module bug (?): visible alpha channel
Imagine simple script:
from PIL import Image
from aggdraw import Draw, Brush
im = Image.new("RGBA", (600, 600), (0, 0, 0, 0))
draw = Draw(im)
brush = Brush("yellow")
draw.polygon(
(
50, 50,
550, 60,
550... | Python `aggdraw` module bug (?): visible alpha channel | Imagine simple script:
from PIL import Image
from aggdraw import Draw, Brush
im = Image.new("RGBA", (600, 600), (0, 0, 0, 0))
draw = Draw(im)
brush = Brush("yellow")
draw.polygon(
(
50, 50,
550, 60,
550, 550,
60, 550,
),
N... | [
"It's because your background is black, but transparent. If you set your image background to white, you don't get the visible edges. Either transparent or solid white works in my simple tests.\nTry these values:\ntransBlack = (0, 0, 0, 0) # shows your example with visible edges\nsolidBlack = (0, 0, 0, 255) ... | [
1
] | [] | [] | [
"aggdraw",
"alpha_transparency",
"python",
"python_imaging_library"
] | stackoverflow_0006942039_aggdraw_alpha_transparency_python_python_imaging_library.txt |
Q:
How do I sort by minimum with a iterative function?
My teacher wants me to do an algorithm to sort in ascending order but by using the minimum number in a list and putting it at the beginning. I read a file of numbers and so far I have:
def findMin(ls, n):
m = 0
for i in range(1, n): #n is... | How do I sort by minimum with a iterative function? | My teacher wants me to do an algorithm to sort in ascending order but by using the minimum number in a list and putting it at the beginning. I read a file of numbers and so far I have:
def findMin(ls, n):
m = 0
for i in range(1, n): #n is length
if ls[i]<ls[m]:
... | [
"From your description what I deduced is that your teacher wants you to implement Selection Sort algorithm. You may want to have a look at it.\nIn this algorithm, you swap the least number with the current position. Initially the current position is at the beginning of the list and it shifts as you swap values.\n",... | [
1,
0
] | [] | [] | [
"algorithm",
"min",
"python"
] | stackoverflow_0007871193_algorithm_min_python.txt |
Q:
Autocomplete Textbox Example in python + Google app engine
For my google app engine application, I need to include a autocompleter Textbox which will show the name starting with the textbox value.And the name will retrieve from the google app engine datastore.
Any good tutorial or sample code please.
Update: Pleas... | Autocomplete Textbox Example in python + Google app engine | For my google app engine application, I need to include a autocompleter Textbox which will show the name starting with the textbox value.And the name will retrieve from the google app engine datastore.
Any good tutorial or sample code please.
Update: Please Answer for this
I created a sample HTML code : dl.dropbox.com/... | [
"You can have a look at the jquery auto complete here\nHTML :\n$(\"#search_users\").autocomplete(/search/search_manager);\n\npython-controller:\njquery autocomplete plugin by default uses variable q\nclass search_user(webapp.RequestHandler):\n q = (self.request.GET['q']).lower() \n results=mod... | [
8,
2,
0
] | [] | [] | [
"ajax",
"autocomplete",
"google_app_engine",
"python"
] | stackoverflow_0005935638_ajax_autocomplete_google_app_engine_python.txt |
Q:
GAE find entities with item not in ListProperty
I have a little application where I am passing messages between users. My model for the message is like this
class Message(db.Model):
from = db.UserProperty()
sent_to_users = db.ListProperty(db.Key)
I send the message to users if they are online, so when I ... | GAE find entities with item not in ListProperty | I have a little application where I am passing messages between users. My model for the message is like this
class Message(db.Model):
from = db.UserProperty()
sent_to_users = db.ListProperty(db.Key)
I send the message to users if they are online, so when I detect that a user is online I send any message that ... | [
"Inequality filters on list properties don't really work. As you know, inequality filters run separate \"less than value\" and \"greater than value\" queries under the hood, and then concatenate the results. List properties with multiple values will have multiple hits in the same index, so if you filter out one ite... | [
2,
0,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007865694_google_app_engine_google_cloud_datastore_python.txt |
Q:
Returning an instance of class from constructor
I need to return an instance of Bike in the constructor. For example:
class Bike(object):
def __init__(self,color):
self.bikeColor = color
return self #It should return an instance of the class; is this not right?
myBike = Bike("blue")
When I do... | Returning an instance of class from constructor | I need to return an instance of Bike in the constructor. For example:
class Bike(object):
def __init__(self,color):
self.bikeColor = color
return self #It should return an instance of the class; is this not right?
myBike = Bike("blue")
When I do the above, I get the following error:
TypeError: __i... | [
"class Bike(object):\n def __init__(self, color):\n self.bikeColor = color\n\nmyBike = Bike(\"blue\")\n\nIs enough. In Python, __init__ is not really a constructor - it's an initializer. It takes an already constructed object and initializes it (for example, setting its bikeColor attribute.\nPython also h... | [
4
] | [] | [] | [
"instance",
"python"
] | stackoverflow_0007871248_instance_python.txt |
Q:
How do i get "score" to show up in the game window?
So far in my snake game the score is printed in python shell. How can i have it printed in the games window instead? So that the game and the score are in the same window?
Thanks Eric
while running:
screen.fill((0, 0, 0))
worm.move()
worm.draw()
... | How do i get "score" to show up in the game window? | So far in my snake game the score is printed in python shell. How can i have it printed in the games window instead? So that the game and the score are in the same window?
Thanks Eric
while running:
screen.fill((0, 0, 0))
worm.move()
worm.draw()
food.draw()
if worm.crashed:
exit();
el... | [
"Use the font module to render fonts on screen.\nFrom the userguide:\nwhite = (255, 255, 255)\n\nmessage = 'your message'\nfont = pygame.font.Font(None, 40)\ntext = font.render(message, 1, white)\nscreen.blit(text, (x_position,y_position))\n\n",
"In response to your edit: You're only blitting the text to the scr... | [
1,
1
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0007869637_pygame_python.txt |
Q:
Create Form Auto Complete in Google App Engine
I want to build a auto complete feature for a tags field like in SO on App Engine ... any idea how I should go about the process?
Server Side Algo? - What logic should be there for auto-complete?
App Engine implementation? - What should be the Datastore schema for thi... | Create Form Auto Complete in Google App Engine | I want to build a auto complete feature for a tags field like in SO on App Engine ... any idea how I should go about the process?
Server Side Algo? - What logic should be there for auto-complete?
App Engine implementation? - What should be the Datastore schema for this?
| [
"Hey. I came around this question a few days ago. The datastore schema doesn't really matter as long as you have a StringProperty field that you'd like to search on. Since App Engine does not support full text searching yet, you'll have to go with some sort of a \"starts with\" search, which is not 100% but quite o... | [
8,
6,
1
] | [] | [] | [
"ajax",
"autocomplete",
"google_app_engine",
"python"
] | stackoverflow_0004243570_ajax_autocomplete_google_app_engine_python.txt |
Q:
Funny ASCI error with .replace("x","w")
I am making a program that takes a sentence and garbles it, until run through a "degarbler"
Theres probably a better way to do this, but I would appreciate it if everyone would show me how to fix what I am doing wrong
def sencoder (sentence):
sentence = sentence.replace ... | Funny ASCI error with .replace("x","w") | I am making a program that takes a sentence and garbles it, until run through a "degarbler"
Theres probably a better way to do this, but I would appreciate it if everyone would show me how to fix what I am doing wrong
def sencoder (sentence):
sentence = sentence.replace ("a","h")
sentence = sentence.replace ("s... | [
"Here is a hint: Use the translate method instead.\n>>> import string\n\n>>> t = string.maketrans(\"abcdef\", \"bcdefa\")\n>>> \"abracadabra\".translate(t)\n'bcrbdbebcrb'\n\n>>> t2 = string.maketrans(\"bcdefa\", \"abcdef\")\n>>> \"bcrbdbebcrb\".translate(t2)\n'abracadabra'\n\n",
"\nI am making a program that take... | [
5,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007871402_python.txt |
Q:
Convert binary data to web-safe text and back - Python
I want to convert a binary file (such as a jpg, mp3, etc) to web-safe text and then back into binary data. I've researched a few modules and I think I'm really close but I keep getting data corruption.
After looking at the documentation for binascii I came up ... | Convert binary data to web-safe text and back - Python | I want to convert a binary file (such as a jpg, mp3, etc) to web-safe text and then back into binary data. I've researched a few modules and I think I'm really close but I keep getting data corruption.
After looking at the documentation for binascii I came up with this:
from binascii import *
raw_bytes = open('test.jpg... | [
"You should use base64 encoding instead of quoted printable. Use b2a_base64() and a2b_base64().\nQuoted printable is much bigger for binary data like pictures. In this encoding each binary (non alphanumeric character) code is changed into =HEX. It can be used for texts that consist mainly of alphanumeric like email... | [
1,
1,
1
] | [
"@PMC's answer copied from the question:\nHere's what works:\nfrom binascii import *\nraw_bytes = open('28.jpg','rb').read()\nstr_list = []\ni = 0\nwhile i < len(raw_bytes):\n byteSegment = raw_bytes[i:i+57]\n str_list.append(b2a_base64(byteSegment))\n i += 57\nbytesBackAll = a2b_base64(''.join(str_list))\... | [
-2
] | [
"ascii",
"binary",
"file",
"python",
"utf"
] | stackoverflow_0007868572_ascii_binary_file_python_utf.txt |
Q:
How to know who is importing me in python?
How can I find out what file is importing a particular file in python?
Consider the following example:
#a.py
import cmn
....
#b.py
import cmn
...
#cmn.py
#Here, I want to know which file (a.py or b.py)
#is importing this one.
#Is it possible to do this?
...
All the fil... | How to know who is importing me in python? | How can I find out what file is importing a particular file in python?
Consider the following example:
#a.py
import cmn
....
#b.py
import cmn
...
#cmn.py
#Here, I want to know which file (a.py or b.py)
#is importing this one.
#Is it possible to do this?
...
All the files a.py, b.py and cmn.py are in the same directo... | [
"The namedtuple code in the collections module has an example of how (and when) to do this:\n#cmn.py\nimport sys\nprint 'I am being imported by', sys._getframe(1).f_globals.get('__name__')\n\nOne limitation of this approach is that the outermost module is always named __main__. If that is the case, the name of the... | [
11,
3,
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0007871319_import_python.txt |
Q:
PyCrypto examples for Python3
I am looking for examples PyCrypto AES and RSA algorithms. Anybody can help me links, or examples right here?
A:
If you're interested in the math for making RSA key pairs and applying them, here is a recipe that might interest you: http://code.activestate.com/recipes/577737
For a c... | PyCrypto examples for Python3 | I am looking for examples PyCrypto AES and RSA algorithms. Anybody can help me links, or examples right here?
| [
"If you're interested in the math for making RSA key pairs and applying them, here is a recipe that might interest you: http://code.activestate.com/recipes/577737\nFor a complete implementation, why not look at the source for PyCrypto.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007871714_python.txt |
Q:
How can I create a SEO friendly dash-delimited url from a string in PYTHON?
Basically, my question is the same as this but in Python (and GAE), not C#.
Requirements:
Separate each word by a dash and remove all punctuation (taking into account not all words are separated by spaces.)
Function takes in a max length,... | How can I create a SEO friendly dash-delimited url from a string in PYTHON? | Basically, my question is the same as this but in Python (and GAE), not C#.
Requirements:
Separate each word by a dash and remove all punctuation (taking into account not all words are separated by spaces.)
Function takes in a max length, and gets all tokens below that max length. Example: ToSeoFriendly("hello world h... | [
"def ToSeoFriendly(s, maxlen):\n '''Join with dashes, eliminate punction, clip to maxlen, lowercase.\n\n >>> ToSeoFriendly(\"The quick. brown4 fox jumped\", 14)\n 'the-quick-brow'\n\n '''\n t = '-'.join(s.split()) # join words with dashes\n u = ''.join([c for... | [
5,
3,
3
] | [] | [] | [
"python",
"url"
] | stackoverflow_0007855794_python_url.txt |
Q:
Tutorials/Learning Resources for Implementing a Script Interpreter (e.g. Python, Lua) in C#
I'm looking for a complete tutorial / learning resource, from which I can learn how to implement a script parser in C#.
My intention is to implement such a system within a game engine to promote the creation of user genera... | Tutorials/Learning Resources for Implementing a Script Interpreter (e.g. Python, Lua) in C# | I'm looking for a complete tutorial / learning resource, from which I can learn how to implement a script parser in C#.
My intention is to implement such a system within a game engine to promote the creation of user generated content.
Edit: This is more as a learning exercise than anything else.
| [
"Why not just integrate an existing script parser (e.g.: integrating Lua into C#)?\n"
] | [
2
] | [] | [] | [
"c#",
"lua",
"python"
] | stackoverflow_0007872160_c#_lua_python.txt |
Q:
SQLAlchemy inheritance based on whether data exists in another table
I have two legacy table that I would like to use SQLAlchemy declarative to access data.
Order:
order_id
is_processed
FooData:
foo_id
order_id
A order may or may not have FooData and I would like to distinguish between the two order types using ... | SQLAlchemy inheritance based on whether data exists in another table | I have two legacy table that I would like to use SQLAlchemy declarative to access data.
Order:
order_id
is_processed
FooData:
foo_id
order_id
A order may or may not have FooData and I would like to distinguish between the two order types using SQLAlchemy declarative models.
The problem I have wrapping my head around ... | [
"If you can change the DB, then simply add one discriminator column, set\nthe value of this column to proper value (order|foodata) depending on whether\nthe foodata exists for it, make it NOT NULL and configure simple Joined Table Inheritance.\nIf you cannot change the DB (add a discriminator column) and you only h... | [
0
] | [] | [] | [
"inheritance",
"python",
"sqlalchemy"
] | stackoverflow_0007856195_inheritance_python_sqlalchemy.txt |
Q:
Why does Tkinter freeze when packing a scrollbar?
I'm trying to attach a scrollbar to a list box in Tkinter, but whenever the code reaches one of the .pack() lines it freezes... any idea why? (I've experimented with running an example code that does the same thing that I found on the internet and that worked fine)... | Why does Tkinter freeze when packing a scrollbar? | I'm trying to attach a scrollbar to a list box in Tkinter, but whenever the code reaches one of the .pack() lines it freezes... any idea why? (I've experimented with running an example code that does the same thing that I found on the internet and that worked fine).
#Read Box
self.scrollbar = Tkinter.Scroll... | [
"Seems that you're mixing pack and grid at same level (i.e. not inside two separate Frame or else). This will make your app to freeze, as described in documentation.\nSo what you should do is to .grid your scrollbar :-)\nMore material: as said above, you can mix different window managers, but not inside the same fr... | [
2
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0007872534_python_tkinter.txt |
Q:
Django/Python POST
First a bit of an introduction. I will send a POST to a url and it will have either
ip, mac or hostname. Now depending on which of these key' are in the QueryDict i want it to do certain calls. I.e:
Output of
print request.POST
<QueryDict: {u'ip': [u'10.1.24.178'], u'message': [u'Test'], u'cli... | Django/Python POST | First a bit of an introduction. I will send a POST to a url and it will have either
ip, mac or hostname. Now depending on which of these key' are in the QueryDict i want it to do certain calls. I.e:
Output of
print request.POST
<QueryDict: {u'ip': [u'10.1.24.178'], u'message': [u'Test'], u'client': [u'auabrthin1']}>
... | [
"if 'client' in request.POST:\n # do something\n\n"
] | [
8
] | [] | [] | [
"django",
"post",
"python"
] | stackoverflow_0007873020_django_post_python.txt |
Q:
How do I create a tuple with an attribute using Python?
I have a class WeightedArc defined as follows:
class Arc(tuple):
@property
def tail(self):
return self[0]
@property
def head(self):
return self[1]
@property
def inverted(self):
return Arc((self.head, self.tail))
def __eq__(self, ... | How do I create a tuple with an attribute using Python? | I have a class WeightedArc defined as follows:
class Arc(tuple):
@property
def tail(self):
return self[0]
@property
def head(self):
return self[1]
@property
def inverted(self):
return Arc((self.head, self.tail))
def __eq__(self, other):
return self.head == other.head and self.tail == o... | [
"The fixed-up version of your original code is:\nclass WeightedArc(Arc):\n def __new__(cls, arc, weight):\n self = tuple.__new__(cls, arc)\n self.weight = weight\n return self\n\nAnother approach to look at the verbose option for collections.namedtuple to see an example of how to subclass tu... | [
7,
2
] | [] | [] | [
"inheritance",
"python",
"tuples"
] | stackoverflow_0007871818_inheritance_python_tuples.txt |
Q:
How to compare dates in Python?
I need to see if a date has more than X days. How can I do this in Python?
I have tested something like:
if datetime.date(2010, 1, 12) > datetime.timedelta(3):
I got the error:
TypeError: can't compare datetime.date to datetime.timedelta
Any clue on how to achieve this?
A:
You c... | How to compare dates in Python? | I need to see if a date has more than X days. How can I do this in Python?
I have tested something like:
if datetime.date(2010, 1, 12) > datetime.timedelta(3):
I got the error:
TypeError: can't compare datetime.date to datetime.timedelta
Any clue on how to achieve this?
| [
"You can't compare a datetime to a timedelta. A timedelta represents a duration, a datetime represents a specific point in time. The difference of two datetimes is a timedelta. Datetimes are comparable with each other, as are timedeltas.\nYou have 2 options:\n\nSubtract another datetime from the one you've given, a... | [
7,
1
] | [] | [] | [
"date_comparison",
"datetime",
"python"
] | stackoverflow_0007873013_date_comparison_datetime_python.txt |
Q:
How to make python modules compatible with different OS?
I have windows xp, I have found some python libraries that only work for windows xp and thus if you have a mac os or linux or windows 7, you can't download my program because it won't work, how to make these libraries compatible with these OS, I can't ask th... | How to make python modules compatible with different OS? | I have windows xp, I have found some python libraries that only work for windows xp and thus if you have a mac os or linux or windows 7, you can't download my program because it won't work, how to make these libraries compatible with these OS, I can't ask the creator of the libraries so I have to download the source co... | [
"You're asking a very general question. Perhaps overly general.\nGenerally, unless your application is relatively simple, it's impossible to guarantee that it is going to work on Linux and Mac OS X by only having Windows available. You will have to at least test it on Linux. Mac OS X is rather similar to Linux in m... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007873170_python.txt |
Q:
How to organize this loop in a more elegant Pythonic way
So I have a function which reduces some dataset, and returns the number of elements removed. I have to stop applying it once the number of items reduced during the function's operation is zero. Currently I've got this:
num_removed = reduction_pass(dataset)
w... | How to organize this loop in a more elegant Pythonic way | So I have a function which reduces some dataset, and returns the number of elements removed. I have to stop applying it once the number of items reduced during the function's operation is zero. Currently I've got this:
num_removed = reduction_pass(dataset)
while num_removed > 0:
num_removed = reduction_pass(dataset... | [
"I assume you don't actually need the final return value, as I assume it indicates the number of removed elements, which will obviously always be 0 on the last pass.\nThe simple-is-better-than-complex way:\nwhile reduction_pass(dataset) > 0: pass\n\nThe showing-off, obviously-not-serious way:\nfrom itertools import... | [
4,
1,
0,
0,
0
] | [] | [] | [
"do_while",
"iterator",
"loops",
"python"
] | stackoverflow_0007873213_do_while_iterator_loops_python.txt |
Q:
Creating Bar Charts in Python
I have a couple of problems with the Bar Chart that I'm trying to create in python. My code for the chart looks like this:
import matplotlib
matplotlib.use('Agg')
from pylab import *
import calendar
def webshow(img):
savefig(img,dpi=500)
print 'Content-Type: text/html\n'
... | Creating Bar Charts in Python | I have a couple of problems with the Bar Chart that I'm trying to create in python. My code for the chart looks like this:
import matplotlib
matplotlib.use('Agg')
from pylab import *
import calendar
def webshow(img):
savefig(img,dpi=500)
print 'Content-Type: text/html\n'
print '<img width="800" height="40... | [
"First up, I would use a figure object to work on: this makes it easier to construct the plot to your liking. To construct your graph, the following should do:\nfig = plt.figure()\nfig.subplots_adjust(bottom=0.2) # Remark 1\nax = fig.add_subplot(111)\nax.bar(arange(len(grosses)), grosses)\nax.ticklabel_for... | [
4
] | [] | [] | [
"bar_chart",
"charts",
"matplotlib",
"python"
] | stackoverflow_0007871338_bar_chart_charts_matplotlib_python.txt |
Q:
Jython standalone jar and packages
Is it possible to create a jython standalone (jar) including jython packages (pynum, python-excel, ...)?
A:
Yes. Jython FAQ on distribution. Basically, you just need to have the /Lib directory inside the Jython jar. You can add modules there - as long as they are Jython compati... | Jython standalone jar and packages | Is it possible to create a jython standalone (jar) including jython packages (pynum, python-excel, ...)?
| [
"Yes. Jython FAQ on distribution. Basically, you just need to have the /Lib directory inside the Jython jar. You can add modules there - as long as they are Jython compatible (ie no native part).\n"
] | [
2
] | [] | [] | [
"java",
"jython",
"python"
] | stackoverflow_0007824921_java_jython_python.txt |
Q:
Convert file stream to base64 python
I have read the file stream of a zip file by the following code:
file = open(source_url, "rb")
data = file.read()
file.close()
byte_arr = base64.b64encode(data)
Now I am trying to call a webservice which accepts base64Binary format of data (byte array written in java).... | Convert file stream to base64 python | I have read the file stream of a zip file by the following code:
file = open(source_url, "rb")
data = file.read()
file.close()
byte_arr = base64.b64encode(data)
Now I am trying to call a webservice which accepts base64Binary format of data (byte array written in java). If I send byte_arr to the web-service I g... | [
"I guess there's nothing wrong with your base64 encoding. It seems like it is not embedded in a correct XML document. Probably the error is when you send your data, maybe you should check that piece of code.\n"
] | [
1
] | [] | [] | [
"base64",
"python"
] | stackoverflow_0007873677_base64_python.txt |
Q:
How to convert date to timestamp using Python?
I need to convert this result to timestamp:
>>> print (datetime.date(2010, 1, 12) + datetime.timedelta(days = 3))
2010-01-15
I need to compare the value with this timestamp:
>>> datetime.datetime.now()
2011-10-24 10:43:43.371294
How can I achieve this?
A:
I need t... | How to convert date to timestamp using Python? | I need to convert this result to timestamp:
>>> print (datetime.date(2010, 1, 12) + datetime.timedelta(days = 3))
2010-01-15
I need to compare the value with this timestamp:
>>> datetime.datetime.now()
2011-10-24 10:43:43.371294
How can I achieve this?
| [
"\nI need to convert this result to timestamp\n\nimport time\n\n\nmydate = datetime.date(2010, 1, 12) + datetime.timedelta(days = 3)\ntime.mktime(mydate.timetuple())\n\n\nI need to compare the value with this timestamp:\n\na = datetime.datetime(2010, 1, 12) + datetime.timedelta(days = 3)\nb = datetime.datetime.now(... | [
8,
1,
1
] | [] | [] | [
"datetime_conversion",
"python"
] | stackoverflow_0007873828_datetime_conversion_python.txt |
Q:
utf8 codec can't decode byte 0x96 in python
I am trying to check if a certain word is on a page for many sites. The script runs fine for say 15 sites and then it stops.
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 15344: invalid start byte
I did a search on stackoverflow and found many issu... | utf8 codec can't decode byte 0x96 in python | I am trying to check if a certain word is on a page for many sites. The script runs fine for say 15 sites and then it stops.
UnicodeDecodeError: 'utf8' codec can't decode byte 0x96 in position 15344: invalid start byte
I did a search on stackoverflow and found many issues on it but I can't seem to understand what went... | [
"The byte at 15344 is 0x96. Presumably at position 15343 there is either a single-byte encoding of a character, or the last byte of a multiple-byte encoding, making 15344 the start of a character. 0x96 is in binary 10010110, and any byte matching the pattern 10XXXXXX (0x80 to 0xBF) can only be a second or subsequen... | [
29,
9,
3
] | [] | [] | [
"python"
] | stackoverflow_0007873556_python.txt |
Q:
Django App Dependency Cycle
I am in the middle of developing a Django application, which has quite complicated models (it models a university - courses, modules, lectures, students etc.)
I have separated the project into apps, to make the whole thing more organised (apps are courses, schools, people, modules and t... | Django App Dependency Cycle | I am in the middle of developing a Django application, which has quite complicated models (it models a university - courses, modules, lectures, students etc.)
I have separated the project into apps, to make the whole thing more organised (apps are courses, schools, people, modules and timeperiods). I am having a proble... | [
"If your dependency is with foreign keys referencing models in other applications, you don't need to import the other model. You can use a string in your ForeignKey definition:\nclass MyModel(models.Model):\n myfield = models.ForeignKey('myotherapp.MyOtherModel')\n\nThis way there's no need to import MyOtherMode... | [
60,
5,
3,
2
] | [] | [] | [
"dependencies",
"django",
"python"
] | stackoverflow_0000895454_dependencies_django_python.txt |
Q:
python setuptools installation in centos
i have to install mysqldb module of python in my centos server. i have 2 versions of python
2.4.3 the default one
2.6 which i installed
i want to install mysqldb module for 2.6 version of the python.
i installed it from here but when i am on the line
python2.6 setup.py i... | python setuptools installation in centos | i have to install mysqldb module of python in my centos server. i have 2 versions of python
2.4.3 the default one
2.6 which i installed
i want to install mysqldb module for 2.6 version of the python.
i installed it from here but when i am on the line
python2.6 setup.py install
it says
Traceback (most recent call la... | [
"When you installed Python 2.6, you most likely didn't have zlib-devel installed, so your Python doesn't have that feature built in. I recommend that you install\nreadline-devel\nsqlite-devel\nzlib-devel\nopenssl-devel\n\nbefore compiling your own Python. After installing the newly compiled Python, fetch the setupt... | [
9
] | [] | [] | [
"centos",
"mysql_python",
"python",
"setuptools",
"zlib"
] | stackoverflow_0007873950_centos_mysql_python_python_setuptools_zlib.txt |
Q:
Running pyflakes remotely with flymake and tramp in emacs?
I'm trying to use flymake to run pyflakes, as suggested here
This works fine for local files, and almost works with remote files with a bit of tweaking, but I'm left with a problem where flymake/pyflakes 'modifies' the buffer when it runs (although nothing... | Running pyflakes remotely with flymake and tramp in emacs? | I'm trying to use flymake to run pyflakes, as suggested here
This works fine for local files, and almost works with remote files with a bit of tweaking, but I'm left with a problem where flymake/pyflakes 'modifies' the buffer when it runs (although nothing actually seems to change), which renders it a bit useless in pr... | [
"You need to tell flymake to create it's copy of the buffer somewhere locally, I prefer using the $TMP directory since this also allows me to use tramp on files in directories I don't have write permissions to.\nYou may want to checkout my fork of flymake-python since it does all this.\n",
"I have this fixed in m... | [
9,
6
] | [] | [] | [
"emacs",
"flymake",
"pyflakes",
"python",
"tramp"
] | stackoverflow_0003145746_emacs_flymake_pyflakes_python_tramp.txt |
Q:
Paramiko hangs while executing a large wget command
Hi I am having problems executing a command that performs a wget of a 100mb file over a Ubuntu 10 server. Shorter commands work fine except for this. The below class contains how I use paramiko and my different tries of overcoming this problem (see the different ... | Paramiko hangs while executing a large wget command | Hi I am having problems executing a command that performs a wget of a 100mb file over a Ubuntu 10 server. Shorter commands work fine except for this. The below class contains how I use paramiko and my different tries of overcoming this problem (see the different run or exec methods). In the case of exec_cmd the executi... | [
"I had the same problem, my python script hung when the shell script I was running on a remote ssh client, did a wget command on a 400Mb file.\nI found that adding a time-out to the wget command fixed the problem.\nOriginally I had:\nwget http://blah:8888/file.zip\nnow with this:\nwget -q -T90 http://blah:8888/file... | [
3,
2
] | [] | [] | [
"linux",
"paramiko",
"python",
"ssh"
] | stackoverflow_0007630674_linux_paramiko_python_ssh.txt |
Q:
py-appscript expects arguments
I want to make a Python script to control VLC. VLC can be controlled through AppleScript and by using py-appscript I can run AppleScript code from Python.
Using AppleScript I can play/pause VLC by
tell application "VLC" to play
This equals to the following in py-appscript
app('VLC')... | py-appscript expects arguments | I want to make a Python script to control VLC. VLC can be controlled through AppleScript and by using py-appscript I can run AppleScript code from Python.
Using AppleScript I can play/pause VLC by
tell application "VLC" to play
This equals to the following in py-appscript
app('VLC').play()
I should also be able to sk... | [
"From the appscript documentation:\n\nNames that match Python keywords or names reserved by appscript have an underscore appended. \n\nAs next is a reserved keyword, you can fix this by running\napp('VLC').next_()\n\n"
] | [
2
] | [] | [] | [
"arguments",
"python",
"sourceforge_appscript",
"vlc"
] | stackoverflow_0007874976_arguments_python_sourceforge_appscript_vlc.txt |
Q:
Why am i getting an error: "buffsize musth be an integer" for mv shell command
Why am i getting an error: "buffsize musth be an integer"
afer this line:
pid2 = subprocess.Popen(["mv"],glob.glob(os.path.basename(filename)+'[0-9]*'),folder);
It is a simply mv command with a blog shell expansion .
I want sth like mv... | Why am i getting an error: "buffsize musth be an integer" for mv shell command | Why am i getting an error: "buffsize musth be an integer"
afer this line:
pid2 = subprocess.Popen(["mv"],glob.glob(os.path.basename(filename)+'[0-9]*'),folder);
It is a simply mv command with a blog shell expansion .
I want sth like mv filename[0-9]* folder
| [
"First of all, it's Python, so you don't need a semi-colon at the end of a line. Then, what you want is to supply one argument, i.e.\npid2 = subprocess.Popen([\"mv\"] +\n glob.glob(os.path.basename(filename)+'[0-9]*') +\n [folder])\n\nOtherwise, you're specifying the re... | [
3,
0
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0007875597_python_shell.txt |
Q:
Python/Numpy - Extract a 2-d Sub-array from a 2-d array using variables
Ok, So I have a 2-d array of data which has the shape(23025, 1000), it's called 'allfiles'.
I need to go through the array 50 columns at a time and extract them to a sub-array for manipulation. The problem is when i address the array using the... | Python/Numpy - Extract a 2-d Sub-array from a 2-d array using variables | Ok, So I have a 2-d array of data which has the shape(23025, 1000), it's called 'allfiles'.
I need to go through the array 50 columns at a time and extract them to a sub-array for manipulation. The problem is when i address the array using the code below, it doesn't seem to recognize the variables (a and b). the code i... | [
"You are getting i from the loop but don't use it.\nq = 50\n\nfor start in xrange(0, allfiles.shape[1], q):\n data = allfiles[:,start:start+q]\n ...\n\n"
] | [
2
] | [] | [] | [
"arrays",
"numpy",
"python",
"variables"
] | stackoverflow_0007875643_arrays_numpy_python_variables.txt |
Q:
WTForms syntax when using Flask and Flask-MongoAlchemy
I am testing out Python framework Flask and Flask-MongoAlchemy with MongoDB (of course). As I'm building multiple documents in my test app, I like to get the forms validated us WTForms.
Can anyone share with me an example on how to create the object referenc... | WTForms syntax when using Flask and Flask-MongoAlchemy | I am testing out Python framework Flask and Flask-MongoAlchemy with MongoDB (of course). As I'm building multiple documents in my test app, I like to get the forms validated us WTForms.
Can anyone share with me an example on how to create the object references in a SelectField()?
class Parent(db.Document):
title ... | [
"It's documented in WTForms documentation of the SelectField quoted here for convenience:\n\nSelect fields keep a choices property which is a sequence of (value,\n label) pairs.\n\nI'm not sure about form.parent.choices syntax but the code looks like:\nform.parent.choices = [(1, 'parent name 1'), (2, 'parent name ... | [
1
] | [] | [] | [
"flask",
"mongodb",
"python",
"wtforms"
] | stackoverflow_0007856949_flask_mongodb_python_wtforms.txt |
Q:
How do I add a list of dictionaries to another list of dictionaries?
I'm using a for loop to add a dictionary to a list of dictionaries (which I'm calling data_file), using data_file.append()
It works fine :) But then later I try to add some more dictionaries to data_file in another for loop and I use data_file.ap... | How do I add a list of dictionaries to another list of dictionaries? | I'm using a for loop to add a dictionary to a list of dictionaries (which I'm calling data_file), using data_file.append()
It works fine :) But then later I try to add some more dictionaries to data_file in another for loop and I use data_file.append() again and it doesn't work. It doesn't add those dictionaries to dat... | [
"Here's your problem:\nopen_file = csv.DictReader(open(travel))\ngenerators.append(open_file) \n\ntravel_generators = generators[:]\nmassage_generators = generators[:]\n\nYour travel_generators and massage_generators lists are using the same open file to iterate over and get data; the problem with that is once t... | [
1,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0007875051_dictionary_list_python.txt |
Q:
Handling variables in function with parallel spawning in Python
I have a Monte Carlo simulator that has a calculation function it calls many (millions or more) times in a loop. In order to speed this up, I would like split it into multiple parallel thread calls to the simulator. ie. If I want a to run it a tota... | Handling variables in function with parallel spawning in Python | I have a Monte Carlo simulator that has a calculation function it calls many (millions or more) times in a loop. In order to speed this up, I would like split it into multiple parallel thread calls to the simulator. ie. If I want a to run it a total of 1 million times, split it up into maybe 4 - 250,000 runs all goi... | [
"If your code is pure Python, and you are using CPython, threading likely won't speed up your code due to the global interpreter lock. What you are probably looking for is the multiprocessing module, specifically its Pool.map() method.\nSince using mulitprocessing means using separate processes instead of just sep... | [
2
] | [] | [] | [
"montecarlo",
"parallel_processing",
"python",
"simulation"
] | stackoverflow_0007876039_montecarlo_parallel_processing_python_simulation.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.