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:
How to pass multiple arguments in command line using python
(My Code):
import csv
import re
import string
import sys
import fileinput
import os
import random
import glob
import getopt
def getSymbols(filename):
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
... | How to pass multiple arguments in command line using python | (My Code):
import csv
import re
import string
import sys
import fileinput
import os
import random
import glob
import getopt
def getSymbols(filename):
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line,
f.close()
if len(sys.argv) < 2:
... | [
"The files are at argv[1], argv[2], and so on. So just take a slice.\nfor filename in sys.argv[1:]:\n readfile(filename)\n\n",
"you can use\n len(sys.argv)\nto count number of arguments and use them as sys.argv[1], sys.argv[2] etc.\n",
"You may find that the fileinput module is what you want for your pro... | [
11,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0006149498_python.txt |
Q:
Infinite loop in simulation
I'm starting out in python.. The details I have written in the below.. It goes to an infinite loop and give me an error when I try to call the function inside itself.. Is this kind of recursion not allowed ?
Posting code below.. Thanks for all your help :)
The program assumes that we ha... | Infinite loop in simulation | I'm starting out in python.. The details I have written in the below.. It goes to an infinite loop and give me an error when I try to call the function inside itself.. Is this kind of recursion not allowed ?
Posting code below.. Thanks for all your help :)
The program assumes that we have 100 passengers boarding a plan... | [
"Recursion, while allowed, isn't your best first choice for this.\nPython enforces an upper bound on recursive functions. It appears that your loop exceeds the upper bound.\nYou really want some kind of while loop in assign.\ndef assign(ini,mov): \n \"\"\"The first is passenger no. and the second is the final... | [
0,
0
] | [] | [] | [
"infinite_loop",
"python",
"recursion"
] | stackoverflow_0006153611_infinite_loop_python_recursion.txt |
Q:
Django Password Reset - DoesNotExist exception
The password_reset page of my Django site is causing a DoesNotExist exception after an email address is entered and the button pressed.
The four URLs required for the password reset function are in (the main project) urls.py as:
(r'^password_reset/$', 'appname.views.c... | Django Password Reset - DoesNotExist exception | The password_reset page of my Django site is causing a DoesNotExist exception after an email address is entered and the button pressed.
The four URLs required for the password reset function are in (the main project) urls.py as:
(r'^password_reset/$', 'appname.views.cust_password_reset'),
(r'^password_reset/done/', 'ap... | [
"That error, \"Site matching query does not exist\" means that the SITE_ID in settings.py does not match up with an actual Site object in the database. Check the id attribute for your site, and make sure it's the same as SITE_ID.\n"
] | [
2
] | [] | [] | [
"django",
"django_authentication",
"python"
] | stackoverflow_0006153603_django_django_authentication_python.txt |
Q:
How to upload current date/time into App Engine with Bulkloader tool?
How can I add a last modified time property to my entity kind that gets updated during a bulk upload?
I'm currently using appcfg upload_data to upload a csv up to my high replication datastore. I plan to have this as a cron job to do a one-way s... | How to upload current date/time into App Engine with Bulkloader tool? | How can I add a last modified time property to my entity kind that gets updated during a bulk upload?
I'm currently using appcfg upload_data to upload a csv up to my high replication datastore. I plan to have this as a cron job to do a one-way sync from our internal database to datastore. In order to account for stale ... | [
"I would do this:\n\nAdd a property to my bulkuploader.yaml\n for the modified time and use a import\n transform to get the date?\n\n"
] | [
1
] | [] | [] | [
"bulkloader",
"google_app_engine",
"python"
] | stackoverflow_0006149263_bulkloader_google_app_engine_python.txt |
Q:
Time complexity of accessing an element in a tuple
There is similar question about hash (dictionaries) and lists, also there is a good piece of info here: http://wiki.python.org/moin/TimeComplexity
But I didn't find anything about tuples.
The access time for
data_structure[i]
for a linked list is in general O(n) ... | Time complexity of accessing an element in a tuple | There is similar question about hash (dictionaries) and lists, also there is a good piece of info here: http://wiki.python.org/moin/TimeComplexity
But I didn't find anything about tuples.
The access time for
data_structure[i]
for a linked list is in general O(n)
for dictionary is ~ O(1)
What about tuple?
Is it O(n)... | [
"It's O(1) for both list and tuple. They are both morally equivalent to an integer indexed array.\n",
"Lists and tuples are indexable in the exact same way arrays are in other languages.\nA simplified explanation is that space is allocated for references to objects, those references take up a uniform amount of sp... | [
11,
4,
3,
1
] | [] | [] | [
"complexity_theory",
"python",
"tuples"
] | stackoverflow_0006153348_complexity_theory_python_tuples.txt |
Q:
How to alternate around directories using subprocess
I want to change the current directory using subprocess.
For example:
import os, sys, subprocess
os.environ['a'] = '/home'
os.environ['b'] = '/'
subprocess.call('cd $a', shell=True)
subprocess.call('ls', shell=True)
subprocess.call('cd $b', shell=True)
subpro... | How to alternate around directories using subprocess | I want to change the current directory using subprocess.
For example:
import os, sys, subprocess
os.environ['a'] = '/home'
os.environ['b'] = '/'
subprocess.call('cd $a', shell=True)
subprocess.call('ls', shell=True)
subprocess.call('cd $b', shell=True)
subprocess.call('ls', shell=True)
I think that this should work... | [
"To change the directory just use os.chdir() instead.\nYou can also execute commands in specific directoeies by running subprocess.Popen(...) - it has an optional parameter cwd=None. Just use it to specify the working directory.\nAlso, you could take a look at a small module I wrote that completes some missing func... | [
13
] | [] | [] | [
"python",
"subprocess",
"unix"
] | stackoverflow_0006154218_python_subprocess_unix.txt |
Q:
Image not found error when importing QtGui from PyQt4
I have installed ActivePython 2.7 on Mac OS X 10.5. The main reason for this is to use pypm, the package manager. However, after installing ActivePython and setting up my .bash_profile file to use that version of Python, I encounter a lot of problems with the p... | Image not found error when importing QtGui from PyQt4 | I have installed ActivePython 2.7 on Mac OS X 10.5. The main reason for this is to use pypm, the package manager. However, after installing ActivePython and setting up my .bash_profile file to use that version of Python, I encounter a lot of problems with the pypm-installed libraries. To install all of these modules, I... | [
"Make sure python and qt have same architecture (32bit vs 64bit)\nfor mathplot looks like a different g++ used to compile python and mathplot\nhave you tried with stock osx python?\n"
] | [
0
] | [] | [] | [
"macos",
"pypm",
"pyqt4",
"python"
] | stackoverflow_0006146834_macos_pypm_pyqt4_python.txt |
Q:
Sending SMS using Python
I am trying to send sms using python and a GSM modem connected to my local machine, I have successfully sent the SMS using AT commands but now I have a technical problem for which I need help, the server of my website is located in United States while I live in Australia, so if I want to u... | Sending SMS using Python | I am trying to send sms using python and a GSM modem connected to my local machine, I have successfully sent the SMS using AT commands but now I have a technical problem for which I need help, the server of my website is located in United States while I live in Australia, so if I want to use the SMS feature on actual s... | [
"A practical solution would be to connect to SMS gateway service instead of implementing your own service. Nowadays they are really cheap or even free. \n"
] | [
2
] | [] | [] | [
"at_command",
"gsm",
"python"
] | stackoverflow_0006154409_at_command_gsm_python.txt |
Q:
Receive multiple values via pyserial and display in Python GUI
I am trying to receive data using serial communication in Python, which I can do, but I need to improve my code.
I am sending a "packet" from Arduino that is in the form of "&4,25/n" with the key factors being the values in the positions of "4" and "25... | Receive multiple values via pyserial and display in Python GUI | I am trying to receive data using serial communication in Python, which I can do, but I need to improve my code.
I am sending a "packet" from Arduino that is in the form of "&4,25/n" with the key factors being the values in the positions of "4" and "25". In this packet, I have the "&" as a startbyte, and the new line ... | [
"Try splitting the text:\nsplit_data = ping_data.split(',')\n\nsplit_data will contain ['4', '25'] for the example above.\nYou can then access the data like so:\nfirst_val = split_data[0]\nsecond_val = split_data[1]\n\n"
] | [
3
] | [] | [] | [
"arduino",
"pyserial",
"python",
"serial_port"
] | stackoverflow_0006154341_arduino_pyserial_python_serial_port.txt |
Q:
How to run a code with different set of parameters without waiting for a code to execute with one parameter and then entering the next one
My python program takes two input parameters from the command line for execution eg (maxt, 30days). The execution time of this program is approximately 10 mins. I want to run t... | How to run a code with different set of parameters without waiting for a code to execute with one parameter and then entering the next one | My python program takes two input parameters from the command line for execution eg (maxt, 30days). The execution time of this program is approximately 10 mins. I want to run the program three time ie first with maxt and 30 days, second with maxt and 14 days and third with maxt and 7 days. How could run the code three ... | [
"If you are on a unix command line:\n$ yourprogram maxt 30days &\n$ yourprogram maxt 14days &\n$ yourprogram maxt 7days &\n\nthis starts your programs in the background in parallell.\n",
"It sounds like what you want is a shell script, like so:\n#! /bin/sh\n\nyourprogram maxt 30days\nyourprogram maxt 14days\nyour... | [
2,
0,
0
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0006154531_python_shell.txt |
Q:
function inside list comprehension - is it evaluated multiple times
Which one's a better way of doing list comprehension in python (in terms of computation time & cpu cycles).
In example (1) is the value f(r) evaluated in each iteration or is it evaluated once and cached ?
y = [x*f(r) for x in xlist]
c = f(r)
y... | function inside list comprehension - is it evaluated multiple times | Which one's a better way of doing list comprehension in python (in terms of computation time & cpu cycles).
In example (1) is the value f(r) evaluated in each iteration or is it evaluated once and cached ?
y = [x*f(r) for x in xlist]
c = f(r)
y = [x*c for x in xlist]
where
def f(r):
... some arbitrary function ... | [
"It evaluates for every iteration. Look at this:\n>>> def f():\n... print(\"func\")\n... \n>>> [f() for i in range(4)]\nfunc\nfunc\nfunc\nfunc\n[None, None, None, None]\n\nAs you say, if f() has no side effects, storing the return value on a variable and using that variable instead is a lot faster solution.\n",... | [
12,
11,
10,
2,
1,
1,
0
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0006155008_list_comprehension_python.txt |
Q:
moving from one csv worksheet to the next in a python script
I've been using excel to create .csv workesheets that I'd like to parse using python. Each worksheet is named after a shop (e.g worksheet 1: "Waitrose", worksheet 2: "Tesco", worksheet 3: "Asda") and contains a list of products (column 1) and their assoc... | moving from one csv worksheet to the next in a python script | I've been using excel to create .csv workesheets that I'd like to parse using python. Each worksheet is named after a shop (e.g worksheet 1: "Waitrose", worksheet 2: "Tesco", worksheet 3: "Asda") and contains a list of products (column 1) and their associated prices (column 2). I've written a python script that can acc... | [
"Each worksheet must be saved as a separate CSV. Since you are already able to parse a single CSV I'll concentrate on handling the individual files. Once you have a CSV for each Excel worksheet, you can iterate through each .csv file in a directory using the glob module. With glob.glob() you can use wildcards in... | [
3,
1
] | [] | [] | [
"applescript",
"csv",
"excel",
"python",
"worksheet"
] | stackoverflow_0006152925_applescript_csv_excel_python_worksheet.txt |
Q:
Need to create a list of sets, from a list of sets whose members may be connected
I'm dealing with polygonal data in realtime here, but the problems quite simple.
I have a huge list containing thousands of sets of polygon Indecies (Integers) and I need to simplify the list as "fast" as possible into a list of sets... | Need to create a list of sets, from a list of sets whose members may be connected | I'm dealing with polygonal data in realtime here, but the problems quite simple.
I have a huge list containing thousands of sets of polygon Indecies (Integers) and I need to simplify the list as "fast" as possible into a list of sets of "connected" Indecies.
i.e. Any sets containing integers that are also in another se... | [
"It's hard to tell the performance without a sufficiently large set, but here is some basic code to start from:\nwhile True:\n merged_one = False\n supersets = [listOfSets[0]]\n\n for s in listOfSets[1:]:\n in_super_set = False\n for ss in supersets:\n if s & ss:\n ss... | [
4,
2,
1,
0,
0
] | [] | [] | [
"api",
"maya",
"python"
] | stackoverflow_0006144262_api_maya_python.txt |
Q:
Crop image from django template
Is there any way to crop an image from django template? I am not saving the image anywhere it is URL example.
A:
Check this: http://thumbnail.sorl.net/examples.html#template-examples
A:
Or check http://django-filebrowser.readthedocs.org/en/latest/versions.html#image-versions
| Crop image from django template | Is there any way to crop an image from django template? I am not saving the image anywhere it is URL example.
| [
"Check this: http://thumbnail.sorl.net/examples.html#template-examples\n",
"Or check http://django-filebrowser.readthedocs.org/en/latest/versions.html#image-versions\n"
] | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006155226_django_python.txt |
Q:
Pydev won't Resolve Dynamically created Attributes
Greetings SO,
I have a weird problem that I don't seem to be able to solve:
I am working with the pydev plugin with eclipse Helios on Windows XP (if it matters).
I have a module which contains a class. The __init__ of this class takes a parameter which determines ... | Pydev won't Resolve Dynamically created Attributes | Greetings SO,
I have a weird problem that I don't seem to be able to solve:
I am working with the pydev plugin with eclipse Helios on Windows XP (if it matters).
I have a module which contains a class. The __init__ of this class takes a parameter which determines the set of attributes that a method of this class should... | [
"This is a general problem which all dynamic language IDEs suffer. Pydev has no way of knowing what attributes Car.__init__ sets on instances of Car, without executing your code. If you use class variables for the attributes you set in __init__, Pydev should be able to offer autocomplete suggstion.\nclass Car(objec... | [
1,
0
] | [] | [] | [
"dynamic",
"eclipse",
"pydev",
"python",
"resolve"
] | stackoverflow_0006048250_dynamic_eclipse_pydev_python_resolve.txt |
Q:
How to call SIOCSIFHWADDR ioctl to change MAC address in Python?
So I have Python code which creates a Linux TAP interface, but it always comes up with a random, auto-generated MAC address. To simplify testing I would like to manually assign the interface a MAC address after it has been initialized. I know I can d... | How to call SIOCSIFHWADDR ioctl to change MAC address in Python? | So I have Python code which creates a Linux TAP interface, but it always comes up with a random, auto-generated MAC address. To simplify testing I would like to manually assign the interface a MAC address after it has been initialized. I know I can do this with the SIOCSIFHWADDR ioctl and struct ifreq, but I had a few ... | [
"from: http://nullege.com/codes/show/src@p@y@pynetlinux-1.0@pynetlinux@ifconfig.py\ndef set_mac(self, newmac):\n ''' Set the device's mac address. Device must be down for this to\n succeed. '''\n macbytes = [int(i, 16) for i in newmac.split(':')]\n ifreq = struct.pack('16sH6B8x', self.name, AF_UNIX,... | [
6,
0,
0
] | [] | [] | [
"c",
"linux",
"python"
] | stackoverflow_0006154846_c_linux_python.txt |
Q:
Sort a numpy array by another array, along a particular axis
Similar to this answer, I have a pair of 3D numpy arrays, a and b, and I want to sort the entries of b by the values of a. Unlike this answer, I want to sort only along one axis of the arrays.
My naive reading of the numpy.argsort() documentation:
Return... | Sort a numpy array by another array, along a particular axis | Similar to this answer, I have a pair of 3D numpy arrays, a and b, and I want to sort the entries of b by the values of a. Unlike this answer, I want to sort only along one axis of the arrays.
My naive reading of the numpy.argsort() documentation:
Returns
-------
index_array : ndarray, int
Array of indices that sor... | [
"You still have to supply indices for the other two dimensions for this to work correctly. \n>>> a = numpy.zeros((3, 3, 3))\n>>> a += numpy.array((1, 3, 2)).reshape((3, 1, 1))\n>>> b = numpy.arange(3*3*3).reshape((3, 3, 3))\n>>> sort_indices = numpy.argsort(a, axis=0)\n>>> static_indices = numpy.indices((3, 3, 3))\... | [
22
] | [] | [] | [
"multidimensional_array",
"numpy",
"python",
"sorting"
] | stackoverflow_0006155649_multidimensional_array_numpy_python_sorting.txt |
Q:
PyQt - resize parent widget to its child
Just a main widget with a tabs widget in it.
The problem is - when I run it, only part of tabs are shown (as shown on attached picture). So, you need to resize, or scroll tabs to get for the last.
How can I set it so that window shows all tabs from the start?
import sys
f... | PyQt - resize parent widget to its child | Just a main widget with a tabs widget in it.
The problem is - when I run it, only part of tabs are shown (as shown on attached picture). So, you need to resize, or scroll tabs to get for the last.
How can I set it so that window shows all tabs from the start?
import sys
from PyQt4.QtGui import *
class MainWindow(QWi... | [
"You can use QTabWidget.setUsesScrollButtons(bool) \nimport sys\nfrom PyQt4.QtGui import *\n\nclass MainWindow(QWidget):\n def __init__(self, parent=None):\n QWidget.__init__(self, parent)\n\n # making tabs\n tabs = QTabWidget()\n tabs.setUsesScrollButtons(False) #here is\n\n t... | [
3
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0006155705_pyqt_python.txt |
Q:
Webpage redirect to the main page with CGI Python
As my first web app I developed a very simple survey. Random questions are being asked from the user anytime the page refreshes. The answer is sent to a cgi script using post to save the answers to the database.
However, when the user presses the submit button it ... | Webpage redirect to the main page with CGI Python | As my first web app I developed a very simple survey. Random questions are being asked from the user anytime the page refreshes. The answer is sent to a cgi script using post to save the answers to the database.
However, when the user presses the submit button it automatically goes to the page which is responsible for... | [
"You want to implement this: https://en.wikipedia.org/wiki/Post/Redirect/Get\nIt's much simpler than it sounds. The CGI script that receives the POST must simply produce the following output:\nStatus: 303 See other\nLocation: http://lalala.com/themainpage\n\n",
"You can also send a HTTP header from your processin... | [
10,
8,
1
] | [] | [] | [
"cgi",
"forms",
"html",
"python"
] | stackoverflow_0006122957_cgi_forms_html_python.txt |
Q:
Traversing a diagram that represents real operations
Greetings,
Can anyone please tell me what algorithm is used for traversing a directed acyclic graph/ diagram like this :
Ex.
Diagram nodes : A, B, C, D1, D2, D3, E
Diagram edges : A → B, B → C, C → D1, C → D2, C → D3, D1 → E, D2 → E, D3 → E
The trave... | Traversing a diagram that represents real operations | Greetings,
Can anyone please tell me what algorithm is used for traversing a directed acyclic graph/ diagram like this :
Ex.
Diagram nodes : A, B, C, D1, D2, D3, E
Diagram edges : A → B, B → C, C → D1, C → D2, C → D3, D1 → E, D2 → E, D3 → E
The traversal is like this :
A → B → C → D1, then C → D2, then C →... | [
"A topological sort will give you the order that you need to perform the operations in given the edges.\n"
] | [
5
] | [] | [] | [
"diagram",
"graph",
"python"
] | stackoverflow_0006156392_diagram_graph_python.txt |
Q:
Why is my basic PyGame module so slow?
I've planning on writing a code in Pygame and I was just getting started with the basics and found that the executing code was really slow. When I press a key it takes a while for it to print it in the terminal (there doesn't seem to be any pattern to it).
I'm running Python ... | Why is my basic PyGame module so slow? | I've planning on writing a code in Pygame and I was just getting started with the basics and found that the executing code was really slow. When I press a key it takes a while for it to print it in the terminal (there doesn't seem to be any pattern to it).
I'm running Python 2.6, I downgraded after coming across this p... | [
"pyGame is based on SDL which is internally based on threads.\nWhen you have threading, print messages are basically a no-no. Because often times because of the scheduler slices (which are large in SDL), the print messages get delayed. Its not that pygame is slow (it is some situations, but, not in this one), its j... | [
3
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0006156485_pygame_python.txt |
Q:
Python client support for running Hive on top of Amazon EMR
I've noticed that neither mrjob nor boto supports a Python interface to submit and run Hive jobs on Amazon Elastic MapReduce (EMR). Are there any other Python client libraries that supports running Hive on EMR?
A:
With boto you can do something like t... | Python client support for running Hive on top of Amazon EMR | I've noticed that neither mrjob nor boto supports a Python interface to submit and run Hive jobs on Amazon Elastic MapReduce (EMR). Are there any other Python client libraries that supports running Hive on EMR?
| [
"With boto you can do something like this:\nargs1 = [u's3://us-east-1.elasticmapreduce/libs/hive/hive-script',\n u'--base-path',\n u's3://us-east-1.elasticmapreduce/libs/hive/',\n u'--install-hive',\n u'--hive-versions',\n u'0.7']\nargs2 = [u's3://us-east-1.elasticmapreduce/l... | [
9
] | [] | [] | [
"boto",
"elastic_map_reduce",
"hive",
"python"
] | stackoverflow_0006103816_boto_elastic_map_reduce_hive_python.txt |
Q:
Why does re.findall() give me different results than re.finditer() in Python?
I wrote up this regular expression:
p = re.compile(r'''
\[\[ #the first [[
[^:]*? #no :s are allowed
.*? #a bunch of chars
(
\| #either go until a |
|\]\] #or the last ]]
)
... | Why does re.findall() give me different results than re.finditer() in Python? | I wrote up this regular expression:
p = re.compile(r'''
\[\[ #the first [[
[^:]*? #no :s are allowed
.*? #a bunch of chars
(
\| #either go until a |
|\]\] #or the last ]]
)
''', re.VERBOSE)
I want to use re.findall to get all the matching sections ... | [
"Findall returns a list of matching groups. The parantheses in your regex defines a group that findall thinks you want, but you don't want groups. (?:...) is a non-capturing paranthesis. Change your regex to:\n'''\n\\[\\[ #the first [[\n[^:]*? #no :s are allowed\n.*? #a bunch of c... | [
7,
3,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006157671_python_regex.txt |
Q:
Advice on writing to a log file with python
I have some code that will need to write about 20 bytes of data every 10 seconds.
I'm on Windows 7 using python 2.7
You guys recommend any 'least strain to the os/hard drive' way to do this?
I was thinking about opening and closing the same file very 10 seconds:
f = open... | Advice on writing to a log file with python | I have some code that will need to write about 20 bytes of data every 10 seconds.
I'm on Windows 7 using python 2.7
You guys recommend any 'least strain to the os/hard drive' way to do this?
I was thinking about opening and closing the same file very 10 seconds:
f = open('log_file.txt', 'w')
f.write(information)
f.clos... | [
"As expected, python comes included with a great tool for this, have a look at the logging module\n",
"Use the logging framework. This is exactly what it is designed to do.\nEdit: Balls, beaten to it :).\n",
"Don't worry about \"frying\" your hard drive - 20 bytes every 10 seconds is a small fraction of the dat... | [
13,
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0006157781_python.txt |
Q:
Using datetime.strptime to get date from string using python
i have a bunch of strings like this:
s = 3851102123
objective would be to extract the date from it
in example:
85 is year
11 is month
02 is day
basically string indexes 1,2 = year, 3,4 = month, 5,6 = day
rest can be discarded, this is what i came up wit... | Using datetime.strptime to get date from string using python | i have a bunch of strings like this:
s = 3851102123
objective would be to extract the date from it
in example:
85 is year
11 is month
02 is day
basically string indexes 1,2 = year, 3,4 = month, 5,6 = day
rest can be discarded, this is what i came up with:
>> x = datetime.strptime("3851102123", ??)
How would one extrac... | [
"I am not sure if you can do it like that, as strptime will expect a format string and the format string does not allow for variable fields (as you'll need if you want the format to ignore the first number of the string)\nYou could do something like this:\ndatetime.strptime(the_string[1:7], \"%y%m%d\").strftime(\"%... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0006157845_python.txt |
Q:
Python efficiency: lists vs. tuples
I have a medium-amount of base objects.
These base objects will be put in collections, and these collections will be munged around: sorted, truncated, etc.
Unfortunately, the n is large enough that memory consumption is slightly worrisome, and speed is getting concerning.
My un... | Python efficiency: lists vs. tuples | I have a medium-amount of base objects.
These base objects will be put in collections, and these collections will be munged around: sorted, truncated, etc.
Unfortunately, the n is large enough that memory consumption is slightly worrisome, and speed is getting concerning.
My understanding is that tuples are slightly m... | [
"If you have a tuple and a list with the same elements, the tuple takes less space. Since tuples are immutable, you can't sort them, add to them, etc. I recommend watching this talk by Alex Gaynor for a quick intro on when to choose what datastructure in Python.\nUPDATE: Thinking about it some more, you may want to... | [
16,
9,
4,
3,
2,
1,
1
] | [] | [] | [
"optimization",
"python",
"python_2.6",
"python_2.7"
] | stackoverflow_0006063494_optimization_python_python_2.6_python_2.7.txt |
Q:
PyGame bogging down linux?
When I run my pygame code it bogs down the system. PyGame becomes unresponsive and it slows down Ubuntu so much that I've had to force a shut down twice.
I posted a very similar question here:
Why is my basic PyGame module so slow?
but I decided to rephrase it because when I asked the o... | PyGame bogging down linux? | When I run my pygame code it bogs down the system. PyGame becomes unresponsive and it slows down Ubuntu so much that I've had to force a shut down twice.
I posted a very similar question here:
Why is my basic PyGame module so slow?
but I decided to rephrase it because when I asked the original question I wasn't aware ... | [
"You should limit the fps, you can use clock.tick for that\nwhile true:\n for event in pygame.event.get():\n #manage your events\n #update your sprites\n screen.blit(...) #draw to screen\n pygame.display.flip()\n clock.tick(30)\n\n",
"If you decide to use a delay like suggested in the answer... | [
1,
1
] | [] | [] | [
"memory",
"pygame",
"python",
"ubuntu"
] | stackoverflow_0006158213_memory_pygame_python_ubuntu.txt |
Q:
Using pip to install single-file python modules
I'm wondering if there's a way to "install" single-file python modules using pip (i.e. just have pip download the specified version of the file and copy it to site-packages).
I have a Django project that uses several 3rd-party modules which aren't proper distribution... | Using pip to install single-file python modules | I'm wondering if there's a way to "install" single-file python modules using pip (i.e. just have pip download the specified version of the file and copy it to site-packages).
I have a Django project that uses several 3rd-party modules which aren't proper distributions (django-thumbs and a couple others) and I want to p... | [
"pip requires a valid setup.py to install a python package. By definition every python package has a setup.py... What you are trying to install isn't a package but rather a single file module... what's wrong with doing something like:\ngit clone git+https://github.com/path/to/file.git /path/to/python/install/lib\n\... | [
2
] | [] | [] | [
"pip",
"python"
] | stackoverflow_0006158191_pip_python.txt |
Q:
Marshaling and/or saving Objects with/without their current state to file and reloading them in Python
Hi
Is there any known method, through API or clean programming practice to save an object to a file and then load the object again for instance if: Object inst is an instance of class C
and it has variables V1 ... | Marshaling and/or saving Objects with/without their current state to file and reloading them in Python | Hi
Is there any known method, through API or clean programming practice to save an object to a file and then load the object again for instance if: Object inst is an instance of class C
and it has variables V1 and V2 which are currently initialized, can we save it to a file and read it back? Now what if we want to t... | [
"Use the pickle module or the (slightly) higher-level Shelve module\n"
] | [
1
] | [] | [] | [
"marshalling",
"python",
"saving_data"
] | stackoverflow_0006158564_marshalling_python_saving_data.txt |
Q:
Simple questions about txt file input and output with Python 2.6
this is my first post here to stackoverflow, and I am still just learning Python and programming in general. I'm working on some simple game logic, and I'm getting a little washed up on how Python handles file input/output.
What I'm trying to do is,... | Simple questions about txt file input and output with Python 2.6 | this is my first post here to stackoverflow, and I am still just learning Python and programming in general. I'm working on some simple game logic, and I'm getting a little washed up on how Python handles file input/output.
What I'm trying to do is, while my game is running, store a series of variables (all numeric, i... | [
"Does it have to be text? I'd use pickle if not\nhttp://docs.python.org/library/pickle.html\n",
"There are quite a few ways to do this. Do you want the file to be human-readable or human-writable? (Could encourage cheating if you do.)\nThe simplest thing that you could do which would work is to use the ConfigPars... | [
2,
0
] | [] | [] | [
"file_io",
"python",
"variables"
] | stackoverflow_0006158788_file_io_python_variables.txt |
Q:
In Tk with Python, how do I specify a Frame or Canvas to resize with my window?
I'm totally new to Tk and the Packing concept, so bear with me. Here is my code:
from Tkinter import *
class frm_main:
def __init__(self, parent):
self.frame = Frame(parent, bg="green") #green for testing
self.fra... | In Tk with Python, how do I specify a Frame or Canvas to resize with my window? | I'm totally new to Tk and the Packing concept, so bear with me. Here is my code:
from Tkinter import *
class frm_main:
def __init__(self, parent):
self.frame = Frame(parent, bg="green") #green for testing
self.frame.pack(fill="both")
self.canvas = Canvas(self.frame, bg="black", width=1000... | [
"Set expand = 1 in the calls to pack() to make the widgets adjust when their containers are resized.\nself.frame.pack(fill = \"both\", expand = 1)\n...\nself.canvas.pack(fill = \"both\", expand = 1)\n\nYou can use a frame to group a set of widgets or add an extra border, but in this example there is no need for the... | [
5
] | [] | [] | [
"anchor",
"packing",
"python",
"tkinter"
] | stackoverflow_0006158604_anchor_packing_python_tkinter.txt |
Q:
Why is sys.path initialized differently during startup than when run from bash, for Python embedded in Apache
I am using Python embedded in Apache using modwsgi, and I am finding that the sys.path does not get initialized correctly when Apache is started from the rc2.d startup folder than when run from the shell. ... | Why is sys.path initialized differently during startup than when run from bash, for Python embedded in Apache | I am using Python embedded in Apache using modwsgi, and I am finding that the sys.path does not get initialized correctly when Apache is started from the rc2.d startup folder than when run from the shell.
The versions:
Ubuntu Lucid 10.04
Apache 2.2
Python 2.6
mod_wsgi 3.3
Firstly, I am testing the initialization using... | [
"You're running as a different user. Bash (and your other login scripts) set some of your path variables when you run as your standard user that may not get set when running as the apache user on startup. \nApache is initializing correctly. You just need to be explicit about which paths you want to include, if you ... | [
0
] | [] | [] | [
"apache",
"mod_wsgi",
"python"
] | stackoverflow_0006159097_apache_mod_wsgi_python.txt |
Q:
Python on the web: executing code as it's processed?
I made a python application that I'd like to deploy to the web. I'm on a Mac, so I enabled the web server and dropped it in my cgi-bin, and it works fine. The problem is, the application does some intensive computations, and I would really like to let the user... | Python on the web: executing code as it's processed? | I made a python application that I'd like to deploy to the web. I'm on a Mac, so I enabled the web server and dropped it in my cgi-bin, and it works fine. The problem is, the application does some intensive computations, and I would really like to let the user know what's going on while it's executing.
Even though i ... | [
"Instead of 'print', you might want to try\nsys.stdout.write('something something something')\nsys.stdout.flush()\n\nThat'll ensure that the web server isn't waiting for a buffer to fill up.\n",
"If sys.stdout.flush() didn't do the trick, the problem is likely to be resolved by chunked-encoding transfer.\nTo give... | [
1,
1,
1
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0006147461_cgi_python.txt |
Q:
I need create a variable that is the GMT offset where it's 7:XX AM right now
I've been working on this for a bit and not seeing the answer quite yet. Essentially, I need to add a conditional depending on a GMT offset into a script. The GMT offset needs to be wherever in the world it is 7 AM at the time the script ... | I need create a variable that is the GMT offset where it's 7:XX AM right now | I've been working on this for a bit and not seeing the answer quite yet. Essentially, I need to add a conditional depending on a GMT offset into a script. The GMT offset needs to be wherever in the world it is 7 AM at the time the script runs.
In other words, if it's 7 AM in New York, I need to write a python script th... | [
"If it's 07:00 in New York, then it's 11:00 GMT. 7 - 11 = -4.\nIf it's 07:00 in Los Angeles, then it's 14:00 GMT. 7 - 14 = -7.\nSo take the current time in GMT, round it to the hour of your choice, and subtract from 7.\n[update]\nAh, right, there is no -15... But it all works mod 24. So take 7-time.gmtime().tm_... | [
1,
1
] | [] | [] | [
"python",
"time",
"timezone"
] | stackoverflow_0006159504_python_time_timezone.txt |
Q:
Amazon api not returning results aligned with the amazon website results
I'm using the python-amazon-product-api to create a search bar which will return results similar to the results returned on the amazon site. However, when I do an itemSearch, as follows, I get some results, but it only returns products which ... | Amazon api not returning results aligned with the amazon website results | I'm using the python-amazon-product-api to create a search bar which will return results similar to the results returned on the amazon site. However, when I do an itemSearch, as follows, I get some results, but it only returns products which are sold and shipped by amazon. I was wondering if anyone could help me fix th... | [
"Try to set the 'MerchantId' parameter to 'All':\nroot = api.item_search('All', Keywords=searchWord, ResponseGroup='Large', ItemPage=pageNo, MerchantId='All')\n\nIf you don't specify it, it will be defaulted to \"Amazon\", which is why you see only Amazon's products (please refer to the Item Search documentation fo... | [
1
] | [] | [] | [
"amazon",
"amazon_product_api",
"python"
] | stackoverflow_0006157990_amazon_amazon_product_api_python.txt |
Q:
Python: Best way to access variable from within a class instance?
I've got a class named Player and there will be 200-300 instances of this class. There is a function within this class called Move and this function requires knowledge of the map.
I also have a class named Map with 1-2 instances. What is the best wa... | Python: Best way to access variable from within a class instance? | I've got a class named Player and there will be 200-300 instances of this class. There is a function within this class called Move and this function requires knowledge of the map.
I also have a class named Map with 1-2 instances. What is the best way to feed an instance of Map into the Player instances?
I just ask beca... | [
"If you pass the Map to the Player at init this just passes a reference, not a copy. You will not create redundant instances of Map this way, and it's the best way to do it.\n",
"Nothing in Python is ever implicitly copied. Whenever you do x = y, whether that's a function call or a variable/element/attribute as... | [
1,
1
] | [] | [] | [
"class",
"oop",
"python",
"variables"
] | stackoverflow_0006159619_class_oop_python_variables.txt |
Q:
Module import works on interpreter but not on a script
i was beggining to follow a tutorial on elementtree in this site http://www.bigfatalien.com/?p=223 so as usual i typed the reference scripts on the interpreter and i went
import xml.etree.ElementTree as xml
And the interpreter run that command just fine and ... | Module import works on interpreter but not on a script | i was beggining to follow a tutorial on elementtree in this site http://www.bigfatalien.com/?p=223 so as usual i typed the reference scripts on the interpreter and i went
import xml.etree.ElementTree as xml
And the interpreter run that command just fine and using "xml" in the intrepreter with no problems my IDE even ... | [
"A really silly question: did you name your script file xml.py? If so, DON'T DO THAT ... import xml.anything will be looking in your script file! It's never a good idea to give a script file the same name as a module that you are going to import.\nUpdate Tracebacks are your friends. Lead to read them carefully. If ... | [
13,
1
] | [] | [] | [
"elementtree",
"import",
"interpreter",
"python"
] | stackoverflow_0006159523_elementtree_import_interpreter_python.txt |
Q:
Open multiple predefined text files in python
Hello I was just wondering if it was possible to open multiple predefined text files in python.
I have some code below (it doesn't work yet), and the first function has a parameter of categories, which are all text file names that are predefined below in a test case. ... | Open multiple predefined text files in python | Hello I was just wondering if it was possible to open multiple predefined text files in python.
I have some code below (it doesn't work yet), and the first function has a parameter of categories, which are all text file names that are predefined below in a test case. I need to try and open all of the text files as def... | [
"Use string interpolation or formatting to put the category into the filespec, and glob.glob() to resolve it.\n",
"Why are you reading the lines into a list, and then going over it after the fact?\nimport glob, itertools\n\ndef data_entry(categories):\n globs = [glob.iglob(category + \"*.txt\") for category in... | [
0,
0,
0
] | [] | [] | [
"mysql",
"python",
"sql",
"text"
] | stackoverflow_0006160081_mysql_python_sql_text.txt |
Q:
Python 2.7 OS X installer, mod_wsgi and Apache
The Python 2.6 OS X installer didn't support 64 bit architectures, necessitating some chicanery to get mod_wsgi, Python 2.6 and Apache2 working on 10.5.
However, the Python 2.7 OS X installer does build a 'fat' Python install, so I'd like to know if anyone's tried thi... | Python 2.7 OS X installer, mod_wsgi and Apache | The Python 2.6 OS X installer didn't support 64 bit architectures, necessitating some chicanery to get mod_wsgi, Python 2.6 and Apache2 working on 10.5.
However, the Python 2.7 OS X installer does build a 'fat' Python install, so I'd like to know if anyone's tried this setup before I ditch my current Python 2.6 local s... | [
"How to solve your problem:\n\nupgrade OS X to 10.6\ninstall macports and install any python distribution you like (you can have multiple installed)\n\nPS. I use Python 2.7 with mod_wsgi on Apache (64bit)\n"
] | [
1
] | [] | [] | [
"mod_wsgi",
"osx_leopard",
"python"
] | stackoverflow_0004028394_mod_wsgi_osx_leopard_python.txt |
Q:
Django problem with POST method
I am having an issue with using POSTed data instead of GET data with Django.
Here's my simplified urlpatterns class:
urlpatterns = patterns('',
('^hello/$', hello),
('^hello/ajax_info/$', ajax_info),
)
And I have this view in the views.py file:
def ajax_info(request):
... | Django problem with POST method | I am having an issue with using POSTed data instead of GET data with Django.
Here's my simplified urlpatterns class:
urlpatterns = patterns('',
('^hello/$', hello),
('^hello/ajax_info/$', ajax_info),
)
And I have this view in the views.py file:
def ajax_info(request):
if request.method == "POST":
... | [
"I'm not familiar with django, but that 500 sure looks like an HTTP status code, indicating that your response was bad. Perhaps watch what happens with a JavaScript debugger: Firebug, Chrome's tools, Opera Dragonfly, etc.\nIncidentally, you may want to use a library like jQuery for the client code. Manual ajax is... | [
2,
2,
2,
1
] | [] | [] | [
"django",
"forms",
"get",
"post",
"python"
] | stackoverflow_0006159671_django_forms_get_post_python.txt |
Q:
How to choose closest/fastest mirror in Python?
I've been thinking about how to implement mirror picking in Python. When I call on service API I get response with IP address. Now I want to take that address and check if it's close to me or not. If not, retry. I thought about pinging, as I have only ~1ms ping to th... | How to choose closest/fastest mirror in Python? | I've been thinking about how to implement mirror picking in Python. When I call on service API I get response with IP address. Now I want to take that address and check if it's close to me or not. If not, retry. I thought about pinging, as I have only ~1ms ping to the IP addresses hosted in same data center, but much h... | [
"The YUM fastestmirror plugin uses a crude method of timing how long it takes to connect to a port on the remote server. Whilst its crude, it measures lag rather than bandwidth, it is fairly effective:\ntime_before = time.time()\nsock.connect((self.host, self.port))\nresult = time.time() - time_before\nsock.close(... | [
4,
1
] | [] | [] | [
"geo",
"geoip",
"ping",
"python"
] | stackoverflow_0006159173_geo_geoip_ping_python.txt |
Q:
system python versus user python
I've installed Python 2.7 using macports and because of my $PATH variable, that's the one I get when I type $ python. However, virtualenv defaults to using Python 2.6 unless I remember to force it to do otherwise with the -p flag.
On a related note, globally running yolk -l shows ... | system python versus user python | I've installed Python 2.7 using macports and because of my $PATH variable, that's the one I get when I type $ python. However, virtualenv defaults to using Python 2.6 unless I remember to force it to do otherwise with the -p flag.
On a related note, globally running yolk -l shows the following:
Python - 2.6.1... | [
"If you force python 2.7 globally on your system, things will break. You don't want to do that.\nYou should use virtualenvwrapper. It should choose your preferred python.\nhttp://www.doughellmann.com/docs/virtualenvwrapper/install.html#python-interpreter-virtualenv-and-path\n",
"I have had similar problems, altho... | [
2,
1
] | [] | [] | [
"macports",
"python"
] | stackoverflow_0006159274_macports_python.txt |
Q:
Writing to a new Xml file using Python Error Message?
What is this error message ?
My code
#!/usr/bin/python
from xml.dom.minidom import Document
def CreateXml(nameSpace, rootElementName):
xmlDoc = xml.dom.minidom.Document()
xmlRootElement = doc.createElementNS(nameSpace, rootElementName)
xmlDoc.appen... | Writing to a new Xml file using Python Error Message? | What is this error message ?
My code
#!/usr/bin/python
from xml.dom.minidom import Document
def CreateXml(nameSpace, rootElementName):
xmlDoc = xml.dom.minidom.Document()
xmlRootElement = doc.createElementNS(nameSpace, rootElementName)
xmlDoc.appendChild(xmlRootElement)
return xmlDoc
Error is
File "... | [
"You forgot to import xml.dom.minidom to import the XML minidom module.\n>>> xml.dom.minidom.Document()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'xml' is not defined\n>>> import xml.dom.minidom\n>>> xml.dom.minidom.Document()\n<xml.dom.minidom.Document instance a... | [
0
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0006160289_cgi_python.txt |
Q:
Setting the Date on the wx.calendar CalendarCtrl Widget
I'm trying to set the selected date so that it is always the current day. How would I go about this?
Currently if I let the widget sit for more than a day, the selected date doesn't update. Thus the date would be behind. How would I go about changing the sel... | Setting the Date on the wx.calendar CalendarCtrl Widget | I'm trying to set the selected date so that it is always the current day. How would I go about this?
Currently if I let the widget sit for more than a day, the selected date doesn't update. Thus the date would be behind. How would I go about changing the selected date, so that it's always up to date?
| [
"you could set a timer (wx.Timer) instance to produce a wx.EVT_TIMER every several few seconds/minutes and bind the event to a method in charge of updating the calendar with the current date (wx.DateTime_Now()) if required.\nHere you have a minimal working demo code (try to change the date: it will go back to the c... | [
1
] | [] | [] | [
"calendar",
"calendar_control",
"python",
"wxpython"
] | stackoverflow_0006159917_calendar_calendar_control_python_wxpython.txt |
Q:
jsp + php + asp.net + python in one site?
I have a question: can I mix jsp, php, asp.net and python in one site?
For example:
www.mysite.com/customer.html <-- this page is written by jsp
www.mysite.com/mycart.html <-- this page is written by php
www.mysite.com/login.html <-- this page is written by asp.net
www.mys... | jsp + php + asp.net + python in one site? | I have a question: can I mix jsp, php, asp.net and python in one site?
For example:
www.mysite.com/customer.html <-- this page is written by jsp
www.mysite.com/mycart.html <-- this page is written by php
www.mysite.com/login.html <-- this page is written by asp.net
www.mysite.com/admin.html <-- this page is written by ... | [
"You cannot share a session unless there is one module (for apache or something) that encompasses all of these technologies properly.\nIf this doesn't bother you, then, just configure your webserver to handle all of the file endings and such.\n",
"Speaking from my experience, I suppose all web servers supports th... | [
1,
0,
0,
0
] | [] | [] | [
"asp.net",
"jsp",
"php",
"python",
"webserver"
] | stackoverflow_0006085057_asp.net_jsp_php_python_webserver.txt |
Q:
Special Python dict with object IDs
I want to create a special dictionary which uses object IDs as keys, like this:
class ObjectIdDict(dict):
def __setitem__(self, key, value):
super(ObjectIdDict, self).__setitem__(id(key), value)
def __getitem__(self, key):
super(ObjectIdDict, self).__ge... | Special Python dict with object IDs | I want to create a special dictionary which uses object IDs as keys, like this:
class ObjectIdDict(dict):
def __setitem__(self, key, value):
super(ObjectIdDict, self).__setitem__(id(key), value)
def __getitem__(self, key):
super(ObjectIdDict, self).__getitem__(id(key))
But if I run the follow... | [
"__getitem__ must return the result:\ndef __getitem__(self, key):\n return super(ObjectIdDict, self).__getitem__(id(key))\n #^^^^^\n\nWithout a return, the implicit return value is None, and therefore oiddict[key] is None for all keys.\n"
] | [
4
] | [] | [] | [
"dictionary",
"inheritance",
"python"
] | stackoverflow_0006160381_dictionary_inheritance_python.txt |
Q:
Python: How to run a script1 from script2 and DUPLICATE script1's output (stdout, stderr) in script2 for logging (into a file)
I have two python scripts: script1.py and script2.py
I want to run script1 from script2 (os.system, subprocess.Popen, ..) and then log script1's output (stdout, stderr) to a file log.txt, ... | Python: How to run a script1 from script2 and DUPLICATE script1's output (stdout, stderr) in script2 for logging (into a file) | I have two python scripts: script1.py and script2.py
I want to run script1 from script2 (os.system, subprocess.Popen, ..) and then log script1's output (stdout, stderr) to a file log.txt, while still seeing script1's and script2's outputs on my terminal (as I would see, without the logging feature), as the are printed ... | [
"Use the subprocess module (not os.system). Send stdout and stderr to a pipe and capture them in local variables (using communicate probably). Once you have them in local vars you can both print them and write them to a file (so you're probably most of the way there already).\nSomething like:\nlog = open(\"log.tx... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006160699_python.txt |
Q:
python compare each 2bytes in some portion of data
In python, assume that there is data when I run...
search = target.readframes(2205)
Each frame consist of 2 bytes. I want to compare each 2-byte value and extract highest 2 values in the range.
For example, if the data looks like this...
0000|0001|0002|0008|0007|... | python compare each 2bytes in some portion of data | In python, assume that there is data when I run...
search = target.readframes(2205)
Each frame consist of 2 bytes. I want to compare each 2-byte value and extract highest 2 values in the range.
For example, if the data looks like this...
0000|0001|0002|0008|0007|000F|000D|000A|00FB|00FC|00FA|00F9|00F8|00D7|00C3|0000
... | [
"First, you should use only bytes objects if you deal with binary data. They require Python 2.6+.\nExample\ndata = b\"\\x42\\x43\\x44\\x45\"\nprint(data[0:2], data[2:4])\n\nAnd yes, you can use normal compare operations with bytes.\nI am not sure that kind of object is returned by your readframes but if it is not b... | [
1,
0
] | [] | [] | [
"byte",
"comparison",
"python"
] | stackoverflow_0006160271_byte_comparison_python.txt |
Q:
Please explain how regex non-zero lookbehind assertion works in clear language
Can someone explain in clear language how the non-zero lookbehind assertion (?<=.) technically works in the example below? That is, can you actually walk through it? The code works fine and produces the correct result.
I read about (?<=... | Please explain how regex non-zero lookbehind assertion works in clear language | Can someone explain in clear language how the non-zero lookbehind assertion (?<=.) technically works in the example below? That is, can you actually walk through it? The code works fine and produces the correct result.
I read about (?<=\w) at http://www.regular-expressions.info/wordboundaries.html, but the explanation ... | [
"Look-behind does just that: it verifies that whatever precedes the current character matches the look-behind expression.\nIn your case, (?<=.)s will match s, but only if what precedes it matches . (i.e. anything except CRLF).\n"
] | [
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006160635_python_regex.txt |
Q:
Shell-style list generation or variable expression in Python?
----Complete Rephrasing----
I was working on a new class where each instance was essentially sequential and linked. I had thought, in a very shell scripty way, that I could define a function to compile a list of all of these instances if I named them s... | Shell-style list generation or variable expression in Python? | ----Complete Rephrasing----
I was working on a new class where each instance was essentially sequential and linked. I had thought, in a very shell scripty way, that I could define a function to compile a list of all of these instances if I named them systematically. Then I could do what I wanted in the first place, ... | [
"Something like this:\nlist_of_x = [x1, x2, x3]\n\n",
"If you have code like this:\nx1 = \"foo\"\nx2 = \"bar\"\nx3 = \"goat\"\n\nthen you should replace it with:\nx = [\"foo\", \"bar\", \"goat\"]\n\nYou could do:\nx = [x1, x2, x3]\n\nBut that will copy the values from x1,x2, x3 into x. Changes made to x will not ... | [
1,
1,
0,
0,
-2
] | [
"you can convert a variable to its value by using eval(var)\nFor example, in your case you could do:\nmap(eval,List_Of_X)\n\nif you wanted to convert your list of strings ['x1','x2',...] into their values, say [1,2,...] if x1=1 and x2=2\n"
] | [
-3
] | [
"python",
"variables"
] | stackoverflow_0006159727_python_variables.txt |
Q:
problem with pyopengl in linux
I am a beginner.
I want to use pyopengl in linux but I have a problem.
I try to import pyopengl module as below :
from OpenGl.GL import *
but interpreter shows this error message :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named ... | problem with pyopengl in linux | I am a beginner.
I want to use pyopengl in linux but I have a problem.
I try to import pyopengl module as below :
from OpenGl.GL import *
but interpreter shows this error message :
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named OpenGl.Gl
what should I do?
| [
"Python is a case-sensitive language. Both G and L should be uppercase letters:\nfrom OpenGL.GL import *\n\n"
] | [
3
] | [] | [] | [
"pyopengl",
"python"
] | stackoverflow_0006160952_pyopengl_python.txt |
Q:
PHP, Python and java
I have to make a big project in my work and i need to select the appropriate language for development, i have three options (PHP , Python and Java)
I have a poor information about PHP , and intermediate information about Java and no information about Python
so i need your help to know the stre... | PHP, Python and java | I have to make a big project in my work and i need to select the appropriate language for development, i have three options (PHP , Python and Java)
I have a poor information about PHP , and intermediate information about Java and no information about Python
so i need your help to know the strength and weakness of each ... | [
"Given that Java is the only language you have experience with, you should stick with it. Besides that, good software can be written in any of these languages.\n",
"If you don't know any of the languages, how do you expect to do any development in any of them?\nLearning a development language enough be the leadin... | [
8,
2,
0
] | [] | [] | [
"java",
"php",
"python"
] | stackoverflow_0006160890_java_php_python.txt |
Q:
Python multiple classes
I want to create multiple bots with all their own unique id. But how can do this automatically for numerous bots and have all an other id? I can use bot1, bot2 but what if i want to use this with 100 bots?
class newbot:
id = randomid()
bot1 = newbot()
bot2 = newbot()
print bot1.id... | Python multiple classes | I want to create multiple bots with all their own unique id. But how can do this automatically for numerous bots and have all an other id? I can use bot1, bot2 but what if i want to use this with 100 bots?
class newbot:
id = randomid()
bot1 = newbot()
bot2 = newbot()
print bot1.id
print bot2.id #all the sa... | [
"The id member ends up being shared among all instances of your class because it's defined as a class member instead of an instance member. You probably should write:\nclass newbot(object):\n def __init__(self):\n self.id = randomid()\n\nbot1 = newbot() \nbot2 = newbot() \n\n# The two ids should be diff... | [
7,
3
] | [] | [] | [
"python"
] | stackoverflow_0006160705_python.txt |
Q:
looking for practical solutions for optimizing text parsing speed with python
Set of lines need to be parsed with set of different named regexes.
Every line is passed through every regex until match is found.
When match is found code should return/yield (named regex,value) pairs for each line.
Files are 2GB+ siz... | looking for practical solutions for optimizing text parsing speed with python | Set of lines need to be parsed with set of different named regexes.
Every line is passed through every regex until match is found.
When match is found code should return/yield (named regex,value) pairs for each line.
Files are 2GB+ size so I am looking for some ideas for improving speed of my parsers.
Currently code ... | [
"In the first instance, I wouldn't worry about switching to another language. Alternative strategies are likely to yield greater benefits. The regexp engine used by python is written in C anyway (iirc).\n\n'Optimising' the regular expressions if probably your first task. How to do this is dependent on your text, an... | [
4,
3,
1
] | [] | [] | [
"optimization",
"parsing",
"python",
"text_parsing"
] | stackoverflow_0006160942_optimization_parsing_python_text_parsing.txt |
Q:
readframes return 2 byte in python
When readframes() is used in python, the online documention says sampling frequency is returned it looks it returns 2 bytes. I think there are 4 byte on each frame:
left = 2 bytes
right = 2 bytes
Do I have to check if it is mono or stereo and if it is stereo, read 2 frames at a ... | readframes return 2 byte in python | When readframes() is used in python, the online documention says sampling frequency is returned it looks it returns 2 bytes. I think there are 4 byte on each frame:
left = 2 bytes
right = 2 bytes
Do I have to check if it is mono or stereo and if it is stereo, read 2 frames at a time and if it is mono, read 1 frame at ... | [
"A wave file has:\n\nsample rate of Wave_read.getframerate() per second (e.g 44100 if from an audio CD).\nsample width of Wave_read.getsampwidth() bytes (i.e 1 for 8-bit samples, 2 for 16-bit samples)\nWave_read.getnchannels() channels (typically 1 for mono, 2 for stereo)\n\nEvery time you do a Wave_read.getframes(... | [
5
] | [] | [] | [
"frequency",
"python",
"sampling",
"wav"
] | stackoverflow_0006149640_frequency_python_sampling_wav.txt |
Q:
extracting the root of a tree in python
Hey everybody,
I've been trying to find a built-in function for extracting the root of a tree in python,
I haven't found something like that and I've been trying to build one of my own but I couldn't build something generic to fit all my needs.
Does anyone have something pr... | extracting the root of a tree in python | Hey everybody,
I've been trying to find a built-in function for extracting the root of a tree in python,
I haven't found something like that and I've been trying to build one of my own but I couldn't build something generic to fit all my needs.
Does anyone have something prepared or perhaps know how to extract this in... | [
"You have to roll your own:\nclass Node(object):\n def __init__(self, p=None):\n self.parent = p\n self.children = []\n\nn1 = Node()\nn2 = Node()\nn1.children.append(n2)\nn2.parent = n1\n\nOf course you would want to have methods like addChild that would manage the .children and .parent attributes ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006161204_python.txt |
Q:
How can I get the content of body element by using html5lib in Python?
How can I get the content of <body> element by using html5lib in Python?
Example input data: <html><head></head><body>xxx<b>yyy</b></hr></body></html>
Expected output: xxx<b>yyy</b></hr>
It should work even if HTML is broken (unclosed tags,...)... | How can I get the content of body element by using html5lib in Python? | How can I get the content of <body> element by using html5lib in Python?
Example input data: <html><head></head><body>xxx<b>yyy</b></hr></body></html>
Expected output: xxx<b>yyy</b></hr>
It should work even if HTML is broken (unclosed tags,...).
| [
"html5lib allows you to parse your documents using a variety of standard tree formats. You can do this using lxml, as I've done below, or you can follow the instructions in their user documentation to do it either with minidom, ElementTree or BeautifulSoup. \nfile = open(\"mydocument.html\")\ndoc = html5lib.parse(f... | [
5
] | [] | [] | [
"html5lib",
"python"
] | stackoverflow_0006161393_html5lib_python.txt |
Q:
Python MySQLdb 'not all arguments converted during string formatting'
I'm doing a task for uni, where we take a text file with a list of student IDs and their favourite movies, games, tv shows, et cetera, and populating a MySQL database with it. The text files are formatted like so:
1 Fight Club
1 Pootie Tang
... | Python MySQLdb 'not all arguments converted during string formatting' | I'm doing a task for uni, where we take a text file with a list of student IDs and their favourite movies, games, tv shows, et cetera, and populating a MySQL database with it. The text files are formatted like so:
1 Fight Club
1 Pootie Tang
3 The Lord Of The Rings Trilogy
3 Ocean's Eleven
3 The Italian Job
4 ... | [
"Its must be the typo, remove the $ and replace it with %\nError code:\ncursor.executemany('''INSERT INTO popularity\n VALUES (%s, %s, $s)''', entries_list)\n\nCorrected code:\ncursor.executemany('''INSERT INTO popularity\n VALUES (%s, %s, %s)''', entries_list)\n\n"
] | [
11
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0006161697_mysql_python.txt |
Q:
I would like some advice why this would not insert data into my SQL table
Following is my code:
import MySQLdb
def insert_popularity(PersonNumber, Category, Value):
# make a connection to the dataabse
connection = MySQLdb.connect(host='localhost', user='root', \
passwd='password', db=... | I would like some advice why this would not insert data into my SQL table | Following is my code:
import MySQLdb
def insert_popularity(PersonNumber, Category, Value):
# make a connection to the dataabse
connection = MySQLdb.connect(host='localhost', user='root', \
passwd='password', db='inb104')
# get a cursor on the database
cursor = connection.cursor()
# const... | [
"You've created the query to execute as a tuple. There two possibilities to solve this:\n\nUse the created query (sql) as a list of arguments:\nsql = (\"\"\"INSERT INTO popularity (PersonNumber, Category, Value)\n VALUES(%s, %s, %s)\"\"\", (number, Category, value))\n # execute the query\ncursor.execute(*... | [
2,
2,
1,
1,
1
] | [] | [] | [
"python",
"sql",
"text_files"
] | stackoverflow_0006148293_python_sql_text_files.txt |
Q:
pyqt4 button click handler
I have a problem usin pyqt4:
here is the code I'm using, the point is that if in the event handler for the pushOk button clicked I call chiedi_numeri() it does not show me any form, while if I call chiedi_numeri() it says that argument 3 og QObjectConnect has an invalid type. how can I s... | pyqt4 button click handler | I have a problem usin pyqt4:
here is the code I'm using, the point is that if in the event handler for the pushOk button clicked I call chiedi_numeri() it does not show me any form, while if I call chiedi_numeri() it says that argument 3 og QObjectConnect has an invalid type. how can I solve it?
thanks
class Ui_dialog(... | [
"When you connect a Signal to a python function, you pass the function object. In other words, you omit the trailing parentheses since you are passing the function not calling it. Try changing that line to read app.connect(ui.pushOk, Qt.SIGNAL(\"clicked()\"), chiedi_numeri)\n",
"One thing you're doing wrong is ... | [
1,
0,
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0006160815_pyqt_pyqt4_python.txt |
Q:
Sort a numpy array by another array, along a particular axis, using less memory
From the answer to this question, I learned how to sort the entries of one numpy array a by the values of another numpy array b, along a particular axis.
However, this method requires the creation of several intermediate arrays that ar... | Sort a numpy array by another array, along a particular axis, using less memory | From the answer to this question, I learned how to sort the entries of one numpy array a by the values of another numpy array b, along a particular axis.
However, this method requires the creation of several intermediate arrays that are the same size as a, one for each dimension of a. Some of my arrays are quite large,... | [
"Would a record array serve your purposes?\n>>> a = numpy.zeros((3, 3, 3))\n>>> a += numpy.array((1, 3, 2)).reshape((3, 1, 1))\n>>> b = numpy.arange(3*3*3).reshape((3, 3, 3))\n>>> c = numpy.array(zip(a.flatten(), b.flatten()), dtype=[('f', float), ('i', int)]).reshape(3, 3, 3)\n>>> c.sort(axis=0)\n>>> c['i']\narray... | [
2
] | [] | [] | [
"multidimensional_array",
"numpy",
"python",
"sorting"
] | stackoverflow_0006162172_multidimensional_array_numpy_python_sorting.txt |
Q:
For python I want to make each values in a list respond to another value
def data_entry(categories):
# these are the values within categories
data_entry(['movies', 'sports', 'actors', 'tv', 'games', \
'activities', 'musicians', 'books'])
# for each different value in categories i need it to open a different ... | For python I want to make each values in a list respond to another value | def data_entry(categories):
# these are the values within categories
data_entry(['movies', 'sports', 'actors', 'tv', 'games', \
'activities', 'musicians', 'books'])
# for each different value in categories i need it to open a different txt file
# for example
when categories = movies ([0])
filename='movies.txt'
w... | [
"\nWrite a dict that maps a category name to a filename.\nLoop over your list of categories, and retrieve the filename by indexing into the dict using the category name.\nUse open() with the filename.\n\nExample:\ncategories = [\"movies\", \"tv\"]\n\n# long winded:\nfilenames = {\n \"movies\": \"movies.txt\",\n ... | [
3,
3,
1
] | [] | [] | [
"python",
"types"
] | stackoverflow_0006162231_python_types.txt |
Q:
Cleaner way to save foreign key relationship in django
I am currently doing the following and was wondering if there's any way to condense these 4 lines...as they're very verbose....
g = game_form.save(commit=False)
team = Team.objects.get(pk=team_id)
g.team = team
g.save()
A:
If it's ok for Team to be part of t... | Cleaner way to save foreign key relationship in django | I am currently doing the following and was wondering if there's any way to condense these 4 lines...as they're very verbose....
g = game_form.save(commit=False)
team = Team.objects.get(pk=team_id)
g.team = team
g.save()
| [
"If it's ok for Team to be part of the form then I would make Team a ModelChoiceField in my form. Django will handle everything behind the scenes for you.\n"
] | [
2
] | [] | [] | [
"django",
"foreign_keys",
"modelform",
"python"
] | stackoverflow_0006162664_django_foreign_keys_modelform_python.txt |
Q:
python2.7:A sample script ,in C partition it can run however in D partition it has AttributeError
I am learning python. Today I meet with a odd problem.
from urllib import urlopen
url='http://www.google.com'
f=urlopen(url).read()
print f
It is a sample script ,it can run if it in C partition however in D partiti... | python2.7:A sample script ,in C partition it can run however in D partition it has AttributeError | I am learning python. Today I meet with a odd problem.
from urllib import urlopen
url='http://www.google.com'
f=urlopen(url).read()
print f
It is a sample script ,it can run if it in C partition however in D partition
it has AttributeError:
Traceback (most recent call last):
File "D:\urlopen.py", line 1, in <module... | [
"I don't know why it works on C:\\. It should fail either way. You're importing something from urllib. Your script is called urllib. The current directory comes before standard library dirs, so you import yourself. It's only because imports are \"cached\" (a second import x in the same interpreter process just give... | [
1,
0
] | [] | [] | [
"module",
"python",
"urllib"
] | stackoverflow_0006162811_module_python_urllib.txt |
Q:
Is there a way to write into python code a command to include duplicate entries into a My SQL database
I have to write up a python program that communicates with a My SQL database to write in data... I have done the code however it does not enter all the data as it says there are duplicates... is there a way to ju... | Is there a way to write into python code a command to include duplicate entries into a My SQL database | I have to write up a python program that communicates with a My SQL database to write in data... I have done the code however it does not enter all the data as it says there are duplicates... is there a way to just inclue them?
| [
"You should provide more information like you SQL and database schema. It sounds like you are trying to insert items with the same primary key. If you remove the primary key you should be able to insert the data, or change the insert statement to not insert the field which is the primary key.\n"
] | [
0
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0006162827_python_sql.txt |
Q:
Why does pickle __getstate__ accept as a return value the very instance it required __getstate__ to pickle in the first place?
I was going to ask "How to pickle a class that inherits from dict and defines __slots__". Then I realized the utterly mind-wrenching solution in class B below actually works...
import pick... | Why does pickle __getstate__ accept as a return value the very instance it required __getstate__ to pickle in the first place? | I was going to ask "How to pickle a class that inherits from dict and defines __slots__". Then I realized the utterly mind-wrenching solution in class B below actually works...
import pickle
class A(dict):
__slots__ = ["porridge"]
def __init__(self, porridge): self.porridge = porridge
class B(A):
__slots_... | [
"Maybe I'm a bit late to the party, but this question didn't get an answer that actually explains what's happening, so here we go.\nHere's a quick summary for those who don't want to read this whole post (it got a bit long...):\n\nYou don't need to take care of the contained dict instance in __getstate__() -- pick... | [
20,
3
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0005247250_pickle_python.txt |
Q:
pywebkitgtk vertical resize
Webkit resizes the window it is in to render the full page. The problem though is that it doesn't resize down by default, so if it sized up initially, and you load a second page which is shorter, the page gets tiled. Is there a way to resize it back down to fit the page?
import gtk
impo... | pywebkitgtk vertical resize | Webkit resizes the window it is in to render the full page. The problem though is that it doesn't resize down by default, so if it sized up initially, and you load a second page which is shorter, the page gets tiled. Is there a way to resize it back down to fit the page?
import gtk
import webkit
window = gtk.Window()
b... | [
"Put your web view in a gtk.ScrolledWindow. Then it won't resize to fit the whole page.\n"
] | [
0
] | [] | [] | [
"gtk",
"pygtk",
"python",
"webkit"
] | stackoverflow_0006145321_gtk_pygtk_python_webkit.txt |
Q:
Running Python cgi-scripts everywhere in var/www/
Hey there!
I have a problem, I was not able to solve and I hope that here's someone who can help me.
I want to run my python scripts on my apache2-Server via cgi.
I know that I can add scripts into the cgi-bin Directory, but I want to run the scripts in every direc... | Running Python cgi-scripts everywhere in var/www/ | Hey there!
I have a problem, I was not able to solve and I hope that here's someone who can help me.
I want to run my python scripts on my apache2-Server via cgi.
I know that I can add scripts into the cgi-bin Directory, but I want to run the scripts in every directory in the /var/www directories (also in the subdomain... | [
"I think it's quite a complicated question with no specific detail about it. What exactly is your web server configuration? I mean - do you server server virtual hosts or just running one localhost instance?\nIn each case your definition of cgi scripts directory should point to the same directory:\nScriptAlias /cg... | [
1
] | [] | [] | [
"apache2",
"cgi",
"python"
] | stackoverflow_0006157526_apache2_cgi_python.txt |
Q:
using cookies with twisted.web.client
I'm trying to make a web client application using twisted but having some trouble with cookies. Does anyone have an example I can look at?
A:
While it's true that getPage doesn't easily allow direct access to the request or response headers (just one example of how getPage i... | using cookies with twisted.web.client | I'm trying to make a web client application using twisted but having some trouble with cookies. Does anyone have an example I can look at?
| [
"While it's true that getPage doesn't easily allow direct access to the request or response headers (just one example of how getPage isn't a super awesome API), cookies are actually supported.\ncookies = {cookies: tosend}\nd = getPage(url, cookies=cookies)\ndef cbPage(result):\n print 'Look at my cookies:', cook... | [
7,
2,
1
] | [] | [] | [
"cookies",
"python",
"twisted"
] | stackoverflow_0001398740_cookies_python_twisted.txt |
Q:
Sort list by nested tuple values
Is there a better way to sort a list by a nested tuple values than writing an itemgetter alternative that extracts the nested tuple value:
def deep_get(*idx):
def g(t):
for i in idx: t = t[i]
return t
return g
>>> l = [((2,1), 1),((1,3), 1),((3,6), 1),((4,5), 2)]
>... | Sort list by nested tuple values | Is there a better way to sort a list by a nested tuple values than writing an itemgetter alternative that extracts the nested tuple value:
def deep_get(*idx):
def g(t):
for i in idx: t = t[i]
return t
return g
>>> l = [((2,1), 1),((1,3), 1),((3,6), 1),((4,5), 2)]
>>> sorted(l, key=deep_get(0,0))
[((1, ... | [
"Yes, you could just use a key=lambda x: x[0][1]\n",
"Your approach is quite good, given the data structure that you have.\nAnother approach would be to use another structure.\nIf you want speed, the de-factor standard NumPy is the way to go. Its job is to efficiently handle large arrays. It even has some nice ... | [
12,
2,
1,
1
] | [] | [] | [
"python",
"sorting",
"tuples"
] | stackoverflow_0006162823_python_sorting_tuples.txt |
Q:
Export template function
I have templated function connect:
template<class InstanceClass>
CL_Slot connect (InstanceClass *instance, void(InstanceClass::*function)(Param1, Param2))
It connects for some signal passed function from InstanceClass.
In my example, I want to connect some of classes for the keyboard even... | Export template function | I have templated function connect:
template<class InstanceClass>
CL_Slot connect (InstanceClass *instance, void(InstanceClass::*function)(Param1, Param2))
It connects for some signal passed function from InstanceClass.
In my example, I want to connect some of classes for the keyboard event (KeyDown).
In c++ I write:
g... | [
"Why don't you just add\nextern template<>\n CL_Slot connect<SomeClass> (SomeClass *instance, void(InstanceClass::*function)(Param1, Param2));\n\nnote: extern might need to after template<> -- don't remember\nIf you must have C linkage add a wrapper function (it will inline the templated function).\n\nNote: MSVC... | [
1
] | [] | [] | [
"boost",
"c++",
"export",
"python",
"templates"
] | stackoverflow_0006163387_boost_c++_export_python_templates.txt |
Q:
How can I call sys.exc_clear() for another part of a Python program?
I have a class (see this previous question if you are interested) which tracks, amongst other things, errors. The class is called in a variety of situations, one of them is during an exception. Even though my class calls sys.exc_clear() as part... | How can I call sys.exc_clear() for another part of a Python program? | I have a class (see this previous question if you are interested) which tracks, amongst other things, errors. The class is called in a variety of situations, one of them is during an exception. Even though my class calls sys.exc_clear() as part of the regular course of events, the next time the class is called (even ... | [
"Please note that last exception information is a per-thread construct. An excerpt from sys.exc_info:\n\nThis function returns a tuple of three values that give information about the exception that is currently being handled. The information returned is specific both to the current thread and to the current stack f... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0006155621_python.txt |
Q:
Python, name not defined
def main()
name = input ("Please enter your name")
print ("your name is", name)
In this program,(written in python IDLE) when I run it, and enter my name I get this error message.
Traceback (most recent call last):
File "C:\Users\********\Documents\PYTHON\hello world.py", li... | Python, name not defined | def main()
name = input ("Please enter your name")
print ("your name is", name)
In this program,(written in python IDLE) when I run it, and enter my name I get this error message.
Traceback (most recent call last):
File "C:\Users\********\Documents\PYTHON\hello world.py", line 66, in ?
main()
File... | [
"input() in 2.x interprets its input as Python code. Use raw_input() instead. And stop applying 3.x documentation to 2.x.\n"
] | [
16
] | [] | [] | [
"python"
] | stackoverflow_0006163596_python.txt |
Q:
Problem trying to re-use a primary key id with SQLAlchemy
I'm trying to reuse a primary key in one of my tables with SQLAlchemy and am getting foreign key constraint error.
In a nutshell:
PostgreSQL 8.4
Python 2.7
SQLAlchemy 0.7
I have 3 tables: User, Inventories and Devices. Inventories and Devices have a one-t... | Problem trying to re-use a primary key id with SQLAlchemy | I'm trying to reuse a primary key in one of my tables with SQLAlchemy and am getting foreign key constraint error.
In a nutshell:
PostgreSQL 8.4
Python 2.7
SQLAlchemy 0.7
I have 3 tables: User, Inventories and Devices. Inventories and Devices have a one-to-one relationship with User. User.id is Inventories.user_id an... | [
"To address the error you're seeing, you could update the foreign keys on all of the Device and Inventory models associated with that User model before committing. You'll have to make sure that your User model doesn't auto-increment the id (i.e., that it isn't a PostgreSQL sequence).\nFor example, the SQLAlchemy mo... | [
0,
0,
0
] | [] | [] | [
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0006157824_postgresql_python_sqlalchemy.txt |
Q:
Python regex multiple search
I need to search a string for multiple words.
import re
words = [{'word':'test1', 'case':False}, {'word':'test2', 'case':False}]
status = "test1 test2"
for w in words:
if w['case']:
r = re.compile("\s#?%s" % w['word'], re.IGNORECASE|re.MULTILINE)
else:
r = r... | Python regex multiple search | I need to search a string for multiple words.
import re
words = [{'word':'test1', 'case':False}, {'word':'test2', 'case':False}]
status = "test1 test2"
for w in words:
if w['case']:
r = re.compile("\s#?%s" % w['word'], re.IGNORECASE|re.MULTILINE)
else:
r = re.compile("\s#?%s" % w['word'], re... | [
"There is no space before test1 in status, while your generated regular expressions require there to be a space.\nYou can modify the test to match either after a space or at the beginning of a line:\nfor w in words:\n if w['case']:\n r = re.compile(\"(^|\\s)#?%s\" % w['word'], re.IGNORECASE|re.MULTILINE)\... | [
9,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006163586_python_regex.txt |
Q:
spawn safe, platform-independent dummy process in Python
I'm writing some code that needs to run on different OS platforms and interact with separate processes. To write tests for it, I need to be able to create processes from python that do nothing but wait to be signaled to stop. I would like to be able to creat... | spawn safe, platform-independent dummy process in Python | I'm writing some code that needs to run on different OS platforms and interact with separate processes. To write tests for it, I need to be able to create processes from python that do nothing but wait to be signaled to stop. I would like to be able to create some processes that recursively create more.
Also (this part... | [
"If you're using Python 2.6 the multiprocessing package has some stuff you might find useful.\nThere's a very simple example on my github. If you run spawner it will create 3 processes that run seperately, but use a channel to talk back to the spawner. So if you kill the spawner process the others you have started ... | [
1
] | [] | [] | [
"process",
"python",
"spawn"
] | stackoverflow_0006163818_process_python_spawn.txt |
Q:
search and replace text in python
I am kinda to python programming
I have no clue how to solve that task:
for line in f: br
m = re.search("f(\S+\s+,\s+\S+)",
"56 - f(32 , 6*3) + 62 * ( 54 - 3 ) + f(5 , 9+y)")
print m.group()
I have to convert all f(x , y) to x*y.
I haven't got an idea h... | search and replace text in python | I am kinda to python programming
I have no clue how to solve that task:
for line in f: br
m = re.search("f(\S+\s+,\s+\S+)",
"56 - f(32 , 6*3) + 62 * ( 54 - 3 ) + f(5 , 9+y)")
print m.group()
I have to convert all f(x , y) to x*y.
I haven't got an idea how to solve that. I tried with splittin... | [
"I would recommend a tour towards the python tutorial, perhaps the string section.\nAfter that, the regexp tutorial.\n",
"Regular expressions can be a complicated beast, I suggest reading up on them. For this particular scenario re.sub should do the trick.\nHere's a sample of what I've come up with using the inp... | [
3,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006163677_python_regex.txt |
Q:
Preventing select query on ForeignKey when the primary key is known
to insert a row to a table that has a one-to-one relationship, you would do this in Django:
mypk=2 # Comes from the POST request
model=MyModel(myField="Hello", myForeignModel=ForeignModel.objects.get(pk=mypk))
model.save()
This will cause a SEL... | Preventing select query on ForeignKey when the primary key is known | to insert a row to a table that has a one-to-one relationship, you would do this in Django:
mypk=2 # Comes from the POST request
model=MyModel(myField="Hello", myForeignModel=ForeignModel.objects.get(pk=mypk))
model.save()
This will cause a SELECT query followed by an INSERT query.
However, the SELECT query isn't re... | [
"From the docs:\n\nBehind the scenes, Django appends \"_id\" to the field name to create its database column name.\n\nSimply set myForeignModel_id to the FK value.\n"
] | [
1
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0006163955_django_python_sql.txt |
Q:
App Engine, Python: how to filter query by ID?
I try to get data from app engine datastore.
Filtering query by 'title' (or any other property) works:
obj = db.Query(PageModel).filter('title',title)[0]
But the same thing with ID - doesn't:
obj = db.Query(PageModel).filter('ID',page_id)[0]
I think there is somethi... | App Engine, Python: how to filter query by ID? | I try to get data from app engine datastore.
Filtering query by 'title' (or any other property) works:
obj = db.Query(PageModel).filter('title',title)[0]
But the same thing with ID - doesn't:
obj = db.Query(PageModel).filter('ID',page_id)[0]
I think there is something special about IDs and KEYs in datastore, but I ca... | [
"Try\nobj = PageModel.get_by_id(page_id)\n\ninstead. This assumes that the ID you're working with is the numerical ID of a datastore key (ie, came from something like obj.key().id()) and not some arbitrary ID field you've added to your PageModel.\n",
"You can filter data by using key(s):\nfrom google.appengine.e... | [
13,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002283149_google_app_engine_python.txt |
Q:
Building Python 2.6 as shared library broke (after previously working), any reason why?
I'm on a VPS running CentOS, with has Python 2.4 installed - which unfortunately means that I have to avoid breaking it. So I'm installing Python 2.6 as a separate install, then using virtualenv. Yesterday, I installed Python 2... | Building Python 2.6 as shared library broke (after previously working), any reason why? | I'm on a VPS running CentOS, with has Python 2.4 installed - which unfortunately means that I have to avoid breaking it. So I'm installing Python 2.6 as a separate install, then using virtualenv. Yesterday, I installed Python 2.6 with --enable-shared, so I could compile mod_wsgi - and it worked fine. Today, I had to st... | [
"Thanks to Vensky's post on installing Python 2.6, I have what seems like a fix - although I still don't understand why things broke, and this fix seems kludgy. But at least it's working.\nCreate a file with this line:\n#/etc/ld.so.conf.d/python2.6.conf\n/foo/python2.6/lib\n\nThen run the ldconfig command, with no ... | [
3
] | [] | [] | [
"python",
"shared_libraries"
] | stackoverflow_0006157647_python_shared_libraries.txt |
Q:
How to install OpenCV 2.2 on OSX 10.5 32-bit for ActivePython 2.7?
The title is the whole question.
I have tried homebrew with the --build32 option
I have tried macports
I have tried downloading the source file and compiling from scratch.
All the above install perfectly with no issues. However -- after trackin... | How to install OpenCV 2.2 on OSX 10.5 32-bit for ActivePython 2.7? | The title is the whole question.
I have tried homebrew with the --build32 option
I have tried macports
I have tried downloading the source file and compiling from scratch.
All the above install perfectly with no issues. However -- after tracking down the correct cv.so files from the various installations and moving... | [
"I successfully built OpenCV 2.2 with ActivePython 2.7. \nTo build for 32-bit you need to:\n\nadd CMAKE_OSX_ARCHITECTURES:STRING=i386 to your CMakeCache.txt (right after running cmake)\nRe-run cmake\n\nIf you need the full build instructions I followed, let me know ... I'll update this answer.\n"
] | [
0
] | [] | [] | [
"activepython",
"homebrew",
"macports",
"opencv",
"python"
] | stackoverflow_0006135273_activepython_homebrew_macports_opencv_python.txt |
Q:
returning a user defined function name when using a decorator with a callable object
Consider the following code fragment.
def print_timing(func):
import time
def wrapper(*args, **kwargs):
t1 = time.time()
res = func(*args, **kwargs)
t2 = time.time()
print '%s took %0.3f s ~... | returning a user defined function name when using a decorator with a callable object | Consider the following code fragment.
def print_timing(func):
import time
def wrapper(*args, **kwargs):
t1 = time.time()
res = func(*args, **kwargs)
t2 = time.time()
print '%s took %0.3f s ~ %0.0f min and %0.1f sec' % (func.func_name, t2-t1, int(t2 - t1)/60, (t2-t1) % 60 )
... | [
"No. The decorator happens when the class is built, and the __init__() call happens when the instance is built. You would need to have the decorator turn the function into a descriptor and have that descriptor get the name from the instance.\n",
"As long as you use the decorator only on methods, they'll be passed... | [
1,
1,
1
] | [] | [] | [
"callable",
"decorator",
"function_object",
"python"
] | stackoverflow_0006164291_callable_decorator_function_object_python.txt |
Q:
Make Python Sublists from a list using a Separator
I have for example the following list:
['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|']
and want it to be split by the "|" so the result would look like:
[[u'MOM', u'DAD'],[ u'GRAND'], [u'MOM', u'MAX', u'JULES']]
How can I do this? I only... | Make Python Sublists from a list using a Separator | I have for example the following list:
['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|']
and want it to be split by the "|" so the result would look like:
[[u'MOM', u'DAD'],[ u'GRAND'], [u'MOM', u'MAX', u'JULES']]
How can I do this? I only find examples of sublists on the net which need a lengt... | [
">>> [list(x[1]) for x in itertools.groupby(['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|'], lambda x: x=='|') if not x[0]]\n[[u'MOM', u'DAD'], [u'GRAND'], [u'MOM', u'MAX', u'JULES']]\n\n",
"itertools.groupby() does this very nicely...\n>>> import itertools\n>>> l = ['|', u'MOM', u'DAD', ... | [
15,
10,
1,
0
] | [] | [] | [
"python",
"split",
"sublist"
] | stackoverflow_0006164313_python_split_sublist.txt |
Q:
Sorting collection_name in appengine
class Profile(db.Model):
user = db.UserProperty()
class Playlist(db.Model):
name = db.StringProperty()
profile = db.ReferenceProperty(Profile, collection_name='playlists')
videos_num = db.IntegerProperty(default=0)
This are the basic entities of my model. I ca... | Sorting collection_name in appengine | class Profile(db.Model):
user = db.UserProperty()
class Playlist(db.Model):
name = db.StringProperty()
profile = db.ReferenceProperty(Profile, collection_name='playlists')
videos_num = db.IntegerProperty(default=0)
This are the basic entities of my model. I can access the playlists like profile.playli... | [
"profile.playlists is just a db.Query. Call its .order('videos_num') method.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python",
"sorting"
] | stackoverflow_0006162298_google_app_engine_python_sorting.txt |
Q:
Iterating through JSON to find if a defined object exists
Thanks for helping out. I am working in python.
I'm requesting a json page, and loading it.
fooList = json.load(urllib.urlopen(
"https://path.to.json.com/request?"))
It looks something like this:
{
"data": [
{
"foo": "2323582"
}... | Iterating through JSON to find if a defined object exists | Thanks for helping out. I am working in python.
I'm requesting a json page, and loading it.
fooList = json.load(urllib.urlopen(
"https://path.to.json.com/request?"))
It looks something like this:
{
"data": [
{
"foo": "2323582"
},
{
"foo": "32689023"
},
{
... | [
">>> print any(x['foo']=='1252015' for x in yourJson['data'])\nTrue\n\nany accepts any generator g=<generator> which returns boolean values, and is equivalent to g[0] or g[1] or g[2] or ... or g[N]. Of course if you didn't just want to search yourJson['data'], that would be a different story, and you'd want to defi... | [
3
] | [] | [] | [
"arrays",
"find",
"json",
"loops",
"python"
] | stackoverflow_0006164626_arrays_find_json_loops_python.txt |
Q:
Key generation in Google App Engine
If you guys ever used Google App Engine. It generates a key for every single instance of a model created. It's pretty neat.
I'm looking into building something like that. Do they do it so that the key is based on the content? Or do they just take a random choice from a-zA-Z0-9 f... | Key generation in Google App Engine | If you guys ever used Google App Engine. It generates a key for every single instance of a model created. It's pretty neat.
I'm looking into building something like that. Do they do it so that the key is based on the content? Or do they just take a random choice from a-zA-Z0-9 for like 50 times and build a string out o... | [
"Just using random values is not going to cut it. While the chance of two keys being the same is very slim the chances increase rapidly with the number of keys generated. See the birthday paradox.\nIn most cases such keys are generated in a way that guarantees uniqueness by containing several values like MAC addres... | [
3,
1,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006159666_google_app_engine_python.txt |
Q:
help with python ctypes and nvapi
My end goal is to query NVAPI for gpu usage and other statistics in python. See http://developer.nvidia.com/nvapi
from ctypes import WinDLL
nvapi = WinDLL("nvapi.dll")
print nvapi# <WinDLL 'nvapi.dll', handle 718a0000 at 27c0050>
print nvapi.nvapi_QueryInterface# <_FuncPtr object... | help with python ctypes and nvapi | My end goal is to query NVAPI for gpu usage and other statistics in python. See http://developer.nvidia.com/nvapi
from ctypes import WinDLL
nvapi = WinDLL("nvapi.dll")
print nvapi# <WinDLL 'nvapi.dll', handle 718a0000 at 27c0050>
print nvapi.nvapi_QueryInterface# <_FuncPtr object at 0x026D8E40>
print nvapi.nvapi_Query... | [
"Are you sure it's a WinDLL? From the header file, it looks like a standard C calling convention to me. Have you tried CDLL instead?\nEDIT:\nI see now. The header you pointed to isn't actually the interface for nvapi.dll--it is a wrapper around it that must be statically linked.\nFrom the docs downloaded from NVIDI... | [
2,
0
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0006163770_ctypes_python.txt |
Q:
How to concisely cascade through multiple regex statements in Python
My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if ... | How to concisely cascade through multiple regex statements in Python | My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this:
if re.... | [
"Generally speaking, in these sorts of situations, you want to make the code \"data driven\". That is, put the important information in a container, and loop through it.\nIn your case, the important information is (string, function) pairs.\nimport re\n\ndef fun1():\n print('fun1')\n\ndef fun2():\n print('fun2... | [
24,
13,
2,
1,
0,
0,
0
] | [] | [] | [
"coding_style",
"python",
"regex"
] | stackoverflow_0000597476_coding_style_python_regex.txt |
Q:
iterating through a list with an if statement
I have a list that I am looping through with a "for" loop and am running each value in the list through an if statement. My problem is that I am trying to only have the program do something if all the values in the list pass the if statement and if one doesn't pass, I... | iterating through a list with an if statement | I have a list that I am looping through with a "for" loop and am running each value in the list through an if statement. My problem is that I am trying to only have the program do something if all the values in the list pass the if statement and if one doesn't pass, I want it to move along to the next value in the lis... | [
"Python gives you loads of options to deal with such a situation. If you have example code we could narrow that down for you.\nOne option you could look at is the all operator:\n>>> all([1,2,3,4])\nTrue\n>>> all([1,2,3,False])\nFalse\n\nYou could also check for the length of the filtered list:\n>>> input = [1,2,3,4... | [
13,
4,
0,
0
] | [] | [] | [
"if_statement",
"list",
"loops",
"python"
] | stackoverflow_0006164443_if_statement_list_loops_python.txt |
Q:
gtk.TextBuffer color
I am using this example
http://www.pygtk.org/pygtk2tutorial/examples/testtext.py
but it doesn't work
i see only white textarea, terminal doesn't dispaly any notices
Ubuntu 11.04
A:
You apply colors to textview, not textbuffer
tview = gtk.TextView()
# background
tview.modify_base(gtk.STATE_NO... | gtk.TextBuffer color | I am using this example
http://www.pygtk.org/pygtk2tutorial/examples/testtext.py
but it doesn't work
i see only white textarea, terminal doesn't dispaly any notices
Ubuntu 11.04
| [
"You apply colors to textview, not textbuffer\ntview = gtk.TextView()\n# background\ntview.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse('#000000'))\n# foreground\ntview.modify_text(gtk.STATE_NORMAL, gtk.gdk.color_parse('#FFFFFF'))\n# bonus font\ntview.modify_font(pango.FontDescription('Monospace 11'))\n\n"
] | [
6
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0006165019_pygtk_python.txt |
Q:
Python package structure, setup.py for running unit tests
I'm not sure I'm organizing my package structure correctly or am using the right options in setup.py because I'm getting errors when I try to run unit tests.
I have a structure like this:
/project
/bin
/src
/pkgname
__init_... | Python package structure, setup.py for running unit tests | I'm not sure I'm organizing my package structure correctly or am using the right options in setup.py because I'm getting errors when I try to run unit tests.
I have a structure like this:
/project
/bin
/src
/pkgname
__init__.py
module1.py
module2.py
/tests
... | [
"Through some trial and error, I found the cause of this problem. Test names should match module names. If there is a \"foo_test.py\" test, there needs to be a corresponding module foo.py. \nI found some guidelines on organizing package structure, which helped me reorganize my package into a structure I was confi... | [
51
] | [] | [] | [
"python",
"setuptools",
"testing"
] | stackoverflow_0006164004_python_setuptools_testing.txt |
Q:
XML String to Python Object
So I have an XML string that I want to convert to JSON in Python 3.2. I was going to do that by converting the string to a python object via lxml and then convert the object to JSON via JSONEncoder.
Unfortunately, lxml does not seem to be built for Win32, does anyone have any suggestion... | XML String to Python Object | So I have an XML string that I want to convert to JSON in Python 3.2. I was going to do that by converting the string to a python object via lxml and then convert the object to JSON via JSONEncoder.
Unfortunately, lxml does not seem to be built for Win32, does anyone have any suggestions for an alternate XML - Python l... | [
"I have a super simple script that does this:\nXML to Python data structure « Python recipes « ActiveState Code\nhttp://code.activestate.com/recipes/534109-xml-to-python-data-structure/\nIt is mainly for people to reference XML data as an object in Python. For your purpose, you can introspect the node's content in ... | [
1,
1
] | [] | [] | [
"json",
"python",
"string",
"xml"
] | stackoverflow_0006164312_json_python_string_xml.txt |
Q:
How can I use both a key and an index for the same dictionary value?
I need an array of data that has a numeric index, but also a human readable index. I need the latter because the numeric indices may change in the future, and I need the numeric indices as a part of a fixed length socket message.
My imagination s... | How can I use both a key and an index for the same dictionary value? | I need an array of data that has a numeric index, but also a human readable index. I need the latter because the numeric indices may change in the future, and I need the numeric indices as a part of a fixed length socket message.
My imagination suggests something like this:
ACTIONS = {
(0, "ALIVE") : (1, 4, False),... | [
"The simplest way to achieve this is to have two dictionaries: One mapping the indices to your values, and one mapping the string keys to the same objects:\n>> actions = {\"alive\": (1, 4, False), \"dead\": (2, 1, True)}\n>> indexed_actions = {0: actions[\"alive\"], 2: actions[\"dead\"]}\n>> actions[\"alive\"]\n(1... | [
7,
6,
1,
1
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0006164973_python_python_2.7.txt |
Q:
compare list elements
How can I compare one element with the next one in a sorted list, and print out their differences. Any help would be appreciated.
Eg:
lst = [3.18,10.57,14.95,...]
10.57 - 3.18 = 7.39
14.95 - 10.57 = 4.38
...
A:
it = iter(lst)
it.next()
print [(x, y, y - x) for (x, y) in itertools.izip(lst... | compare list elements | How can I compare one element with the next one in a sorted list, and print out their differences. Any help would be appreciated.
Eg:
lst = [3.18,10.57,14.95,...]
10.57 - 3.18 = 7.39
14.95 - 10.57 = 4.38
...
| [
"it = iter(lst)\nit.next()\nprint [(x, y, y - x) for (x, y) in itertools.izip(lst, it)]\n\n",
"If you are manipulating numerical data, consider using numpy\nimport numpy as np\n\nlst = [3.18,10.57,14.95]\narr = np.array(lst)\n\ndiff = np.diff(arr)\n\n>>> diff\narray([ 7.39, 4.38])\n\nYou can convert it back to l... | [
6,
6,
4,
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0006165277_python.txt |
Q:
Appcelerator Python Application Requires Silverlight?
Something that I couldn't understand from appcelerator website:
If I use appcelerator to write a client-side python application for the web, will it require that users have silverlight installed on their machines?
A:
I got the answer from appcelerator develop... | Appcelerator Python Application Requires Silverlight? | Something that I couldn't understand from appcelerator website:
If I use appcelerator to write a client-side python application for the web, will it require that users have silverlight installed on their machines?
| [
"I got the answer from appcelerator developer center:\n\nThe php/python/ruby scripts are\n executed in the context of the\n Titanium Desktop. So you will need to\n run it inside a session of Ti Desktop\n application, and not on a webpage.\nTi Desktop is a modified webkit that\n knows how to handle this scripts... | [
0
] | [] | [] | [
"appcelerator",
"client_side",
"python",
"silverlight"
] | stackoverflow_0006163105_appcelerator_client_side_python_silverlight.txt |
Q:
unprintable string to number in python
The documentation http://docs.python.org/library/wave.html says
Wave_read.readframes(n)
Reads and returns at most n frames of audio, as a string of bytes.
I want to see these string in hex or just number for knowing then value when no sound is there or plus, minus sound is ... | unprintable string to number in python | The documentation http://docs.python.org/library/wave.html says
Wave_read.readframes(n)
Reads and returns at most n frames of audio, as a string of bytes.
I want to see these string in hex or just number for knowing then value when no sound is there or plus, minus sound is there
I tried
import wave
target = wave.op... | [
"print [ord(i) for i in section[0:2]]\n\nor\nprint [hex(ord(i)) for i in section[0:2]]\n\n"
] | [
2
] | [] | [] | [
"hex",
"printing",
"python",
"string"
] | stackoverflow_0006165418_hex_printing_python_string.txt |
Q:
Need to reference a local variable before assigning
I'm currently working on a permutation algorithm that will be used for a traveling sales person kind of problem. I have a method to calculate the cost of the cycle that will call a method (currentBest) to see if this permutation is better than currentBest one.
... | Need to reference a local variable before assigning | I'm currently working on a permutation algorithm that will be used for a traveling sales person kind of problem. I have a method to calculate the cost of the cycle that will call a method (currentBest) to see if this permutation is better than currentBest one.
def currentBest(newCost):
if newCost < currentB... | [
"If you're trying to find the smallest value in a list, just do:\n>>> min([9,2,4,8,5,6])\n2\n\n",
"Rather than use a magic number, initialise currentBest with Python's None. \nYou should then check whether currentBest is None and if it is, you can assign it the value of newCost and continue.\nE.g (in Python 2.7 a... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006165452_python.txt |
Q:
Where is the syntax error in this dictionary? [Python 2.7]
I'm not sure why this code isn't working. . . I can't find the syntax error it seems fine . It is in the same format as all my other dictionaries
d=dict(zip(('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T... | Where is the syntax error in this dictionary? [Python 2.7] | I'm not sure why this code isn't working. . . I can't find the syntax error it seems fine . It is in the same format as all my other dictionaries
d=dict(zip(('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'),('6','10.76','5.41'.'2.71','5.07','5.65','3.22','5.97','7.5... | [
"'5.41'.'2.71' should be '5.41', '2.71'\nBTW, you should break big lines in small ones:\nkeys = ['A', 'B', 'C',\n 'X', 'Y', 'Z']\nvalues = [1.0, 2.1, 3.2,\n 4.3, 5.4, 6.5]\nd = dict(zip(keys, values))\n\n",
"There's a '.' where there should be a ',' at '5.41'.'2.71'\n"
] | [
3,
0
] | [] | [] | [
"dictionary",
"python",
"string",
"syntax"
] | stackoverflow_0006165559_dictionary_python_string_syntax.txt |
Q:
Best ways to teach a beginner to program?
Original Question
I am currently engaged in teaching my brother to program. He is a total beginner, but very smart. (And he actually wants to learn). I've noticed that some of our sessions have gotten bogged down in minor details, and I don't feel I've been very organize... | Best ways to teach a beginner to program? | Original Question
I am currently engaged in teaching my brother to program. He is a total beginner, but very smart. (And he actually wants to learn). I've noticed that some of our sessions have gotten bogged down in minor details, and I don't feel I've been very organized. (But the answers to this post have helped a ... | [
"I've had to work with several beginner (never wrote a line of code) programmers, and I'll be doing an after school workshop with high school students this fall. This is the closest thing I've got to documentation. It's still a work in progress, but I hope it helps.\n1) FizzBuzz. Start with command line programs. Y... | [
118,
30,
28,
15,
12,
12,
11,
8,
7,
7,
5,
4,
4,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
... | [] | [] | [
"language_agnostic",
"python"
] | stackoverflow_0000003088_language_agnostic_python.txt |
Q:
How to quit a thrift server in Python
I am writing an application in Python that uses thrift to communicate between itself and a client. Whenever I try to exit the application (using Ctrl-C or the exit button on the window), the thrift server keeps the application alive, probably because the server.serve() functio... | How to quit a thrift server in Python | I am writing an application in Python that uses thrift to communicate between itself and a client. Whenever I try to exit the application (using Ctrl-C or the exit button on the window), the thrift server keeps the application alive, probably because the server.serve() function enters an infinite loop. What is the best... | [
"It turns out my problem was not actually thrift-specific. I was running an infinite loop in a non-daemonic thread; therefore, python waited for that thread to close before my whole program would close. Setting \"self.daemon = True\" in the thread's init method fixed the problem nicely.\n"
] | [
1
] | [] | [] | [
"python",
"thrift"
] | stackoverflow_0006159465_python_thrift.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.