content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python Popen hanging with psexec - undesired results
I'm having an issue with subprocess.Popen and what I believe to be pipes. I have the following block of code which works without issue 100% of the time when running from the cli:
p = subprocess.Popen("psexec \\\\" + serverName.get() + " cmd /c \
ver... | Python Popen hanging with psexec - undesired results | I'm having an issue with subprocess.Popen and what I believe to be pipes. I have the following block of code which works without issue 100% of the time when running from the cli:
p = subprocess.Popen("psexec \\\\" + serverName.get() + " cmd /c \
ver & \
echo %USERDOMAIN% & \
dir /a C:\pagef... | [
"[This should be a comment, but I don't have the rep to leave comments]\nI've heard of a lot of problems with subprocess.PIPE. Try making stdin, stdout, and stderr all point to temporary files. Then you can use p.wait() instead of communicate(). Does that seem to work correctly? \n",
"try running the psexec w... | [
0,
0,
0
] | [] | [] | [
"pipe",
"psexec",
"py2exe",
"python",
"subprocess"
] | stackoverflow_0005194713_pipe_psexec_py2exe_python_subprocess.txt |
Q:
Implementing a singleton class and (b)locking issues?
I was wondering about implementing a singleton class following http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/ but was wondering about any (b)locking issues. My code is suppose to cache SQL statements and execute all cac... | Implementing a singleton class and (b)locking issues? | I was wondering about implementing a singleton class following http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/ but was wondering about any (b)locking issues. My code is suppose to cache SQL statements and execute all cached statements using cursor.executemany(SQL, list-of-params... | [
"By avoiding lazy initialization the blocking problem will go away. In a module where initialization of your connection to the database is occurring import the module that contains the singleton and then immediately create an instance of the singleton that is not stored in a variable.\n#Do Database Initialization\n... | [
1,
1,
0,
0
] | [] | [] | [
"blocking",
"locking",
"python",
"singleton"
] | stackoverflow_0005126888_blocking_locking_python_singleton.txt |
Q:
How to do this equivalent C# OOP in python?
I need following structure in python.
public class Circle
{
int member1;
int member2;
int member3;
public Circle(member1)
{
this.member1 = member1;
initializeRest();
}
private intializeRest()
{
//do lot of compu... | How to do this equivalent C# OOP in python? | I need following structure in python.
public class Circle
{
int member1;
int member2;
int member3;
public Circle(member1)
{
this.member1 = member1;
initializeRest();
}
private intializeRest()
{
//do lot of computation to get result1 & result2
this.memb... | [
"class Circle:\n def __init__(self, member1):\n self.member1=member1\n self.rest()\n\n def rest(self):\n self.member2=result2\n self.member3=result2\n\n",
"Python does not have enforced private anything; the convention for letting others know that a method/function/class/what-have-you is p... | [
7,
1
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0003141222_c#_python.txt |
Q:
How to capture an image using selenium pythons script
I want to test the image displayed in my web application. please anyone provide me the solution.
I have used sel.capture_entire_page_screenshot("C:\Users\test\Desktop\privacy.png", "")
it is not working.
A:
One problem with that is that the backslashes aren'... | How to capture an image using selenium pythons script | I want to test the image displayed in my web application. please anyone provide me the solution.
I have used sel.capture_entire_page_screenshot("C:\Users\test\Desktop\privacy.png", "")
it is not working.
| [
"One problem with that is that the backslashes aren't escaped, so \\t\nbecomes a tab character. Try this (the r makes it a \"raw string\" where\nbackslashes have no special meaning):\nsel.capture_entire_page_screenshot(r\"C:\\Users\\test\\Desktop\\privacy.png\", \"\")\n\n"
] | [
0
] | [] | [] | [
"python",
"selenium_rc"
] | stackoverflow_0006837153_python_selenium_rc.txt |
Q:
Taking a snapshot from webcam monitor in python (pygtk)
I have this code for monitoring a webcam with python and pygtk.
The question is, how I take a snapshot with this code?:
#!/usr/bin/env python
import sys, os
import pygtk, gtk, gobject
import pygst
pygst.require("0.10")
import gst
import time
class WebCam:
... | Taking a snapshot from webcam monitor in python (pygtk) | I have this code for monitoring a webcam with python and pygtk.
The question is, how I take a snapshot with this code?:
#!/usr/bin/env python
import sys, os
import pygtk, gtk, gobject
import pygst
pygst.require("0.10")
import gst
import time
class WebCam:
def __init__(self):
window = gtk.Window(gtk.WINDOW... | [
"I'm missing the point of the question. There's a take_snapshot function with the bit that actually takes the snapshot commented out. Modify your code to look like the following\ndef take_snapshot(self,widget):\n filename = str(time.time()) + \".jpg\" \n pixbuf = gtk.gdk.Pixbuf.get_from_drawable(self.movie_wi... | [
1
] | [] | [] | [
"gstreamer",
"pygtk",
"python"
] | stackoverflow_0007324908_gstreamer_pygtk_python.txt |
Q:
Determine whether any files have been added, removed, or modified in a directory
I'm trying to write a Python script that will get the md5sum of all files in a directory (in Linux). Which I believe I have done in the code below.
I want to be able to run this to make sure no files within the directory have chang... | Determine whether any files have been added, removed, or modified in a directory | I'm trying to write a Python script that will get the md5sum of all files in a directory (in Linux). Which I believe I have done in the code below.
I want to be able to run this to make sure no files within the directory have changed, and no files have been added for deleted.
The problem is if I make a change to a f... | [
"As the other answers mentioned, two tar files can be different even if the contents are the same either due to tar metadata changes or to file order changes. You should run the checksum on the file data directly, sorting the directory lists to ensure they are always in the same order. If you want to include some m... | [
8,
7,
3,
1
] | [] | [] | [
"hashlib",
"md5",
"python",
"tar",
"tarfile"
] | stackoverflow_0007325072_hashlib_md5_python_tar_tarfile.txt |
Q:
Get facebook emails using django
I'm using django-socialregistration and facebook python sdk.
This is the code to get friends:
friends = request.facebook.graph.get_connections('me', 'friends')
I can get their name and id but I can't get their email address (not their @facebook.com email).
This is another attempt... | Get facebook emails using django | I'm using django-socialregistration and facebook python sdk.
This is the code to get friends:
friends = request.facebook.graph.get_connections('me', 'friends')
I can get their name and id but I can't get their email address (not their @facebook.com email).
This is another attempt which also can't get their email.
fo... | [
"It is possible to get the email of a user connected to your app using Graph. However, when connecting or signing in using Facebook users must explicitly give you permission to use their email address. Since none of the friends gave you permission, their e-mail addresses are off limits. What this means is you can e... | [
2,
0
] | [] | [] | [
"django",
"facebook",
"facebook_graph_api",
"python"
] | stackoverflow_0007321822_django_facebook_facebook_graph_api_python.txt |
Q:
Pythonic thread-safe object
After reading a lot on this subject and discussing on IRC, the response seems to be: stay away from threads. Sorry for repeating this question, my intention is to go deeper in the subject by not accepting the "threading is evil" answer, with the hope to find a common solution.
EDIT: Jus... | Pythonic thread-safe object | After reading a lot on this subject and discussing on IRC, the response seems to be: stay away from threads. Sorry for repeating this question, my intention is to go deeper in the subject by not accepting the "threading is evil" answer, with the hope to find a common solution.
EDIT: Just Say No to the combined evils of... | [
"If you don't want to lock, then either don't use globals, or use thread-local storage (in a webapp, you can be fairly sure that a request won't cross thread boundary). If global state can be avoided, it should be avoided. This makes multi-threading way easier to implement and debug.\nI also disagree that passing o... | [
5
] | [] | [] | [
"global",
"multithreading",
"object",
"python"
] | stackoverflow_0007322299_global_multithreading_object_python.txt |
Q:
Rebuild list with set set length
I'm building a Python script to do a network inventory on our internal system. Each system has up to five clusters and I am looking for a way to adjust the list to put them all into one line per cluster. Here's the way they are stored on the system:
Cluster One
Primary System
... | Rebuild list with set set length | I'm building a Python script to do a network inventory on our internal system. Each system has up to five clusters and I am looking for a way to adjust the list to put them all into one line per cluster. Here's the way they are stored on the system:
Cluster One
Primary System
Node One
x.x.x.x (Node IP)
Node tw... | [
"First look: How do you split a list into evenly sized chunks?\nUsing one of the answers:\n>>> import itertools\n>>> NetworkTable\n['Cluster One', 'Primary System', 'Node One', 'x.x.x.x (Node IP)', 'Node two', 'x.x.x.x (Node IP)', 'Cluster Two', 'Primary System', 'Node One', 'x.x.x.x (Node IP)', 'Node two', 'x.x.x.... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0007324163_python.txt |
Q:
twisted conch, overriding authentication
I have been trying to override the default authentication scheme in a twisted conch module. Something that I thought I understood how to do. The script itself is the answer to this
question. I am subclassing SSHUserAuthClient in the following way:
class ClientUserAuth(SSHUs... | twisted conch, overriding authentication | I have been trying to override the default authentication scheme in a twisted conch module. Something that I thought I understood how to do. The script itself is the answer to this
question. I am subclassing SSHUserAuthClient in the following way:
class ClientUserAuth(SSHUserAuthClient):
def getPassword(self, promp... | [
"You're probably actually seeing keyboard-interactive authentication taking place. This is like password authentication, but separate. The reason you see different behavior between Linux and OS X is just that your Linux and OS X SSH servers are configured differently.\nOverride getGenericAnswers to handle this on... | [
3,
3
] | [] | [] | [
"python",
"ssh",
"twisted"
] | stackoverflow_0005211526_python_ssh_twisted.txt |
Q:
Any Python alternatives to Selenium for programmatically logging into websites that require JavaScript for login?
I’m writing a little private app to automatically log into my internet banking every day, and download the latest transactions. I’m writing it as a Django app, so I’m working in Python.
My internet ban... | Any Python alternatives to Selenium for programmatically logging into websites that require JavaScript for login? | I’m writing a little private app to automatically log into my internet banking every day, and download the latest transactions. I’m writing it as a Django app, so I’m working in Python.
My internet banking doesn’t seem to work without JavaScript — I think it uses JavaScript to assign a session ID of some sort. Fetching... | [
"since you use selenium I think you have already installed firefox. if so get an extension like firebug or tamper data and see what http-requests the javascript code will do while logging in.\nif you have the url and the parameters needed you can easily program a python client with httplib or urllib2.\nin firebug y... | [
8,
6,
3,
3,
1
] | [
"Since BeautifulSoup is no longer being actively developed I would recommend lxml since it does all the things that BeautifulSoup can do and a lot more.\n"
] | [
-2
] | [
"javascript",
"python",
"selenium"
] | stackoverflow_0002127181_javascript_python_selenium.txt |
Q:
Suggestions on processing large file - python or command line?
Given two files, one containing entries of the form:
label1 label2 name1
label1 label3 name2
and the other of the form:
label1 label2 name1 0.1 1000
label9 label6 name7 0.8 0.5
Suppose you want to extract those lines from file two for which the first... | Suggestions on processing large file - python or command line? | Given two files, one containing entries of the form:
label1 label2 name1
label1 label3 name2
and the other of the form:
label1 label2 name1 0.1 1000
label9 label6 name7 0.8 0.5
Suppose you want to extract those lines from file two for which the first three elements appear in a line (order important) in file one - any... | [
"Your python version is rather inefficient because you're testing for membership in a list, rather than a set or a dict (i.e. O(n) lookup time instead of O(1)).\nTry using a set of tuples or a set of strings instead. Tuples would be a better choice as the two files could be split on different delimiters, but I don'... | [
8,
3,
1,
1
] | [] | [] | [
"command_line",
"parsing",
"python"
] | stackoverflow_0007325949_command_line_parsing_python.txt |
Q:
Generating User IDs in Python
I've created a simple DB using SQLAlchemy in python and there is a column for a unique user ID for each user entered. I want to have a running counter that supplies the next ID whenever a new User is added.
What would be the best way to implement this? A column with the value of the l... | Generating User IDs in Python | I've created a simple DB using SQLAlchemy in python and there is a column for a unique user ID for each user entered. I want to have a running counter that supplies the next ID whenever a new User is added.
What would be the best way to implement this? A column with the value of the last id number, or would that be an ... | [
"Read this: http://www.sqlalchemy.org/docs/core/schema.html#defining-sequences.\nKey generation is a part of the database.\nYou simply want the database to assign unique keys.\n",
"What database are you using? If it's MySQL you might be done already. Try creating a User where User.id = None. It should take the... | [
5,
0,
0
] | [] | [] | [
"database",
"python",
"sqlalchemy",
"userid"
] | stackoverflow_0007325501_database_python_sqlalchemy_userid.txt |
Q:
List coordinates between a set of coordinates
This should be fairly easy, but I'm getting a headache from trying to figure it out. I want to list all the coordinates between two points. Like so:
1: (1,1)
2: (1,3)
In between: (1,2)
Or
1: (1,1)
2: (5,1)
In between: (2,1), (3,1), (4,1)
It does not need to work with... | List coordinates between a set of coordinates | This should be fairly easy, but I'm getting a headache from trying to figure it out. I want to list all the coordinates between two points. Like so:
1: (1,1)
2: (1,3)
In between: (1,2)
Or
1: (1,1)
2: (5,1)
In between: (2,1), (3,1), (4,1)
It does not need to work with diagonals.
| [
"You appear to be a beginning programmer. A general technique I find useful is to do the job yourself, on paper, then look at how you did it and translate that to a program. If you can't see how, break it down into simpler steps until you can.\n",
"Depending on how you want to handle the edge cases, this seems to... | [
4,
2
] | [] | [] | [
"graph",
"math",
"python"
] | stackoverflow_0007326129_graph_math_python.txt |
Q:
Django roll-up (collapsible) menu
I have a web app with three frames (banner, menu, content)
The menu frame needs to have a dynamic roll-up menu
Example:
+ Teachers
- Create
- Edit
- Delete
+ Schools
- Create
- Edit
- Delete
- View Staff
+ Classrooms
- Create
- Edit
- Delete
If you click on ... | Django roll-up (collapsible) menu | I have a web app with three frames (banner, menu, content)
The menu frame needs to have a dynamic roll-up menu
Example:
+ Teachers
- Create
- Edit
- Delete
+ Schools
- Create
- Edit
- Delete
- View Staff
+ Classrooms
- Create
- Edit
- Delete
If you click on the + or "Schools" it will hide/un-hide... | [
"Simple implementation using jQuery:\n<div id=\"menu\">\n <a>Teachers</a><br />\n <div style=\"display: none\">\n <a href=\"\">Edit</a><br />\n <a href=\"\">Delete</a><br /> \n </div>\n <a>Schools</a><br />\n <div style=\"display: none\">\n <a href=\"\">Edit</a><br />\n <a... | [
6,
1
] | [] | [] | [
"django",
"menu",
"python"
] | stackoverflow_0007326158_django_menu_python.txt |
Q:
How should I handle working with celeryd_multi from code?
So far, I've been working only with python manage.py celeryd, starting it like this:
python manage.py celeryd -l info --settings=settings
The code from my view, does this:
BinaryExecTask.delay(request.POST["binary_path"])
And the code from my settings.py, ... | How should I handle working with celeryd_multi from code? | So far, I've been working only with python manage.py celeryd, starting it like this:
python manage.py celeryd -l info --settings=settings
The code from my view, does this:
BinaryExecTask.delay(request.POST["binary_path"])
And the code from my settings.py, is this:
import djcelery
djcelery.setup_loader()
BROKER_BACKEN... | [
"Looks like smth Windows-specific... Did you try to provide full path to python executable in command line like\nC:\\code\\python27\\bin\\python.exe manage.py celeryd_multi start 3 --settings=settings -l info\n\nAlso, use full paths for python file can be usefull\nC:\\code\\python27\\bin\\python.exe C:\\path\\to\\... | [
1
] | [] | [] | [
"celery",
"django",
"multitasking",
"python"
] | stackoverflow_0007325850_celery_django_multitasking_python.txt |
Q:
Save python queue to a file
I am using the Python Queue cclass to manage a list of tasks that are shared between multiple worker threads. The actual code is humungous and I'm still in the process of making it entirely bug free. Time to time, the worker threads will crash and I have to restart the whole routine. In... | Save python queue to a file | I am using the Python Queue cclass to manage a list of tasks that are shared between multiple worker threads. The actual code is humungous and I'm still in the process of making it entirely bug free. Time to time, the worker threads will crash and I have to restart the whole routine. In the process I lose all the tasks... | [
"Have you considered simply pickling your queue?\n",
"There are multiple approach to this, including the pickle module... \nBut in my opinion it would be simples to just write to a file, line per line, each element of the queue in collumns containing other properties you may want to save, like the task_done.\nexa... | [
5,
1,
0,
0,
0
] | [] | [] | [
"multithreading",
"non_volatile",
"python",
"queue"
] | stackoverflow_0006944940_multithreading_non_volatile_python_queue.txt |
Q:
Why is this error thrown in my code - Python?
Why does this error appear?
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27_1\lib\lib-tk\Tkinter.py", line 1410, in __call_
return self.func(*args)
File "editor.py", line 90, in onOpen
fileopened = open(fno, "w+")
T... | Why is this error thrown in my code - Python? | Why does this error appear?
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27_1\lib\lib-tk\Tkinter.py", line 1410, in __call_
return self.func(*args)
File "editor.py", line 90, in onOpen
fileopened = open(fno, "w+")
TypeError: coercing to Unicode: need string or buffe... | [
"askopenfile returns the opened file to you, not its name, so there's no need to call open on it. If you really want the name, you can use askopenfilename instead, but it doesn't seem necessary for what you're doing.\n",
"It's just like it says:\nfileopened = open(fno, \"w+\")\n\nThat's the line of code that had ... | [
4,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007323524_python.txt |
Q:
Any way of performing the task using python cgi?
I currently wrote the following task in Javascript, but I would like to execute the same task using python cgi. Do you have any tips to perform that with python cgi?
<a href"#" onClick="parent.Content.location='https://snu.ac.kr/music.html'; return false;">Music</a>... | Any way of performing the task using python cgi? | I currently wrote the following task in Javascript, but I would like to execute the same task using python cgi. Do you have any tips to perform that with python cgi?
<a href"#" onClick="parent.Content.location='https://snu.ac.kr/music.html'; return false;">Music</a>
The task is basically as follows: when a user click... | [
"CGI is not good (as far as i read from internet) it will run a new python process everytime someone will run the script! and this is not good for your server!\nmaybe FastCGI is better (it will run a long single process that will handle request)\n"
] | [
0
] | [] | [] | [
"cgi",
"javascript",
"onclick",
"python"
] | stackoverflow_0007326471_cgi_javascript_onclick_python.txt |
Q:
Why does this pygtk TextView refuse to wrap?
I have a textview inside a scrolledwindow that refuses to wrap to words/chars/wordschars no matter how I set the wrap mode. It simply extends the size of itself and its containers as it pleases. Here's an example:
import gtk
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
win... | Why does this pygtk TextView refuse to wrap? | I have a textview inside a scrolledwindow that refuses to wrap to words/chars/wordschars no matter how I set the wrap mode. It simply extends the size of itself and its containers as it pleases. Here's an example:
import gtk
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_default_size(256,256)
scroll = gtk.Scrolle... | [
"You need to set the size request on the TextView's container (which is scroll in your example), not the Window or the TextView itself.\nTry the following:\nimport gtk\n\nif __name__ == \"__main__\":\n window = gtk.Window(gtk.WINDOW_TOPLEVEL)\n scroll = gtk.ScrolledWindow()\n scroll.set_policy(gtk.POLICY_N... | [
2,
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0006633312_gtk_pygtk_python.txt |
Q:
Is there an FTP equivalent of Python's makedirs()?
I'm FTP'ing a pile of files with Python and some directory trees may not exist. Is there an FTP version of makedirs() available somewhere or will I have to build my own from scratch?
A:
After posting this, I discovered a nifty little library, ftputil (http://ftp... | Is there an FTP equivalent of Python's makedirs()? | I'm FTP'ing a pile of files with Python and some directory trees may not exist. Is there an FTP version of makedirs() available somewhere or will I have to build my own from scratch?
| [
"After posting this, I discovered a nifty little library, ftputil (http://ftputil.sschwarzer.net), that presents a different FTP interface that cribs as much of the os and os.path modules as possible. Using this, my final code went roughly like this:\nimport ftputil\n\nhost = ftputil.FTPHost(constants.FTP_HOST, con... | [
3
] | [] | [] | [
"ftp",
"python"
] | stackoverflow_0007322014_ftp_python.txt |
Q:
Python Memory Error
I'm runing into Memory Error
Using python 2.6, pyodbc
The code loops through several Sql statements. Singleton run Ok, but the loops get stuck.
Sometimes Loop works ok.
for Sql in LoopList:
f = csr.execute(Sql)
LL = list(f)
The second element in loop crashes.
Sql:
Sql =""" SELE... | Python Memory Error | I'm runing into Memory Error
Using python 2.6, pyodbc
The code loops through several Sql statements. Singleton run Ok, but the loops get stuck.
Sometimes Loop works ok.
for Sql in LoopList:
f = csr.execute(Sql)
LL = list(f)
The second element in loop crashes.
Sql:
Sql =""" SELECT * FROM group WHERE
... | [
"Your query is returning too much data to fit into memory. The execute is probably returning an iterator which only needs to keep one item in memory at a time, but converting that into a list requires every single item returned from the query to fit into memory.\n",
"The solution was to do sql looplist inside MyS... | [
4,
0
] | [] | [] | [
"memory",
"python"
] | stackoverflow_0006862149_memory_python.txt |
Q:
Problem with reading in parameters with special characters in Python
I have a scripts (a.py) reads in 2 parameters like this:-
#!/usr/bin/env python
import sys
username = sys.argv[1]
password = sys.argv[2]
Problem is, when I call the script with some special characters:-
a.py "Lionel" "my*password"
It gives... | Problem with reading in parameters with special characters in Python | I have a scripts (a.py) reads in 2 parameters like this:-
#!/usr/bin/env python
import sys
username = sys.argv[1]
password = sys.argv[2]
Problem is, when I call the script with some special characters:-
a.py "Lionel" "my*password"
It gives me this error:-
/swdev/tools/python/current/linux64/bin/python: No match.... | [
"The problem is in the commands you're actually using, which are not the same as the commands you've shown us. Evidence: in Perl, the first two command-line arguments are $ARGV[0] and $ARGV[1] (the command name is $0). The Perl script you showed us wouldn't produce the output you showed us.\n\"No match\" is a she... | [
1,
0,
0
] | [] | [] | [
"csh",
"parameter_passing",
"perl",
"python",
"shell"
] | stackoverflow_0007160583_csh_parameter_passing_perl_python_shell.txt |
Q:
How to edit single Entity in GAE (Python)?
I'm doing my first small project in Python(GAE), and there's no difficulty in operating GAE's database using queries. But when it comes to editing single Entity I face a problem.
All I need is a simple counter which would increment on every site visit.
So I create an Enti... | How to edit single Entity in GAE (Python)? | I'm doing my first small project in Python(GAE), and there's no difficulty in operating GAE's database using queries. But when it comes to editing single Entity I face a problem.
All I need is a simple counter which would increment on every site visit.
So I create an Entity (this is done once, just to create Entity, th... | [
"The code you use to create the Counter entity is likely wrong. What it does is creating a Counter entity whose parent is Counter with keyname equal to default_counter. That doesn't seem to be what your want, as evidenced by code you use to update the counter.\nYou need to assign the keyname of your Counter entity ... | [
2,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007326657_google_app_engine_google_cloud_datastore_python.txt |
Q:
Iterating a loop with a pause
I am working to integrate with an API that has a limit on the number of requests per second. Is there a way, when running a for loop in python to delay each cycle? Conceptually, something like --
def function(request):
for x in [a,b,c,d,...]:
do something
wait y se... | Iterating a loop with a pause | I am working to integrate with an API that has a limit on the number of requests per second. Is there a way, when running a for loop in python to delay each cycle? Conceptually, something like --
def function(request):
for x in [a,b,c,d,...]:
do something
wait y seconds
Thank you.
| [
"import time\n...\ntime.sleep(5)\n\nThis will sleep for 5 seconds. See http://docs.python.org/library/time.html#time.sleep\n"
] | [
9
] | [] | [] | [
"python"
] | stackoverflow_0007326950_python.txt |
Q:
Set polar plot to have 0 degrees at the top
I have created a simple polar plot using matplotlib. I'm trying to make the plot with 0 degrees at the top (12 o'clock position) rather than the right-hand side (3 o'clock position). I can't see any simple way to do this in the matplotlib documentation.
I've found an old... | Set polar plot to have 0 degrees at the top | I have created a simple polar plot using matplotlib. I'm trying to make the plot with 0 degrees at the top (12 o'clock position) rather than the right-hand side (3 o'clock position). I can't see any simple way to do this in the matplotlib documentation.
I've found an older question here on StackOverflow, but the accept... | [
"Replace angle with angle - pi/4?\n"
] | [
3
] | [] | [] | [
"matplotlib",
"plot",
"python"
] | stackoverflow_0007327205_matplotlib_plot_python.txt |
Q:
Unable to fully remove border of PyQt QGraphicsView
I have tried calling self.setStyleSheet("background: transparent; border: transparent;") on a QGraphicsView, but it still leaves a 1 pixel border on the top edge. I have also tried replacing border: transparent; with border-style: none;, but it didn't work either... | Unable to fully remove border of PyQt QGraphicsView | I have tried calling self.setStyleSheet("background: transparent; border: transparent;") on a QGraphicsView, but it still leaves a 1 pixel border on the top edge. I have also tried replacing border: transparent; with border-style: none;, but it didn't work either.
Here is a screenshot of the problem:
What command will... | [
"You can use one of the following css rule:\ngraphicsView.setStyleSheet(\"border-width: 0px; border-style: solid\")\n\nor\ngraphicsView.setStyleSheet(\"border: 0px\")\n\nYour border should disappear.\nimport sys\nfrom PyQt4.QtGui import *\n\nclass Ui(QWidget):\n\n def __init__(self, parent=None):\n QWidge... | [
10,
0
] | [] | [] | [
"css",
"pyqt",
"python",
"qgraphicsview",
"qt"
] | stackoverflow_0007325911_css_pyqt_python_qgraphicsview_qt.txt |
Q:
python quickest way to merge dictionaries based on key match
I have 2 lists of dictionaries. List A is 34,000 long, list B is 650,000 long. I am essentially inserting all the List B dicts into the List A dicts based on a key match. Currently, I am doing the obvious, but its taking forever (seriously, like a day... | python quickest way to merge dictionaries based on key match | I have 2 lists of dictionaries. List A is 34,000 long, list B is 650,000 long. I am essentially inserting all the List B dicts into the List A dicts based on a key match. Currently, I am doing the obvious, but its taking forever (seriously, like a day). There must be a quicker way!
for a in listA:
a['things'] =... | [
"from collections import defaultdict\ndictB = defaultdict(list)\nfor b in listB:\n dictB[b['ID']].append(b)\n\nfor a in listA:\n a['things'] = []\n for b in dictB[a['ID']]:\n a['things'].append(b)\n\nthis will turn your algorithm from O(n*m) to O(m)+O(n), where n=len(listA), m=len(listB)\nbasically ... | [
4,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007327344_dictionary_python.txt |
Q:
Any way of storing the clicked word (from the html) in the separate file in the server?
The following html works as "when a user clicks the word "Music", it shows the html page (i.e. 'https://snu.ac.kr/music.html')"
<a href"#" onClick="parent.Content.location='https://snu.ac.kr/music.html'; return
false;">M... | Any way of storing the clicked word (from the html) in the separate file in the server? | The following html works as "when a user clicks the word "Music", it shows the html page (i.e. 'https://snu.ac.kr/music.html')"
<a href"#" onClick="parent.Content.location='https://snu.ac.kr/music.html'; return
false;">Music</a>
My question is : when the user clicks the word in the web, is there any way for th... | [
"You should use Javascript to do an AJAX-style post in the background to save whatever information you'd like on click. Then redirect the page on success.\n"
] | [
1
] | [] | [] | [
"cgi",
"onclick",
"python"
] | stackoverflow_0007327678_cgi_onclick_python.txt |
Q:
What is a straight forward approach to matching and enumerating the results of a quiz using Python
In the code below (which shows all my neophyteness in Python), I took the books of the KJV Bible and put them in logical order via a list and dictionary. I then used a random method to display 5 random books to a use... | What is a straight forward approach to matching and enumerating the results of a quiz using Python | In the code below (which shows all my neophyteness in Python), I took the books of the KJV Bible and put them in logical order via a list and dictionary. I then used a random method to display 5 random books to a user along with the position of the each book in a random list for the user to match (something for me to b... | [
"One thing that might help you is to use lists, list comprehension statements and loops, e.g. \nq_count = int(raw_input('How many questions per quiz?'))\n\nquiz_items = [str(sampler(x)) for x in range(q_count)]\nuser_sel = [mydict_book[x] for x in quiz_items]\n\n...\nanswers = []\nfor i in range(q_count):\n next... | [
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007325763_python.txt |
Q:
Printing directly from read() in Python adds an extra newline
I've got a Python script that prints out a file to the shell:
print open(lPath).read()
If I pass in the path to a file with the following contents (no brackets, they're just here so newlines are visible):
> One
> Two
>
I get the following output:
> O... | Printing directly from read() in Python adds an extra newline | I've got a Python script that prints out a file to the shell:
print open(lPath).read()
If I pass in the path to a file with the following contents (no brackets, they're just here so newlines are visible):
> One
> Two
>
I get the following output:
> One
> Two
>
>
Where's that extra newline coming from? I'm running... | [
"Use\nprint open(lPath).read(), # notice the comma at the end.\n\nprint adds a newline. If you end the print statement with a comma, it'll add a space instead.\nYou can use\nimport sys\nsys.stdout.write(open(lPath).read())\n\nIf you don't need any of the special features of print.\nIf you switch to Python 3, or us... | [
8,
1
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0007327911_file_io_python.txt |
Q:
Buildout recipe for a hierarchy of parts
Is there a Python buildout recipe which would allow the following:
[buildout]
parts = group-of-parts
[group-of-parts]
recipe = what.can.i.use.for.this
parts = part-1 part-2
[part-1]
...
[part-2]
...
In other words, I want a recipe which takes a 'parts' attribute much li... | Buildout recipe for a hierarchy of parts | Is there a Python buildout recipe which would allow the following:
[buildout]
parts = group-of-parts
[group-of-parts]
recipe = what.can.i.use.for.this
parts = part-1 part-2
[part-1]
...
[part-2]
...
In other words, I want a recipe which takes a 'parts' attribute much like 'buildout' section does so I can manually m... | [
"No, there is no hierarchy, although you could build a recipe for it, of course.\nWhy do you want it? It's not like you end up with hundreds of parts so it's hard to keep track of them...\n",
"Some time ago I wrote an article on dependency resolution in buildout. Its not an answer to your question, because what y... | [
1,
0,
0
] | [] | [] | [
"buildout",
"python"
] | stackoverflow_0001135082_buildout_python.txt |
Q:
How to generate a sequence of future datetimes in Python and determine nearest datetime from set
I need to generate four datetime objects in Python:
"The next instance of 5:30AM EST"
"The next instance of 8:30AM EST"
"The next instance of 1:00PM EST"
"The next instance of 5:30PM EST"
Then I need to find which of ... | How to generate a sequence of future datetimes in Python and determine nearest datetime from set | I need to generate four datetime objects in Python:
"The next instance of 5:30AM EST"
"The next instance of 8:30AM EST"
"The next instance of 1:00PM EST"
"The next instance of 5:30PM EST"
Then I need to find which of those is closest to the current date/time.
I wish I could say I have some starting code, but I have no... | [
"This should get you started. I have the current time being passed into the function as a datetime, so if the argument is in EST, this should just work.\ndef find_next(cur_dt):\n import datetime as dt\n t = [dt.time(5,30), dt.time(8,30), dt.time(13,0), dt.time(17,30)]\n\n cur_t = cur_dt.time()\n cur_d ... | [
1,
0
] | [] | [] | [
"datetime",
"python",
"sequence"
] | stackoverflow_0007327689_datetime_python_sequence.txt |
Q:
Numpy multidimensional array slicing
Suppose I have defined a 3x3x3 numpy array with
x = numpy.arange(27).reshape((3, 3, 3))
Now, I can get an array containing the (0,1) element of each 3x3 subarray with x[:, 0, 1], which returns array([ 1, 10, 19]). What if I have a tuple (m,n) and want to retrieve the (m,n) el... | Numpy multidimensional array slicing | Suppose I have defined a 3x3x3 numpy array with
x = numpy.arange(27).reshape((3, 3, 3))
Now, I can get an array containing the (0,1) element of each 3x3 subarray with x[:, 0, 1], which returns array([ 1, 10, 19]). What if I have a tuple (m,n) and want to retrieve the (m,n) element of each subarray(0,1) stored in a tu... | [
"you can create the index tuple first:\nindex = (numpy.s_[:],)+t \nx[index]\n\n",
"HYRY solution is correct, but I have always found numpy's r_, c_ and s_ index tricks to be a bit strange looking. So here is the equivalent thing using a slice object:\nx[(slice(None),) + t]\n\nThat single argument to slice is th... | [
9,
4
] | [] | [] | [
"arrays",
"indexing",
"multidimensional_array",
"numpy",
"python"
] | stackoverflow_0007326924_arrays_indexing_multidimensional_array_numpy_python.txt |
Q:
python design pattern for abstracting data access: advantages, disadvantages?
I was wondering for a few ways to accomplish abstracting the data storage access away from the main application and a small example, an IoC framework seems overkill, maybe passing object via constructor parameter (facade).
is the below p... | python design pattern for abstracting data access: advantages, disadvantages? | I was wondering for a few ways to accomplish abstracting the data storage access away from the main application and a small example, an IoC framework seems overkill, maybe passing object via constructor parameter (facade).
is the below pseudo-code a good way to do things and how do i fill in the missing pieces with pyt... | [
"You're about to create Yet Another ORM layer. \nRather than waste a lot of time reinventing that wheel, learn about existing ORM, and adapt one to your noSQL database engine of choice.\nStart, for example, with SQLAlchemy as an ORM that can do all of what you want (and more) for SQL. \nBecause of Python's duck t... | [
2,
1,
0
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0007327347_design_patterns_python.txt |
Q:
Appending large amount of data to a tables (HDF5) database where database.numcols != newdata.numcols?
I am trying to append a large dataset (>30Gb) to an existing pytables table. The table is N columns, and the dataset is N-1 columns; one column is calculated after I know the other N-1 columns.
I'm using numpy.fr... | Appending large amount of data to a tables (HDF5) database where database.numcols != newdata.numcols? | I am trying to append a large dataset (>30Gb) to an existing pytables table. The table is N columns, and the dataset is N-1 columns; one column is calculated after I know the other N-1 columns.
I'm using numpy.fromfile() to read chunks of the dataset into memory before appending it to the database. Ideally, I'd like ... | [
"You could add the results to another table. Unless there's some compelling reason for the calculated column to be adjacent to the other columns, that's probably the easiest. There's something to be said for separating raw data from calculations anyways. \nIf you must increase the size of the table, look into us... | [
2,
2
] | [] | [] | [
"hdf5",
"numpy",
"pytables",
"python"
] | stackoverflow_0007327739_hdf5_numpy_pytables_python.txt |
Q:
How to efficiently store this parsed XML document in MySQL Database using Python?
Following is the XML file : book.xml
<?xml version="1.0" ?>
<!--Sample XML Document-->
<bookstore>
<book _id="E7854">
<title>
Sample XML Book
</title>
<author>
<name _id="AU363">
... | How to efficiently store this parsed XML document in MySQL Database using Python? | Following is the XML file : book.xml
<?xml version="1.0" ?>
<!--Sample XML Document-->
<bookstore>
<book _id="E7854">
<title>
Sample XML Book
</title>
<author>
<name _id="AU363">
<first>
Benjamin
</first>
<last>
Smith
... | [
"Based on your comment above, I would simply create a book class, an author class, an author list, and a chapter class. Assign the chapters of the book to a list of Chapter objects on the Book itself. Maintain the AuthorList as a dict of their IDs, pointing to the actual Author objects. Use a data member of the Boo... | [
2
] | [] | [] | [
"dom",
"mysql",
"python",
"xml",
"xml_parsing"
] | stackoverflow_0007327924_dom_mysql_python_xml_xml_parsing.txt |
Q:
Python pytz Converting a timestamp (string format) from one timezone to another
I have a timestamp with timezone information in string format and I would like to convert this to display the correct date/time using my local timezone. So for eg... I have
timestamp1 = 2011-08-24 13:39:00 +0800
and I would like to co... | Python pytz Converting a timestamp (string format) from one timezone to another | I have a timestamp with timezone information in string format and I would like to convert this to display the correct date/time using my local timezone. So for eg... I have
timestamp1 = 2011-08-24 13:39:00 +0800
and I would like to convert this to say timezone offset +1000 to dsiplay
timestamp2 = 2011-08-24 15:39:00 +... | [
"datetime.astimezone will do your basic conversion once you have a datetime object. If you're trying to get a datetime object from a string, pip install python-dateutil and it's as simple as:\n>>> from dateutil.parser import parse\n>>> from dateutil.tz import tzoffset\n>>> dt = parse('2011-08-24 13:39:00 +0800')\nd... | [
14
] | [] | [] | [
"python",
"pytz",
"timestamp",
"timezone"
] | stackoverflow_0007328630_python_pytz_timestamp_timezone.txt |
Q:
How to modify blobstoreuploadhandler to admit status 200?
It's said that GAE SDK 1.5.4 has removed the requirement that blobstoreuploadhandler must return a redirect and on production it's supposedly already so that the handler can make a "regular" response to a template with template variables. I need this capabi... | How to modify blobstoreuploadhandler to admit status 200? | It's said that GAE SDK 1.5.4 has removed the requirement that blobstoreuploadhandler must return a redirect and on production it's supposedly already so that the handler can make a "regular" response to a template with template variables. I need this capability with dev_appserver and therefore ask how I can modify the ... | [
"The solution was posted and I could verify that this worked: \ndef EndRedirect(self, dispatched_output, original_output):\n\n\"\"\"Handle the end of upload complete notification. Makes sure the application upload handler returned an appropriate status code. \"\"\"\n\n response = dev_appserver.RewriteResponse(di... | [
0
] | [] | [] | [
"blobstore",
"google_app_engine",
"python"
] | stackoverflow_0007217021_blobstore_google_app_engine_python.txt |
Q:
How do you compile python with >1024 file descriptors?
The workaround for an issue in supervisord is to:
"compile a Python that supports > 1024 file descriptors"
https://github.com/Supervisor/supervisor/issues/26
Can someone please walk me through what changes are necessary to accomplish this? I have the python 2.... | How do you compile python with >1024 file descriptors? | The workaround for an issue in supervisord is to:
"compile a Python that supports > 1024 file descriptors"
https://github.com/Supervisor/supervisor/issues/26
Can someone please walk me through what changes are necessary to accomplish this? I have the python 2.7.2 source extracted and ready to go.
Running centos 5.6, if... | [
"That's actually the limit of the underlying select(2) system call.\nFrom the man page:\nAn fd_set is a fixed size buffer. Executing FD_CLR() or FD_SET() with a value of fd \nthat is negative or is equal to or larger than FD_SETSIZE will result in \nundefined behavior. \n\nAnd the standard FD_SETSIZE is 1... | [
4
] | [] | [] | [
"centos",
"centos5",
"python"
] | stackoverflow_0007328165_centos_centos5_python.txt |
Q:
Referencing an external library in a Python appengine project, using Pydev/Eclipse
it's a couple of months I've started development in Python - having myself a C# and Java background.
I'm currently working on 2 different python/appengine applications, and as often happens in those cases, both application share com... | Referencing an external library in a Python appengine project, using Pydev/Eclipse | it's a couple of months I've started development in Python - having myself a C# and Java background.
I'm currently working on 2 different python/appengine applications, and as often happens in those cases, both application share common code - so I would like to refactor and move the common/generic code into a shared pl... | [
"The dev_appserver and the production environment don't have any concept of projects or libraries, so you need to structure your app so that all the necessary libraries are under the application's root. The easiest way to do this, usually, is to symlink them in as subdirectories, or worst-case, to copy them (or, us... | [
4
] | [] | [] | [
"google_app_engine",
"pydev",
"python"
] | stackoverflow_0007328959_google_app_engine_pydev_python.txt |
Q:
sorting floats numerically - not in ascii order - in python
This might sound like a silly question, but I've tried to find an answer that works without much success. I've got a list of lists:
for v in sorted(list):
print v
[885.1, 12824]
[885.1, 19843]
[885.11, 1319]
[885.12, 1155]
[885.13, 12844]
[885.14, 33... | sorting floats numerically - not in ascii order - in python | This might sound like a silly question, but I've tried to find an answer that works without much success. I've got a list of lists:
for v in sorted(list):
print v
[885.1, 12824]
[885.1, 19843]
[885.11, 1319]
[885.12, 1155]
[885.13, 12844]
[885.14, 33602]
[885.15, 11324]
[885.16, 44040]
[885.2, 119283]
[885.3, 842... | [
"convert the float to string first and split it by \".\":\nsorted(a, key=lambda x:map(int, str(float(x[0])).split(\".\")))\n\n",
"This is called a \"natsort\" (natural sort). A quick google on it gives me this: http://www.skynet.ie/~caolan/Packages/python-natsort.html (haven't tried it though). Maybe it helps you... | [
3,
1,
1,
1
] | [] | [] | [
"floating_point",
"python",
"sorting"
] | stackoverflow_0007329482_floating_point_python_sorting.txt |
Q:
How to design a program with many configuration options?
Lets say I have a program that has a large number of configuration options. The user can specify them in a config file. My program can parse this config file, but how should it internally store and pass around the options?
In my case, the software is used to... | How to design a program with many configuration options? | Lets say I have a program that has a large number of configuration options. The user can specify them in a config file. My program can parse this config file, but how should it internally store and pass around the options?
In my case, the software is used to perform a scientific simulation. There are about 200 options ... | [
"matplotlib is a large package with many configuration options. It use a rcParams module to manage all the default parameters. rcParams save all the default parameters in a dict.\nEvery functions will get the options from keyword argurments:\nfor example:\ndef f(x,y,opt_a=None, opt_b=None):\n if opt_a is None: o... | [
5,
4,
2,
0
] | [] | [] | [
"api",
"coding_style",
"python"
] | stackoverflow_0007329371_api_coding_style_python.txt |
Q:
Python script video system will not initialize
Here's a copy of the script. The error is on line 25.
import os, sys
import pygame
from pygame.locals import *
if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled'
class PyManMain:
"""The Main PyMan Class - Thi... | Python script video system will not initialize | Here's a copy of the script. The error is on line 25.
import os, sys
import pygame
from pygame.locals import *
if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled'
class PyManMain:
"""The Main PyMan Class - This class handles the main
initialization and cre... | [
"You have some indentation problem, try with this code : \nimport os, sys\nimport pygame\nfrom pygame.locals import *\n\nif not pygame.font: print 'Warning, fonts disabled'\nif not pygame.mixer: print 'Warning, sound disabled'\n\nclass PyManMain:\n \"\"\"The Main PyMan Class - This class handles the main \n i... | [
0
] | [] | [] | [
"initialization",
"python",
"video"
] | stackoverflow_0007329115_initialization_python_video.txt |
Q:
How can I classify data with the nearest-neighbor algorithm using Python?
I need to classify some data with (I hope) nearest-neighbour algorithm. I've googled this problem and found a lot of libraries (including PyML, mlPy and Orange), but I'm unsure of where to start here.
How should I go about implementing k-NN... | How can I classify data with the nearest-neighbor algorithm using Python? | I need to classify some data with (I hope) nearest-neighbour algorithm. I've googled this problem and found a lot of libraries (including PyML, mlPy and Orange), but I'm unsure of where to start here.
How should I go about implementing k-NN using Python?
| [
"Particularly given the technique (k-Nearest Neighbors) that you mentioned in your Q, i would strongly recommend scikits.learn. [Note: after this Answer was posted, the lead developer of this Project informed me of a new homepage for this Project.]\nA few features that i believe distinguish this library from the ot... | [
63
] | [] | [] | [
"machine_learning",
"python"
] | stackoverflow_0007326958_machine_learning_python.txt |
Q:
Basecamp file upload using Python
According to the Basecamp API documentation, files should be uploaded using HTTP POST with content type set to application/octet-stream and the request body containing the binary contents of the file (see http://developer.37signals.com/basecamp/). I'd like to stream the file rathe... | Basecamp file upload using Python | According to the Basecamp API documentation, files should be uploaded using HTTP POST with content type set to application/octet-stream and the request body containing the binary contents of the file (see http://developer.37signals.com/basecamp/). I'd like to stream the file rather than reading the whole thing into mem... | [
"I ended up using Twisted for this since I needed the upload to happen asynchronously anyway. This excellent blog post explains the general procedure: http://marianoiglesias.com.ar/python/file-uploading-with-multi-part-encoding-using-twisted/. I simply wrote my own producer instead to write raw binary data as the P... | [
0
] | [] | [] | [
"basecamp",
"python"
] | stackoverflow_0007318582_basecamp_python.txt |
Q:
forms_for_model() and forms_for_instance() are deprecated how do I use ModelForm subclass Instead?
models.py
class Person(models.Model):
userID = models.ForeignKey(User, unique=True)
name = models.CharField('name', max_length=200)
birthday = models.DateField('Birthday',blank=True,null=True)
gender... | forms_for_model() and forms_for_instance() are deprecated how do I use ModelForm subclass Instead? | models.py
class Person(models.Model):
userID = models.ForeignKey(User, unique=True)
name = models.CharField('name', max_length=200)
birthday = models.DateField('Birthday',blank=True,null=True)
gender = models.CharField(max_length=1, choices=gender_list)
email = models.EmailField('Email', max_length... | [
"Django in 24 hours is really outdated now.\nConsider switching to djangobook v2.0 - it's up to date and really great. And official docs on modelforms\nHere is small comparison of old and newforms.\n",
"The docs explain this fully.\n"
] | [
0,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0007329924_django_django_forms_python.txt |
Q:
Open source language/library/representation format that allows treating numeric formulas as objects?
I'm looking for a way to store a series of formulas/equations as text (so they are easily diff-able). Later formulas depend on the results of earlier ones.
I should be able to evaluate the formulas (similar to Live... | Open source language/library/representation format that allows treating numeric formulas as objects? | I'm looking for a way to store a series of formulas/equations as text (so they are easily diff-able). Later formulas depend on the results of earlier ones.
I should be able to evaluate the formulas (similar to Live Worksheets in MathCAD) to numeric results, but also be able to programmatically produce a string represen... | [
"you can use sympy:\nfrom sympy import *\n\na,b,c,d,e = symbols(\"a,b,c,d,e\")\nx = a**2 + b/(c-min(d,e))\ny = c+sqrt(x*e)\n\nvalues = {a:73,b:13,c:100,d:20,e:18}\n\nprint x\nprint y\n\nprint x.subs(values)\nprint y.subs(values)\n\nprint N(x.subs(values))\nprint N(y.subs(values))\n\nthe output is:\na**2 + b/(c - d)... | [
4
] | [] | [] | [
"code_generation",
"formulas",
"math",
"python"
] | stackoverflow_0007330284_code_generation_formulas_math_python.txt |
Q:
What is the pythonic structure of the code of a python-c++ interface with many functions?
I am writing a python interface to a c++ library and am wondering about the correct design of the library.
I have found out (the hard way) that all methods passed to python must be declared static. If I understand correctly, ... | What is the pythonic structure of the code of a python-c++ interface with many functions? | I am writing a python interface to a c++ library and am wondering about the correct design of the library.
I have found out (the hard way) that all methods passed to python must be declared static. If I understand correctly, this means that all functions basically must be defined in the same .cpp file. My interface has... | [
"\nI have found out (the hard way) that all methods passed to python must\n be declared static. If I understand correctly, this means that all\n functions basically must be defined in the same .cpp file. My\n interface has many functions, so this gets ugly very quickly.\n\nWhere did you find this out? It isn't ... | [
1,
0
] | [] | [] | [
"c++",
"interface",
"python"
] | stackoverflow_0007330279_c++_interface_python.txt |
Q:
python process wrapper
i have a java program which runs on a particular port in ubuntu. While running the program i need to take the output from the program and needs to save it in the log file. I use nohub to run them currently.when they fail I don't know why they fail.Then the process restart the nohub get overw... | python process wrapper | i have a java program which runs on a particular port in ubuntu. While running the program i need to take the output from the program and needs to save it in the log file. I use nohub to run them currently.when they fail I don't know why they fail.Then the process restart the nohub get overwritten . I want the process ... | [
"You should use the subprocess module of python.\nIf your logs are not too big, you can simply use : \n# for python >=2.7\nresult = subprocess.check_output([\"/path/to/process_to_lauch\", \"arg1\"])\n\n# for python < 2.7\nprocess = subprocess.Popen([\"/path/to/process_to_lauch\", \"arg1\"], stdout=subprocess.PIPE, ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007329547_python.txt |
Q:
loading a text file into a database using python
I am trying to load a text file into a database. My text file is about 1.6GB. I need to write a python script to load the text file with all the headers into a database
Any guidelines on how I go about doing this?
thanks
A:
Using python is certainly possible. If ... | loading a text file into a database using python | I am trying to load a text file into a database. My text file is about 1.6GB. I need to write a python script to load the text file with all the headers into a database
Any guidelines on how I go about doing this?
thanks
| [
"Using python is certainly possible. If you're reading into mysql, you might check out mysql-python. Reading the text file you can use file = open('filename','r'), and file.readline() to get each line and parse it.\nHowever... there is an added overhead of using python. If the text file is orderly (that is, one ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007330718_python.txt |
Q:
What's the best way to count unique visitors with Hadoop?
hey all, just getting started on hadoop and curious what the best way in mapreduce would be to count unique visitors if your logfiles looked like this...
DATE siteID action username
05-05-2010 siteA pageview jim
05-05-2010 siteB pageview tom
05... | What's the best way to count unique visitors with Hadoop? | hey all, just getting started on hadoop and curious what the best way in mapreduce would be to count unique visitors if your logfiles looked like this...
DATE siteID action username
05-05-2010 siteA pageview jim
05-05-2010 siteB pageview tom
05-05-2010 siteA pageview jim
05-05-2010 siteB pageview bob
0... | [
"You could do it as a 2-stage operation:\nFirst step, emit (username => siteID), and have the reducer just collapse multiple occurrences of siteID using a set - since you'd typically have far less sites than users, this should be fine. \nThen in the second step, you can emit (siteID => username) and do a simple cou... | [
3,
1,
1,
0
] | [] | [] | [
"hadoop",
"mapreduce",
"python"
] | stackoverflow_0002885394_hadoop_mapreduce_python.txt |
Q:
creating a list with 2 entries for each element of an iterator
I'm looking for a more elegant way to do something like this:
[data[i/2] if i%2==0 else log10(data[i/2]) for i in xrange(len(data)*2)]
So if data was [1,10,100], I want to make a list:
[1,0,10,1,100,2]
fyi: this is for output to a csv file
A:
>>> d... | creating a list with 2 entries for each element of an iterator | I'm looking for a more elegant way to do something like this:
[data[i/2] if i%2==0 else log10(data[i/2]) for i in xrange(len(data)*2)]
So if data was [1,10,100], I want to make a list:
[1,0,10,1,100,2]
fyi: this is for output to a csv file
| [
">>> data = [1, 10, 100]\n>>> [x for y in data for x in (y, math.log10(y))]\n[1, 0.0, 10, 1.0, 100, 2.0]\n\n",
"data = [1,10,100]\nitertools.chain(*((x,log10(x)) for x in data))\n\nthen make a list\n",
"sum(([x, math.log10(x)] for x in data), [])\n\n",
"Excuse me for answering my own question, but the answers... | [
1,
1,
1,
0
] | [] | [] | [
"iterator",
"list",
"python"
] | stackoverflow_0007303390_iterator_list_python.txt |
Q:
python database search with html
I have created a database with python and the results are kept in a text file.
I would like to create a simple html with a search button that looks through my database.
My database would be accessible only on my computer.
My database looks something like this:
Reference | Name | Di... | python database search with html | I have created a database with python and the results are kept in a text file.
I would like to create a simple html with a search button that looks through my database.
My database would be accessible only on my computer.
My database looks something like this:
Reference | Name | Dimension
XXX AAA 45
So, fo... | [
"There are multiple ways to solve this:\n\nInstall a webserver on your local machine and write a full-fledged Python web application\nWrite a simple webserver and application in Python using BaseHTTPServer\nWrite an HTML/JavaScript application that doesn't use Python at all and parses the file for itself. Note that... | [
3,
1
] | [] | [] | [
"database",
"html",
"python",
"search"
] | stackoverflow_0007330860_database_html_python_search.txt |
Q:
Dynamic field insertion when creating python dictionary
I would like to dynamicly add/ don't add a field when creating a python dictionary.
def my_func(input):
return {
'foo':'bar',
None if input == None else 'baz':input
}
This actually works but it returns {'foo': 'bar', None: None}... | Dynamic field insertion when creating python dictionary | I would like to dynamicly add/ don't add a field when creating a python dictionary.
def my_func(input):
return {
'foo':'bar',
None if input == None else 'baz':input
}
This actually works but it returns {'foo': 'bar', None: None}
I would like it to return {'foo': 'bar'}. Is there a way to ... | [
"You be wanting collections.defaultdict\ncollections.default works like a normal dict with one exception, you can set a default_factory, when you do a['test'] and the key is __missing__ then it will call default factory. In default factory you can make it do anything you want to give it a default value.\n",
"I to... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007331256_python.txt |
Q:
Nested for loops in Python compared to map function
I'm working in python and currently have the following code:
list = []
for a in range(100):
for b in range(100):
for c in range(100):
list.append(run(a,b,c))
where run(a,b,c) returns an integer (for example, it could multiply the three nu... | Nested for loops in Python compared to map function | I'm working in python and currently have the following code:
list = []
for a in range(100):
for b in range(100):
for c in range(100):
list.append(run(a,b,c))
where run(a,b,c) returns an integer (for example, it could multiply the three numbers together). Is there a faster way to either loop ove... | [
"Have a look at the itertools-module and particulary the product method\nexample usage:\nfor i in itertools.product(range(0,100), repeat=3):\n #do stuff with i\n list.append(run(i[0],i[1],i[2]))\n\nNote that the function call can be shortened to:\nlist.append(run(*i))\n\nin the example above. see docs.python.... | [
8,
2,
1,
0,
0
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0007330300_loops_python.txt |
Q:
Elegant way to avoid .put() on unchanged entities
A reoccurring pattern in my Python programming on GAE is getting some entity from the data store, then possibly changing that entity based on various conditions. In the end I need to .put() the entity back to the data store to ensure that any changes that might hav... | Elegant way to avoid .put() on unchanged entities | A reoccurring pattern in my Python programming on GAE is getting some entity from the data store, then possibly changing that entity based on various conditions. In the end I need to .put() the entity back to the data store to ensure that any changes that might have been made to it get saved.
However often there were ... | [
"Why not check if the result equals (==) the original and so decide whether to save it. This depends on a correctly implemented __eq__, but by default a field-by-field comparison based on the __dict__ should do it.\n def __eq__(self, other) : \n return self.__dict__ == other.__dict__\n\n(Be sure that the ot... | [
4,
4,
2,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007330974_google_app_engine_python.txt |
Q:
NoneType in QWebFrame Object childFrames() List
I am trying to access a child frame inside a web page using python qt webkit.
The childFrames() result an empty list with NoneType in front of the list, how do I go directly to the second entity since I can't use fr.childFrames()[1][1] : It will throw TypeError: 'QW... | NoneType in QWebFrame Object childFrames() List | I am trying to access a child frame inside a web page using python qt webkit.
The childFrames() result an empty list with NoneType in front of the list, how do I go directly to the second entity since I can't use fr.childFrames()[1][1] : It will throw TypeError: 'QWebFrame' object does not support indexing.
These are ... | [
"Your output seems to be two lists - the first is empty, the second contains QWebFrames.\nWhat does print fr[1][0].frameName() give you? It should return the frame name for <PyQt4.QtWebKit.QWebFrame object at 0x14a1200>.\n"
] | [
0
] | [] | [] | [
"pyqt4",
"python",
"webkit"
] | stackoverflow_0007307001_pyqt4_python_webkit.txt |
Q:
Check if a string is a possible abbrevation for a name
I'm trying to develop a python algorithm to check if a string could be an abbrevation for another word. For example
fck is a match for fc kopenhavn because it matches the first characters of the word. fhk would not match.
fco should not match fc kopenhavn bec... | Check if a string is a possible abbrevation for a name | I'm trying to develop a python algorithm to check if a string could be an abbrevation for another word. For example
fck is a match for fc kopenhavn because it matches the first characters of the word. fhk would not match.
fco should not match fc kopenhavn because no one irl would abbrevate FC Kopenhavn as FCO.
irl is ... | [
"This passes all the tests, including a few extra I created. It uses recursion. Here are the rules that I used:\n\nThe first letter of the abbreviation must match the first letter of\nthe text\nThe rest of the abbreviation (the abbrev minus the first letter) must be an abbreviation for:\n\nthe remaining words, or\n... | [
14,
4,
4,
0,
0
] | [] | [] | [
"abbreviation",
"python",
"slug",
"string_matching",
"text_analysis"
] | stackoverflow_0007331462_abbreviation_python_slug_string_matching_text_analysis.txt |
Q:
Regular Expression to remove " ' from a string in Python
I am fetching my result from a RSS feed using following code:
try:
desc = item.xpath('description')[0].text
if date is not None:
desc =date +"\n"+"\n"+desc
except:
desc = None
But sometimes the description contains few unicode html charecters in ... | Regular Expression to remove " ' from a string in Python | I am fetching my result from a RSS feed using following code:
try:
desc = item.xpath('description')[0].text
if date is not None:
desc =date +"\n"+"\n"+desc
except:
desc = None
But sometimes the description contains few unicode html charecters in feed as below:
The text from XML looks like " and with ' and ... | [
"I used something called \"Unescaping XML\", don't know if it's helpfull to you.\nsee : http://wiki.python.org/moin/EscapingXml\nfrom xml.sax.saxutils import unescape\n\nunescape(\"< & >\")\n\n'< & >'\n\n\n\n\nunescape(\"' "\", {\"'\": \"'\", \""\": '\"'})\n\n'\\' \"'\n\nedit\nJust saw... | [
1
] | [] | [] | [
"python",
"regex",
"string",
"substring"
] | stackoverflow_0007332502_python_regex_string_substring.txt |
Q:
What makes other languages faster than Java in terms of Rapid Development?
Many people say developing in Python, Ruby, PHP ...etc is much faster than Java.
Question is, why? In terms of coding, IDEs, available libraries... etc. Or is the speed in making the first prototype only?
I'm interested in answers from peo... | What makes other languages faster than Java in terms of Rapid Development? | Many people say developing in Python, Ruby, PHP ...etc is much faster than Java.
Question is, why? In terms of coding, IDEs, available libraries... etc. Or is the speed in making the first prototype only?
I'm interested in answers from people who worked long time on Java and long time on other languages.
Note: I have ... | [
"I think the main advantage of the rapid development languages is dynamic typing, where you do not have to put in any effort for static types, as e.g. in Java's \npublic List<Tree<N extends Iterator, E super Interface1 & Interface2>> \n = new ArrayList<Tree<N extends Iterator, E super Interface1 & Interface2>>();\... | [
3,
1,
0,
0
] | [] | [] | [
".net",
"java",
"php",
"python",
"ruby"
] | stackoverflow_0007332758_.net_java_php_python_ruby.txt |
Q:
Python and Beautiful Soup - Search for tag a, return following tag b's until tag A is found
I have 2 variables, one with 'last volume' and the other with 'last issue'.
The HTML I am dealing with contains a list of all volumes and issues, most recent first.
I need to return the href links for all volumes and issues... | Python and Beautiful Soup - Search for tag a, return following tag b's until tag A is found | I have 2 variables, one with 'last volume' and the other with 'last issue'.
The HTML I am dealing with contains a list of all volumes and issues, most recent first.
I need to return the href links for all volumes and issues that are newer than what I have on file.
So using the below example, say my last volume is 13 an... | [
"I think you are looking for findPrevious, which you could use this way:\nimport BeautifulSoup\nimport re\n\ncontent='''\n<ul class=\"bobby\">\n<li><strong>Volume 14</strong></li>\n<li class=\"\">\n<a href=\"/content/ben/cchts/2011/00000014/00000001\" title=\"Issue 1, September 2011\">Issue 1, September 2011</a> ... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0007321842_beautifulsoup_python.txt |
Q:
How to retain an added column in django queryset during serialization?
How do i retain my extra column i've added dynamically on a queryset during serialization to a json string?
this is my code:
tenant_unit = TenantUnit.objects.filter(unit__building__id=10)
# dynamically add a column unit_name
for tu in tenant_u... | How to retain an added column in django queryset during serialization? | How do i retain my extra column i've added dynamically on a queryset during serialization to a json string?
this is my code:
tenant_unit = TenantUnit.objects.filter(unit__building__id=10)
# dynamically add a column unit_name
for tu in tenant_unit:
tu.unit_name = tu.unit.unit_name
# at this point if i loop thru th... | [
"It's more that the django serialiser looks at the columns, not at the attributes.\nYou can look at other serialisation tools: wad of stuff serializer springs to mind.\nI wound up writing my own, that uses a django Form to serialise and deserialise.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007332258_django_python.txt |
Q:
Good examples/templates/best practices API documentation
Im creating the front end for a web service, and another company the back end. I need a good, simple and easily understandable way of making a document of API calls that we can collaborate on and edit together without confusing one another.
are there any goo... | Good examples/templates/best practices API documentation | Im creating the front end for a web service, and another company the back end. I need a good, simple and easily understandable way of making a document of API calls that we can collaborate on and edit together without confusing one another.
are there any good specs/examples etc of project API documentation so this does... | [
"My choice for documentation: Sphinx.\nOthers:\n\nepydoc\npylit\n\nBut Sphinx is quite awesome.\n",
"For small APIs I´ve began to use Google Docs. Its collaboration features are awesome and you can see a list of all changes made on this document.\n"
] | [
2,
0
] | [] | [] | [
"ajax",
"api",
"javascript",
"python",
"specifications"
] | stackoverflow_0007333852_ajax_api_javascript_python_specifications.txt |
Q:
Regex in Python
SO, I am trying create a simple regex that matches the following string:
<PRE>><A HREF="../cgi-bin/hgTracks?hgsid=160564920&db=hg18&position=chrX:33267175-33267784&hgPcrResult=pack">chrX:33267175-33267784</A> 610bp TGATGTTTGGCGAGGAACTC GCAGAGTTTGAAGAGCTCGG
TGATGTTTGGCGAGGAACTCtactattgttacacttaggaaa... | Regex in Python | SO, I am trying create a simple regex that matches the following string:
<PRE>><A HREF="../cgi-bin/hgTracks?hgsid=160564920&db=hg18&position=chrX:33267175-33267784&hgPcrResult=pack">chrX:33267175-33267784</A> 610bp TGATGTTTGGCGAGGAACTC GCAGAGTTTGAAGAGCTCGG
TGATGTTTGGCGAGGAACTCtactattgttacacttaggaaaataatcta
atccaaaggctt... | [
"Stop trying to parse HTML using regexes. You can't do it (robustly). There's a reason there's this famous SO answer. Use lxml instead.\n",
"If you're going to parse HTML, please use lxml, as Hank proposed.\nBut for this regex to work, you need to change the [] to (). A | inside square brackets is interpreted as ... | [
2,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0002960737_python_regex.txt |
Q:
Python delete file, invalid path
I want to delete a file located on my desktop:
os.remove('C:/Benutzer/Me/Desktop/sync.txt')
But I get
[Error 3] System cannot find the path
However the file does exist in the given location. I can copy the path and paste into explorer. This will open the file.
Where is the proble... | Python delete file, invalid path | I want to delete a file located on my desktop:
os.remove('C:/Benutzer/Me/Desktop/sync.txt')
But I get
[Error 3] System cannot find the path
However the file does exist in the given location. I can copy the path and paste into explorer. This will open the file.
Where is the problem?
| [
"I suppose you are on Vista or 7? Then be aware of the UI to do quite a lot of localization.\nProbably the path is really C:\\Users\\..., with the localization to Benutzer happening in the UI.\n",
"Try using backslashes instead of slashes, i.e. 'C:\\Benutzer\\Me\\Desktop\\sync.txt' (dos/windows style paths). To a... | [
4,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007332746_python.txt |
Q:
Problems with Python in Google App Engine - UTF-8 and ASCII
So for the past few days I've been trying to learn Python in App Engine. However, I've been encountering a number of problems with ASCII and UTF encoding. The freshest issue is as follows:
I have the following piece of code of a simplistic chatroom from t... | Problems with Python in Google App Engine - UTF-8 and ASCII | So for the past few days I've been trying to learn Python in App Engine. However, I've been encountering a number of problems with ASCII and UTF encoding. The freshest issue is as follows:
I have the following piece of code of a simplistic chatroom from the book 'Code in the Cloud'
from google.appengine.ext import weba... | [
"Your strings contain unicode characters, but they're not unicode strings, they're byte strings. You need to prefix each one with u (as in u\"foo\") in order to make them into unicode strings. If you ensure all your strings are Unicode strings, you should eliminate that error.\nYou should also specify the encoding ... | [
2,
1
] | [] | [] | [
"ascii",
"google_app_engine",
"python",
"utf_8"
] | stackoverflow_0007138797_ascii_google_app_engine_python_utf_8.txt |
Q:
running really long scripts - how to keep them running and start them again if they fail?
I need to run a bunch of long running processes on a CENTOS server.
If I leave the processes (python/php scripts) to run sometimes the processes will stop running because of trivial errors eg. string encoding issues or someti... | running really long scripts - how to keep them running and start them again if they fail? | I need to run a bunch of long running processes on a CENTOS server.
If I leave the processes (python/php scripts) to run sometimes the processes will stop running because of trivial errors eg. string encoding issues or sometimes because the process seems to get killed by the server.
I try to use nohup and fire the jobs... | [
"\nis there any way to keep these processes running in such a way that all the variables are saved and i can restart the script from where it stopped?\n\nYes. It's called creating a \"checkpoint\" or \"memento\".\n\ni know i can program this \n\nGood. Get started. Each problem is unique, so you have to create, s... | [
3
] | [] | [] | [
"centos",
"php",
"process",
"process_management",
"python"
] | stackoverflow_0007334587_centos_php_process_process_management_python.txt |
Q:
Trace Python imports
My Python library just changed it's main module name from foo.bar to foobar. For backward compat, foo.bar still exists, but importing it raises a few warnings. Now, it seems some example program still imports from the old module, but not directly.
I'd like to find the erroneous import statemen... | Trace Python imports | My Python library just changed it's main module name from foo.bar to foobar. For backward compat, foo.bar still exists, but importing it raises a few warnings. Now, it seems some example program still imports from the old module, but not directly.
I'd like to find the erroneous import statement. Is there any tool that ... | [
"Start the python interpreter with -v:\n$ python -v -m /usr/lib/python2.6/timeit.py\n# installing zipimport hook\nimport zipimport # builtin\n# installed zipimport hook\n# /usr/lib/python2.6/site.pyc matches /usr/lib/python2.6/site.py\nimport site # precompiled from /usr/lib/python2.6/site.pyc\n# /usr/lib/python2.6... | [
78,
9
] | [] | [] | [
"debugging",
"import",
"python",
"trace"
] | stackoverflow_0007332299_debugging_import_python_trace.txt |
Q:
Variations with repetition
Given a list of e.g. two elements l = [1,0] I need to create all possible 5-element variations with repetitions. I've tried itertools.combinations but give me what I wanted.
With given n = 2 and k = 5 I should get 2^5 = 32 elements and the result should look like this:
results = [11111,1... | Variations with repetition | Given a list of e.g. two elements l = [1,0] I need to create all possible 5-element variations with repetitions. I've tried itertools.combinations but give me what I wanted.
With given n = 2 and k = 5 I should get 2^5 = 32 elements and the result should look like this:
results = [11111,11110,11101,11100,11001,11011,110... | [
">>> import itertools\n>>> [\"\".join(item) for item in itertools.product(\"10\", repeat=5)]\n['11111', '11110', '11101', '11100', '11011', '11010', '11001', '11000', '10111', \n'10110', '10101', '10100', '10011', '10010', '10001', '10000', '01111', '01110', \n'01101', '01100', '01011', '01010', '01001', '01000', '... | [
11,
1
] | [] | [] | [
"combinatorics",
"python"
] | stackoverflow_0007334691_combinatorics_python.txt |
Q:
PIL - drawing text and saving
I have created this program:
from PIL import Image, ImageDraw
a = Image.open(r'C:\Users\damian\Desktop\a.png')
draw = ImageDraw.Draw(a)
draw.text((1, 1), 'Hello World!')
a.save(r'C:\Users\damian\Desktop\a.png', "PNG")
In theory it should load image, draw text on it and save it but w... | PIL - drawing text and saving | I have created this program:
from PIL import Image, ImageDraw
a = Image.open(r'C:\Users\damian\Desktop\a.png')
draw = ImageDraw.Draw(a)
draw.text((1, 1), 'Hello World!')
a.save(r'C:\Users\damian\Desktop\a.png', "PNG")
In theory it should load image, draw text on it and save it but when I run it nothing happens. Can s... | [
"I've solved this, it seems default colour is white and drawn text wasn't visible on my white image, fill=\"black\" was needed.\nThis question can now be closed.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007320225_python.txt |
Q:
Problem due to double quote while parsing csv.
I have csv file in the follwing format,
"1";"A";"A:"61 B & BA";"C"
Following is my code to read csv file,
with open(path, 'rb') as f:
reader = csv.reader(f, delimiter = ';', quotechar = '"')
for row in reader:
print row
The problem is, it breaks ... | Problem due to double quote while parsing csv. | I have csv file in the follwing format,
"1";"A";"A:"61 B & BA";"C"
Following is my code to read csv file,
with open(path, 'rb') as f:
reader = csv.reader(f, delimiter = ';', quotechar = '"')
for row in reader:
print row
The problem is, it breaks row in 5 fields,
['1', 'A', 'A:61 B &', ' BA', '... | [
"Your csv file is invalid. If a quote occurs inside a (quoted) string, it must be escaped by doubling it. \n\"1\";\"A\";\"A:\"\"61 B & BA\";\"C\"\n\nwould result in \n['1', 'A', 'A:\"61 B & BA', 'C']\n\nHow should the CSV module guess the difference between quotes that delimit an item and quotes within the ... | [
8,
3,
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0007334752_csv_python.txt |
Q:
Python: Get local IP-Address used to send IP data to a specific remote IP-Address
I am using a Python script to send UDP packets to a server which will register my script to receive notifications from the server. The protocol requires that I send my own IP-Address and port on which I want to receive these notifica... | Python: Get local IP-Address used to send IP data to a specific remote IP-Address | I am using a Python script to send UDP packets to a server which will register my script to receive notifications from the server. The protocol requires that I send my own IP-Address and port on which I want to receive these notifications, so this should be an address that is reachable from the server's network.
Soluti... | [
"I had to solve the same problem once, and spent considerable time trying to find a better way, without success. I also started with gethostname, but discovered, as you did, that it doesn't always return the right result, and can even throw an exception in cases where there is a problem with the hosts file.\nThe o... | [
12,
0
] | [] | [] | [
"ip",
"python"
] | stackoverflow_0007334349_ip_python.txt |
Q:
Asynchronous call within a GUI application using multiprocessing
I have a GUI application that needs to fetch and parse diverse resources from
network beside the GUI main loop.
I've searched for options using the python multiprocessing module since these
fetch actions not only contain blocking IO but also contai... | Asynchronous call within a GUI application using multiprocessing | I have a GUI application that needs to fetch and parse diverse resources from
network beside the GUI main loop.
I've searched for options using the python multiprocessing module since these
fetch actions not only contain blocking IO but also contain heavy parsing, so
multiprocessing may be better option here than py... | [
"You have no reason to use signals (low level api) for python multiprocessing and busy waiting in the main loop.\nYou have to run your (modified) event loop in a QThread, that can directly call qt code, or use QApplication.postEvent (or pyqtSignal) to execute it in the main thread\n# this should be in the delegate ... | [
2,
1
] | [] | [] | [
"asynchronous",
"multiprocessing",
"python",
"user_interface"
] | stackoverflow_0007324424_asynchronous_multiprocessing_python_user_interface.txt |
Q:
Automatically Generate Python Egg from Python PasteScript
So I'm using PasteScript's paster, and I'm trying to automate egg creation. My first step is to get a template of a Python egg. I noticed that PasteScript's paster has one built in, so I've been creating my template from the command line:
$paster create -t ... | Automatically Generate Python Egg from Python PasteScript | So I'm using PasteScript's paster, and I'm trying to automate egg creation. My first step is to get a template of a Python egg. I noticed that PasteScript's paster has one built in, so I've been creating my template from the command line:
$paster create -t basic_package
However, this asks me the questions as a series ... | [
"I recently discovered this myself. The \"paster create\" takes a --config command line argument. This can be a file which contains the variable to use.\nFor example:\nI will create a package called bob from config called bobsetup.cfg. The configuration file will contain:\n[pastescript]\ncreated = 2011-09-07T14:47:... | [
4
] | [] | [] | [
"paster",
"python"
] | stackoverflow_0006783958_paster_python.txt |
Q:
Get current opened browser window in selenium 2 (WebDriver)
I am using selenium 2 (WebDriver) now and I would like to get the control of current opened browser window instead of open a new one. That means I can't use driver.get("url") which is showed in all online documents. Could anyone help?
FYI, I am using Pyth... | Get current opened browser window in selenium 2 (WebDriver) | I am using selenium 2 (WebDriver) now and I would like to get the control of current opened browser window instead of open a new one. That means I can't use driver.get("url") which is showed in all online documents. Could anyone help?
FYI, I am using Python binding of selenium and firefox. Thanks.
| [
"Unfortunately you can't connect to an open browser at the moment. There is an open bug for WebDriver to support that\n"
] | [
0
] | [] | [] | [
"python",
"selenium",
"webdriver"
] | stackoverflow_0007335770_python_selenium_webdriver.txt |
Q:
How to read csv file with string but convert to different type and send to an array in python?
I have a csv file, contain datetime, number1, number2, number3 number4.
I use code to read, but how to change the types.
my code:
import csv
import datetime
myarray=([])
filename='Contract.csv'
f=csv.reader(open(filename... | How to read csv file with string but convert to different type and send to an array in python? | I have a csv file, contain datetime, number1, number2, number3 number4.
I use code to read, but how to change the types.
my code:
import csv
import datetime
myarray=([])
filename='Contract.csv'
f=csv.reader(open(filename,'rb'), delimiter=',')
for row in f:
myarray=array([row for row in f])
print myarray
I get the ... | [
"First, read this question.\nHaving said that. I use a function like this one (requries python-dateutil) to manage dates too:\nfrom dateutil.parser import parse as date_parser\ndef _cast_value(self, value):\n tests = (\n int,\n float,\n lambda value: date_parser(value)\n )\n for test i... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007335830_python.txt |
Q:
python ElementTree write function
I am using python ElementTree to read and modify some content of my html files. When I am done with changes and use ElementTree.write function,
1) it adds extra html: infront of all the tags. How should I avoid that?
2) It also adds & where I have special characters. How should i... | python ElementTree write function | I am using python ElementTree to read and modify some content of my html files. When I am done with changes and use ElementTree.write function,
1) it adds extra html: infront of all the tags. How should I avoid that?
2) It also adds & where I have special characters. How should i avoid that?
Thank you,
Divya.
| [
"You can't. ElementTree works by loading the XML, parsing it, and only storing an abstract representation. It writes that out to a string by walking the abstract representation, but it doesn't remember things like which characters were escaped as entities, or whether an element was stored as <foo/> or <foo></foo> (... | [
1
] | [] | [] | [
"elementtree",
"python"
] | stackoverflow_0007335678_elementtree_python.txt |
Q:
python json boolean to lowercase string
Is there a best-practice for outputting Booleans in Python? I'm generating some JSON (via Django templates), and by default all the Boolean values are output with leading character in uppercase, contrary to the JSON standard (ie, "True" as opposed to "true").
Currently, I fo... | python json boolean to lowercase string | Is there a best-practice for outputting Booleans in Python? I'm generating some JSON (via Django templates), and by default all the Boolean values are output with leading character in uppercase, contrary to the JSON standard (ie, "True" as opposed to "true").
Currently, I format each Boolean string using str.lower(), b... | [
"Well, then serialise to JSON using json, not some custom thingy.\nimport json\nprint json.dumps({'foo': True}) # => {\"foo\": true}\n\n",
"The way to do this is to not use templates. Use the json module, as so:\nimport json\n\ndef my_view(request):\n # ...\n json_d = dict(...)\n return json.dumps(json_d... | [
10,
7,
2,
1
] | [] | [] | [
"boolean",
"django",
"json",
"python",
"string"
] | stackoverflow_0007335829_boolean_django_json_python_string.txt |
Q:
Unable to iteratively call yahoo's term extractor api using python
I am trying to loop through some 50-odd files in a directory. Each file has some text for which i am trying to find the keywords using Yahoo Term Extractor. I am able to extract text from each file, but I am not able to iteratively call the API usi... | Unable to iteratively call yahoo's term extractor api using python | I am trying to loop through some 50-odd files in a directory. Each file has some text for which i am trying to find the keywords using Yahoo Term Extractor. I am able to extract text from each file, but I am not able to iteratively call the API using the text as input. Only the keywords for the first file is displayed.... | [
"Well I don't know anything about the Yahoo Term Extractor, but I'd presume that your call request.add_data(queryData) simply tacks on another data set with each iteration of your loop. And then the call to OPENER.open(request).read() would probably only process the results of the first data set. So either your req... | [
1
] | [] | [] | [
"loops",
"python",
"yahoo"
] | stackoverflow_0007291437_loops_python_yahoo.txt |
Q:
How to embed a terminal in a Tkinter application?
I want to embed a terminal in my main Tkinter window. I would like to have a sub window where a terminal (Bash based terminal) would run. I would like also to be able to let my program interact with the terminal, at least I would like to read the current working di... | How to embed a terminal in a Tkinter application? | I want to embed a terminal in my main Tkinter window. I would like to have a sub window where a terminal (Bash based terminal) would run. I would like also to be able to let my program interact with the terminal, at least I would like to read the current working directory and/or set it.
I don't know if it is really imp... | [
"I am happy to say that it is in fact possible to do it, and you can do it with just a few lines of code (I don't know if it is so easy with other toolkits):\nfrom Tkinter import *\nimport os\n\nroot = Tk()\ntermf = Frame(root, height=400, width=500)\n\ntermf.pack(fill=BOTH, expand=YES)\nwid = termf.winfo_id()\nos.... | [
36,
0
] | [] | [] | [
"python",
"terminal",
"tkinter"
] | stackoverflow_0007253448_python_terminal_tkinter.txt |
Q:
Python to parse non-standard XML file
My input file is actually multiple XML files appending to one file. (It's from Google Patents). It has below structure:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE us-patent-grant SYSTEM "us-patent-grant.dtd" [ ]>
<root_node>...</root_node>
<?xml version="1.0" encoding="U... | Python to parse non-standard XML file | My input file is actually multiple XML files appending to one file. (It's from Google Patents). It has below structure:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE us-patent-grant SYSTEM "us-patent-grant.dtd" [ ]>
<root_node>...</root_node>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE us-patent-grant SYSTEM "u... | [
"Here's my take on it, using a generator and lxml.etree. Extracted information purely for example.\nimport urllib2, os, zipfile\nfrom lxml import etree\n\ndef xmlSplitter(data,separator=lambda x: x.startswith('<?xml')):\n buff = []\n for line in data:\n if separator(line):\n if buff:\n yield ''.joi... | [
6,
2,
0
] | [] | [] | [
"python",
"xml_parsing"
] | stackoverflow_0007335560_python_xml_parsing.txt |
Q:
Separate Django sites with a common authetication/registration backend
I need split my current Django application into two sites.
Site A will contain the public facing site which would contain all the static pages and the registration system.
The other site — Site B — is the site for registered users. They can a... | Separate Django sites with a common authetication/registration backend | I need split my current Django application into two sites.
Site A will contain the public facing site which would contain all the static pages and the registration system.
The other site — Site B — is the site for registered users. They can also log-in to application site through Site B.
If I'm not mistaken, I can us... | [
"For this case, you would have 2 settings.py files called settings_A.py and settings_B.py which specify from settings import *\nA would have SITE=1 and B would have SITE=B. you can then set these files in your apache configs by setting the environment variable for each virtual host DJANGO_SETTINGS_MODULE=settings_A... | [
2,
2,
0
] | [] | [] | [
"django",
"django_sites",
"python"
] | stackoverflow_0007334498_django_django_sites_python.txt |
Q:
Path for running Python files
I have a directory which I would like to be the default for Python scripts so when a user is running python foo.py arg1 arg2 and foo.py is not in the current directory, it should execute python /defaultdir/foo.py arg1 arg2. Neither $PATH nor $PYTHONPATH is good for that: the first wou... | Path for running Python files | I have a directory which I would like to be the default for Python scripts so when a user is running python foo.py arg1 arg2 and foo.py is not in the current directory, it should execute python /defaultdir/foo.py arg1 arg2. Neither $PATH nor $PYTHONPATH is good for that: the first would only work with the command foo.p... | [
"Use python -m:\npython -mfoo arg1 arg2\n\n"
] | [
2
] | [] | [] | [
"path",
"python"
] | stackoverflow_0007337092_path_python.txt |
Q:
Is it best-practice to place __init__ in the beginning or end of a class?
Consider the following code:
class AClass():
def defaultMethod(self):
return 1
def __init__(self, methodToUse = defaultMethod):
print (methodToUse(self))
if __name__== "__main__":
AClass()
In this case one can... | Is it best-practice to place __init__ in the beginning or end of a class? | Consider the following code:
class AClass():
def defaultMethod(self):
return 1
def __init__(self, methodToUse = defaultMethod):
print (methodToUse(self))
if __name__== "__main__":
AClass()
In this case one cannot move the defaultMethod below the __init__ method, if I do, it causes "NameE... | [
"What do you mean, \"I need to define this method before the init or else Python does not know about it\" ?\n>>> class A(object):\n... def __init__(self):\n... self.foo()\n... def foo(self):\n... print '42'\n... \n>>> A()\n42\n\nI usually place __ init__() before other instance methods, but ... | [
4,
4,
1,
1
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0007335237_design_patterns_python.txt |
Q:
Using template tags in django to display a small bit of data for every view
I have an app I created that gets my latest github commits. Other than the model that was created to cache the info, I'm doing a lot of work inside of a simple_tag but I am unsure of the best way to avoid doing this. The reason I made th... | Using template tags in django to display a small bit of data for every view | I have an app I created that gets my latest github commits. Other than the model that was created to cache the info, I'm doing a lot of work inside of a simple_tag but I am unsure of the best way to avoid doing this. The reason I made this into a tag is that I want to display this data as part of the main layout of m... | [
"\nI'm doing a lot of work inside of a simple_tag but I am unsure of the best way to avoid doing this.\n\nTwo Words: View Functions.\n\nA view function should provide the last commit information. The view\n function should call a function that checks the last timestamp in a db\n and if it's over 1 hour old, it us... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007337304_django_python.txt |
Q:
Python raw_input() unable to paste in windows?
Is there a simple module that let's you paste input in python ?
Asking someone to type letter by letter is kinda harsh .
By default a .py file is opened with python.exe if is installed and this does not allow "rightclick+paste" in the console .So how can i make this ... | Python raw_input() unable to paste in windows? | Is there a simple module that let's you paste input in python ?
Asking someone to type letter by letter is kinda harsh .
By default a .py file is opened with python.exe if is installed and this does not allow "rightclick+paste" in the console .So how can i make this happen with python ? i think this would be more of a... | [
"You can make this by open cmd.exe and type here \"C:\\Python32\\python\".\nPath is depend on the version of python. Mine is 3.2.\n",
"If you're looking for a way to simply paste something into the windows command prompt, John Giotta is correct that a user can click on the little icon in the top left.\nI imagine,... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007335957_python.txt |
Q:
How to split an XML file the simple way in Python?
I have Python code for parsing an XML file as detailed here. I understand that XML files are notorious for hogging system resources when manipulated in memory. My solution works for smaller XML files (say 200KB and I have a 340MB file).
I started researching StAX... | How to split an XML file the simple way in Python? | I have Python code for parsing an XML file as detailed here. I understand that XML files are notorious for hogging system resources when manipulated in memory. My solution works for smaller XML files (say 200KB and I have a 340MB file).
I started researching StAX (pull parser) implementation but I am running on a tigh... | [
"You can parse your big XML file incrementally:\nfrom xml.etree.cElementTree import iterparse\n\n# get an iterable and turn it into an iterator\ncontext = iter(iterparse(\"path/to/big.xml\", events=(\"start\", \"end\")))\n\n# get the root element\nevent, root = next(context)\nassert event == \"start\"\n\nfor event,... | [
8,
1
] | [] | [] | [
"python",
"split",
"xml"
] | stackoverflow_0007336694_python_split_xml.txt |
Q:
Need an easy way to remove duplicates of nested tuples in python
I am currently working with a script that has lists that looks like this:
example = [ ((2,1),(0,1)), ((0,1),(2,1)), ((2,1),(0,1)) ]
Now turning this list to a set returns:
set( [ ((2,1),(0,1)), ((0,1),(2,1)) ] )
For my purposes I need to recognize ... | Need an easy way to remove duplicates of nested tuples in python | I am currently working with a script that has lists that looks like this:
example = [ ((2,1),(0,1)), ((0,1),(2,1)), ((2,1),(0,1)) ]
Now turning this list to a set returns:
set( [ ((2,1),(0,1)), ((0,1),(2,1)) ] )
For my purposes I need to recognize these tuples as being equal as well. I dont care about retaining the o... | [
"It sounds like you may be off using frozensets instead of tuples.\n>>> x = [((2, 1), (0, 1)), ((0, 1), (2, 1)), ((2, 1), (0, 1))]\n>>> x\n[((2, 1), (0, 1)), ((0, 1), (2, 1)), ((2, 1), (0, 1))]\n>>> set(frozenset(ts) for ts in x)\nset([frozenset([(0, 1), (2, 1)])])\n\n",
"In [10]: set(tuple(sorted(elt)) for elt i... | [
6,
5,
0
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0007337851_python_tuples.txt |
Q:
parsing a file into a list of lists
I have text file in this manner{ a 3 56 cd 8 }
{ 1 2 3 4 ab 546 }
I am currently using the following line to parse it into a list of list
for line in filename.readlines():
line = line.lstrip('{').rstrip('}\n').strip(' ').split(' ')
Is this the best way to do this?
Because I ... | parsing a file into a list of lists | I have text file in this manner{ a 3 56 cd 8 }
{ 1 2 3 4 ab 546 }
I am currently using the following line to parse it into a list of list
for line in filename.readlines():
line = line.lstrip('{').rstrip('}\n').strip(' ').split(' ')
Is this the best way to do this?
Because I have heard people say that the split func... | [
"Assuming there is no whitespace before the openening and after the closing bracket:\nli = [line[1:-1].split() for line in file]\n\nor if I can't assume that:\nli = [line.strip()[1:-1].split() for line in file]\n\n",
"It may be better to use a module like the csv module to parse your file. Here is a sample code.\... | [
2,
0,
0,
0
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0007336140_parsing_python.txt |
Q:
Get values from module
I made a program to perform some astronomical calculations. It takes only 6 parameters: latitude , longitude, year, hour, minute and day, because
This I believe there must exist an elegant way to get the job done.
The module looks like this:
parameter1 = some1
parameter2 = some2
var_1 = s... | Get values from module | I made a program to perform some astronomical calculations. It takes only 6 parameters: latitude , longitude, year, hour, minute and day, because
This I believe there must exist an elegant way to get the job done.
The module looks like this:
parameter1 = some1
parameter2 = some2
var_1 = some1 + some2 # or other calc... | [
"If I understand you correctly, you are doing something like this:\nimport your_module\nyour_module.parameter1 = 23\nyour_module.parameter2 = 46\nthe_result = your_module.f_var_2\n\nYou are setting variables in your module so that some other variables change so that you can get an answer.\nYou are definitely better... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007337904_python.txt |
Q:
auto_ptr with swig
I'm trying to wrap a C++ library which uses auto_ptr. I'm using swig
and want to generate python bindings. I'v seen the section of the swig docu on how to use swig with smart pointers here. But I can't get it to work.
Swig generates code that wants to initialize the auto_ptr using a const
refer... | auto_ptr with swig | I'm trying to wrap a C++ library which uses auto_ptr. I'm using swig
and want to generate python bindings. I'v seen the section of the swig docu on how to use swig with smart pointers here. But I can't get it to work.
Swig generates code that wants to initialize the auto_ptr using a const
reference, but auto_ptr defin... | [
"I do not believe you are going to be able to successfully wrap this code in SWIG. The problem is that auto_ptr changes ownership when it copies. This is why it requires the copy constructor to not have const. The way that SWIG manages ownership of objects internally means that the it is unlikely you'll get the des... | [
1,
1
] | [] | [] | [
"auto_ptr",
"c++",
"python",
"smart_pointers",
"swig"
] | stackoverflow_0003906019_auto_ptr_c++_python_smart_pointers_swig.txt |
Q:
SqlAlchemy: dynamic queries
How to make dynamic queries in SqlAlchemy ORM (if it is a correct name for them).
I used SqlAlchemy as abstraction for database, with queries in python code, but what if I need to generate these queries dynamically, not only set the parameters of query like "id"?
For example, I need to ... | SqlAlchemy: dynamic queries | How to make dynamic queries in SqlAlchemy ORM (if it is a correct name for them).
I used SqlAlchemy as abstraction for database, with queries in python code, but what if I need to generate these queries dynamically, not only set the parameters of query like "id"?
For example, I need to generate query from list (table n... | [
"Haven't tested, but it with the SQLAlchemy ORM, you can link tables together like:\nfrom sqlalchemy import create_engine, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, ForeignKey\nfrom sqlalchemy.orm import relationship\nfrom asgportal.database import Sess... | [
1,
1
] | [] | [] | [
"database",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0007336947_database_orm_python_sqlalchemy.txt |
Q:
removing random whitespace
All,
I have some indexed text that I would like to format in a more uniform manor. For example:
I live in Virginia and it is raining today
I would like that to print out as
I live in Virginia and it is raining today
I am writing my application in Python so if anyone knows h... | removing random whitespace | All,
I have some indexed text that I would like to format in a more uniform manor. For example:
I live in Virginia and it is raining today
I would like that to print out as
I live in Virginia and it is raining today
I am writing my application in Python so if anyone knows how to do this sort of string man... | [
"A very simple approach:\ns = \"I live in Virginia and it is raining today\"\nwords = s.split()\nprint ' '.join(words)\n\n",
"You could use a regular expression to accomplish this\nimport re\ns = 'I live in Virginia and it is raining today'\nprint re.sub(r'\\s+', ' ', s)\n\n",
"Regular exp... | [
9,
3,
0
] | [] | [] | [
"python",
"regex",
"whitespace"
] | stackoverflow_0007338198_python_regex_whitespace.txt |
Q:
how to generate numbers given their prime factors, but with unknown exponents?
Possible Duplicates:
nth ugly number
Find the Kth least number for expression (2^x)*(3^y)*(5^z)
I'm wondering how to solve this problem in a fast and elegant way:
We define "ugly" every number n which can be written in the form: 2^x ... | how to generate numbers given their prime factors, but with unknown exponents? |
Possible Duplicates:
nth ugly number
Find the Kth least number for expression (2^x)*(3^y)*(5^z)
I'm wondering how to solve this problem in a fast and elegant way:
We define "ugly" every number n which can be written in the form: 2^x * 3^y * 5^z;, where x,y and z are natural numbers. Find the 1500th ugly number.
E.... | [
"Here is a complete solution. O(n) complexity, it generates every number once and in order.\n# http://www.cs.utexas.edu/users/EWD/ewd07xx/EWD792.PDF\n\nn = 15\nbases = [2, 3, 5]\n\nnums = [1] * n\ncandidates_indexes = [0 for _ in bases]\ncandidates = [base for base in bases]\n\nfor i in range(1, n):\n nextn = mi... | [
12,
2,
1,
0
] | [] | [] | [
"factorization",
"hamming_numbers",
"math",
"primes",
"python"
] | stackoverflow_0007333657_factorization_hamming_numbers_math_primes_python.txt |
Q:
External Scrolling
I have a friend who doesn't have a mouse that can scroll who asked me to write him a program that could scroll in other windows. I'm most familiar with Python and was thinking of something that could bind certain keys to scroll. Are there any libraries or any way to scroll in an another window, ... | External Scrolling | I have a friend who doesn't have a mouse that can scroll who asked me to write him a program that could scroll in other windows. I'm most familiar with Python and was thinking of something that could bind certain keys to scroll. Are there any libraries or any way to scroll in an another window, like a webpage or text e... | [
"ControllerMate might do the job for you.\n"
] | [
1
] | [] | [] | [
"external",
"python",
"scroll"
] | stackoverflow_0007311483_external_python_scroll.txt |
Q:
Django models interface with dynamic connection
I have databases with identical schemas spread over several servers and I need to route a Django model to read from the databases on different servers. I know I can use routers to send reads to different databases in settings.DATABASES, but the addresses could change... | Django models interface with dynamic connection | I have databases with identical schemas spread over several servers and I need to route a Django model to read from the databases on different servers. I know I can use routers to send reads to different databases in settings.DATABASES, but the addresses could change at any time and keeping DATABASES up-to-date would b... | [] | [] | [
"\nShould I find some way to dynamically populate settings.DATABASES?\n\nIf you mean to alter settings.py at runtime, you should not.\n"
] | [
-1
] | [
"django",
"python"
] | stackoverflow_0006763272_django_python.txt |
Q:
Getting method arguments into a list of key and value pairs
I'm looking to get each of my method parameters into a dictionary or tuple pairs in a list as later the arguments get put through urllib.urlencode and formed into a POST statement.
I got as far as this from other SO questions
def func(a,b,c,d,e=None,f=Non... | Getting method arguments into a list of key and value pairs | I'm looking to get each of my method parameters into a dictionary or tuple pairs in a list as later the arguments get put through urllib.urlencode and formed into a POST statement.
I got as far as this from other SO questions
def func(a,b,c,d,e=None,f=None):
values= locals()
data= dict((k,v) for k,v in values.iteri... | [
"POST data is treated as unordered 99.99999% of the time (or maybe even more). Don't worry about the ordering.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007336866_python.txt |
Q:
How to create a generic network proxy using Python or C++?
I have an application which communicates over the local area network. However, I want to instead make it communicate over the internet. To do this I propose making an intermediate program which will read the network traffic generated from the application o... | How to create a generic network proxy using Python or C++? | I have an application which communicates over the local area network. However, I want to instead make it communicate over the internet. To do this I propose making an intermediate program which will read the network traffic generated from the application on one computer and send it to the application on another compute... | [
"The term you are missing in your original question is proxy. You specifically need a transparent forwarding proxy.\nHere is a link to some source code in Python that will get you started with writing a proxy.\nThat said, if you search around you should be able to find a transparent forwarding proxy that you don't ... | [
1,
1
] | [] | [] | [
"c++",
"network_programming",
"proxy",
"python"
] | stackoverflow_0007337966_c++_network_programming_proxy_python.txt |
Q:
Assigning the value returned by a function to a variable in Python
I began coding in Python recently and encountered a problem assigning the value returned by a function to a variable.
class Combolock:
def _init_(self,num1,num2,num3):
self.x = [num1,num2,num3]
def next(self, state):
print "... | Assigning the value returned by a function to a variable in Python | I began coding in Python recently and encountered a problem assigning the value returned by a function to a variable.
class Combolock:
def _init_(self,num1,num2,num3):
self.x = [num1,num2,num3]
def next(self, state):
print "Enter combination"
combo = raw_input(">")
if combo == se... | [
"You should use self.next(currentState), as you want the next method in the class scope.\nThe function next is global and next(obj) works only if obj is an iterator.\nYou might want to have a look at the yield statement in the python documentation.\n",
"As Andrea (+1) pointed it out you need to tell python you wa... | [
8,
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007338781_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.