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:
gaema twitter handle error
i use gaema for twitter user loggin http://code.google.com/p/gaema/
and my code is :
class TwitterAuth(WebappAuth, auth.TwitterMixin):
pass
class TwitterHandler(BaseHandler):
def get(self):
twitter_auth = TwitterAuth(self)
try:
if self.request.GET.get("oauth_token", None):
twitter_auth.get_authenticated_user(self._on_auth)
self.response.out.write('sss')
return
twitter_auth.authorize_redirect()
except RequestRedirect, e:
return self.redirect(e.url, permanent=True)
self.render_template('index.html', user=None)
def _on_auth(self, user):
"""This function is called immediatelly after an authentication attempt.
Use it to save the login information in a session or secure cookie.
:param user:
A dictionary with user data if the authentication was successful,
or ``None`` if the authentication failed.
"""
if user:
# Authentication was successful. Create a session or secure cookie
# to keep the user logged in.
#self.response.out.write('logged in as '+user['first_name']+' '+user['last_name'])
self.response.out.write(user)
return
else:
# Login failed. Show an error message or do nothing.
pass
# After cookie is persisted, redirect user to the original URL, using
# the home page as fallback.
self.redirect(self.request.GET.get('redirect', '/'))
and the error is :
Traceback (most recent call last):
File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
handler.get(*groups)
File "D:\zjm_code\gaema\demos\webapp\main.py", line 76, in get
twitter_auth.authorize_redirect()
File "D:\zjm_code\gaema\demos\webapp\gaema\auth.py", line 209, in authorize_redirect
http.fetch(self._oauth_request_token_url(), self.async_callback(
File "D:\zjm_code\gaema\demos\webapp\gaema\auth.py", line 239, in _oauth_request_token_url
consumer_token = self._oauth_consumer_token()
File "D:\zjm_code\gaema\demos\webapp\gaema\auth.py", line 441, in _oauth_consumer_token
self.require_setting("twitter_consumer_key", "Twitter OAuth")
TypeError: require_setting() takes at most 2 arguments (3 given)
thanks
A:
http://www.google.com/codesearch?q=%22def+require_setting%22+package:http://gaema.googlecode.com&hl=en
This is a bug. They should be using "self" as the first argument to require_settings.
I see it's already been reported @ http://code.google.com/p/gaema/issues/detail?id=6
| gaema twitter handle error | i use gaema for twitter user loggin http://code.google.com/p/gaema/
and my code is :
class TwitterAuth(WebappAuth, auth.TwitterMixin):
pass
class TwitterHandler(BaseHandler):
def get(self):
twitter_auth = TwitterAuth(self)
try:
if self.request.GET.get("oauth_token", None):
twitter_auth.get_authenticated_user(self._on_auth)
self.response.out.write('sss')
return
twitter_auth.authorize_redirect()
except RequestRedirect, e:
return self.redirect(e.url, permanent=True)
self.render_template('index.html', user=None)
def _on_auth(self, user):
"""This function is called immediatelly after an authentication attempt.
Use it to save the login information in a session or secure cookie.
:param user:
A dictionary with user data if the authentication was successful,
or ``None`` if the authentication failed.
"""
if user:
# Authentication was successful. Create a session or secure cookie
# to keep the user logged in.
#self.response.out.write('logged in as '+user['first_name']+' '+user['last_name'])
self.response.out.write(user)
return
else:
# Login failed. Show an error message or do nothing.
pass
# After cookie is persisted, redirect user to the original URL, using
# the home page as fallback.
self.redirect(self.request.GET.get('redirect', '/'))
and the error is :
Traceback (most recent call last):
File "D:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 511, in __call__
handler.get(*groups)
File "D:\zjm_code\gaema\demos\webapp\main.py", line 76, in get
twitter_auth.authorize_redirect()
File "D:\zjm_code\gaema\demos\webapp\gaema\auth.py", line 209, in authorize_redirect
http.fetch(self._oauth_request_token_url(), self.async_callback(
File "D:\zjm_code\gaema\demos\webapp\gaema\auth.py", line 239, in _oauth_request_token_url
consumer_token = self._oauth_consumer_token()
File "D:\zjm_code\gaema\demos\webapp\gaema\auth.py", line 441, in _oauth_consumer_token
self.require_setting("twitter_consumer_key", "Twitter OAuth")
TypeError: require_setting() takes at most 2 arguments (3 given)
thanks
| [
"http://www.google.com/codesearch?q=%22def+require_setting%22+package:http://gaema.googlecode.com&hl=en\nThis is a bug. They should be using \"self\" as the first argument to require_settings.\nI see it's already been reported @ http://code.google.com/p/gaema/issues/detail?id=6\n"
] | [
1
] | [] | [] | [
"gaema",
"google_app_engine",
"python",
"twitter"
] | stackoverflow_0002870893_gaema_google_app_engine_python_twitter.txt |
Q:
How can I implement this Python snippet in Java?
I have this Python code that I found online and would like to know how to translate it to Java. My question is not about the algorithm but how to handle the function's arguments.
Here is the code:
def ternarySearch(f, left, right, absolutePrecision):
#left and right are the current bounds; the maximum is between them
if (right - left) < absolutePrecision:
return (left + right)/2
leftThird = (2*left + right)/3
rightThird = (left + 2*right)/3
if f(leftThird) < f(rightThird):
return ternarySearch(f, leftThird, right, absolutePrecision)
return ternarySearch(f, left, rightThird, absolutePrecision)
I would like to know what the function definition would look like. For example, a function returning y=x^2+3 would look like:
public static int y(int x){
return x*x+3;
}
but
return ternarySearch(f, leftThird, right, absolutePrecision)
is not working for me and I'd like to know what to do.
Update:
so for example i have y=3*x+2 it will be like this?
interface MyFunctor {
int myFunction(int x);
}
class MyFunctorImpl implements MyFunctor {
int myFunction(int x) {
return 3*x+2
}
}
like this?
A:
In Java, there are no higher-order functions. That is, you can't pass a function as an argument to another function. What you can do is use the Command pattern; define an Interface supporting the method that you need, then pass an instance of that Interface implementing the method.
For example:
int ternarySearch(MyFunctor f, int left, int right, float absolutePrecision) {
#left and right are the current bounds; the maximum is between them
if (right - left) < absolutePrecision:
return (left + right)/2
leftThird = (2*left + right)/3
rightThird = (left + 2*right)/3
if (f.myFunction(leftThird) < f.myFunction(rightThird)) {
return ternarySearch(f, leftThird, right, absolutePrecision)
}
return ternarySearch(f, left, rightThird, absolutePrecision)
}
and
interface MyFunctor {
int myFunction(int arg);
}
and
class MyFunctorImpl implements MyFunctor {
int myFunction(int arg) {
// implementation
}
}
Then you could call ternarySearch with an instance of MyFunctorImpl as the first argument.
| How can I implement this Python snippet in Java? | I have this Python code that I found online and would like to know how to translate it to Java. My question is not about the algorithm but how to handle the function's arguments.
Here is the code:
def ternarySearch(f, left, right, absolutePrecision):
#left and right are the current bounds; the maximum is between them
if (right - left) < absolutePrecision:
return (left + right)/2
leftThird = (2*left + right)/3
rightThird = (left + 2*right)/3
if f(leftThird) < f(rightThird):
return ternarySearch(f, leftThird, right, absolutePrecision)
return ternarySearch(f, left, rightThird, absolutePrecision)
I would like to know what the function definition would look like. For example, a function returning y=x^2+3 would look like:
public static int y(int x){
return x*x+3;
}
but
return ternarySearch(f, leftThird, right, absolutePrecision)
is not working for me and I'd like to know what to do.
Update:
so for example i have y=3*x+2 it will be like this?
interface MyFunctor {
int myFunction(int x);
}
class MyFunctorImpl implements MyFunctor {
int myFunction(int x) {
return 3*x+2
}
}
like this?
| [
"In Java, there are no higher-order functions. That is, you can't pass a function as an argument to another function. What you can do is use the Command pattern; define an Interface supporting the method that you need, then pass an instance of that Interface implementing the method.\nFor example:\nint ternarySearch(MyFunctor f, int left, int right, float absolutePrecision) {\n #left and right are the current bounds; the maximum is between them\n if (right - left) < absolutePrecision:\n return (left + right)/2\n\n leftThird = (2*left + right)/3\n rightThird = (left + 2*right)/3\n\n if (f.myFunction(leftThird) < f.myFunction(rightThird)) {\n return ternarySearch(f, leftThird, right, absolutePrecision)\n }\n return ternarySearch(f, left, rightThird, absolutePrecision)\n}\n\nand\ninterface MyFunctor {\n int myFunction(int arg);\n}\n\nand\nclass MyFunctorImpl implements MyFunctor {\n int myFunction(int arg) {\n // implementation\n }\n}\n\nThen you could call ternarySearch with an instance of MyFunctorImpl as the first argument.\n"
] | [
8
] | [] | [] | [
"function",
"java",
"python"
] | stackoverflow_0002874487_function_java_python.txt |
Q:
How to write this snippet in Python?
I am learning Python (I have a C/C++ background).
I need to write something practical in Python though, whilst learning. I have the following pseudocode (my first attempt at writing a Python script, since reading about Python yesterday). Hopefully, the snippet details the logic of what I want to do. BTW I am using python 2.6 on Ubuntu Karmic.
Assume the script is invoked as: script_name.py directory_path
import csv, sys, os, glob
# Can I declare that the function accepts a dictionary as first arg?
def getItemValue(item, key, defval)
return !item.haskey(key) ? defval : item[key]
dirname = sys.argv[1]
# declare some default values here
weight, is_male, default_city_id = 100, true, 1
# fetch some data from a database table into a nested dictionary, indexed by a string
curr_dict = load_dict_from_db('foo')
#iterate through all the files matching *.csv in the specified folder
for infile in glob.glob( os.path.join(dirname, '*.csv') ):
#get the file name (without the '.csv' extension)
code = infile[0:-4]
# open file, and iterate through the rows of the current file (a CSV file)
f = open(infile, 'rt')
try:
reader = csv.reader(f)
for row in reader:
#lookup the id for the code in the dictionary
id = curr_dict[code]['id']
name = row['name']
address1 = row['address1']
address2 = row['address2']
city_id = getItemValue(row, 'city_id', default_city_id)
# insert row to database table
finally:
f.close()
I have the following questions:
Is the code written in a Pythonic enough way (is there a better way of implementing it)?
Given a table with a schema like shown below, how may I write a Python function that fetches data from the table and returns is in a dictionary indexed by string (name).
How can I insert the row data into the table (actually I would like to use a transaction if possible, and commit just before the file is closed)
Table schema:
create table demo (id int, name varchar(32), weight float, city_id int);
BTW, my backend database is postgreSQL
[Edit]
Wayne et al:
To clarify, what I want is a set of rows. Each row can be indexed by a key (so that means the rows container is a dictionary (right)?. Ok, now once we have retrieved a row by using the key, I also want to be able to access the 'columns' in the row - meaning that the row data itself is a dictionary. I dont know if Python supports multidimensional array syntax when dealing with dictionaries - but the following statement will help explain how I intend to conceptually use the data returned from the db. A statement like dataset['joe']['weight'] will first fetch the row data indexed by the key 'joe' (which is a dictionary) and then index that dictionary for the key 'weight'. I want to know how to build such a dictionary of dictionaries from the retrieved data in a Pythonic way like you did before.
A simplistic way would be to write something like:
import pyodbc
mydict = {}
cnxn = pyodbc.connect(params)
cursor = cnxn.cursor()
cursor.execute("select user_id, user_name from users"):
for row in cursor:
mydict[row.id] = row
Is this correct/can it be written in a more pythonic way?
A:
to get the value from the dictionary you need to use .get method of the dict:
>>> d = {1: 2}
>>> d.get(1, 3)
2
>>> d.get(5, 3)
3
This will remove the need for getItemValue function. I wont' comment on the existing syntax since it's clearly alien to Python. Correct syntax for the ternary in Python is:
true_val if true_false_check else false_val
>>> 'a' if False else 'b'
'b'
But as I'm saying below, you don't need it at all.
If you're using Python > 2.6, you should use with statement over the try-finally:
with open(infile) as f:
reader = csv.reader(f)
... etc
Seeing that you want to have row as dictionary, you should be using csv.DictReader and not a simple csv. reader. However, it is unnecessary in your case. Your sql query could just be constructed to access the fields of the row dict. In this case you wouldn't need to create separate items city_id, name, etc. To add default city_id to row if it doesn't exist, you could use .setdefault method:
>>> d
{1: 2}
>>> d.setdefault(1, 3)
2
>>> d
{1: 2}
>>> d.setdefault(3, 3)
3
>>> d
{1: 2, 3: 3}
and for id, simply row[id] = curr_dict[code]['id']
When slicing, you could skip 0:
>>> 'abc.txt'[:-4]
'abc'
Generally, Python's library provide a fetchone, fetchmany, fetchall methods on cursor, which return Row object, that might support dict-like access or return a simple tuple. It will depend on the particular module you're using.
A:
It looks mostly Pythonic enough for me.
The ternary operation should look like this though (I think this will return the result you expect):
return defval if not key in item else item[key]
Yeah, you can pass a dictionary (or any other value) in basically any order. The only difference is if you use the *args, **kwargs (named by convention. Technically you can use any name you want) which expect to be in that order and the last one or two arguments.
For inserting into a DB you can use the odbc module:
import odbc
conn = odbc.odbc('servernamehere')
cursor = conn.cursor()
cursor.execute("INSERT INTO mytable VALUES (42, 'Spam on Eggs', 'Spam on Wheat')")
conn.commit()
You can read up or find plenty of examples on the odbc module - I'm sure there are other modules as well, but that one should work fine for you.
For retrieval you would use
cursor.execute("SELECT * FROM demo")
#Reads one record - returns a tuple
print cursor.fetchone()
#Reads the rest of the records - a list of tuples
print cursor.fetchall()
to make one of those records into a dictionary:
record = cursor.fetchone()
# Removes the 2nd element (at index 1) from the record
mydict[record[1]] = record[:1] + record[2:]
Though that practically screams for a generator expression if you want the whole shebang at once
mydict = dict((record[1], record[:1] + record[2:] for record in cursor.fetchall())
which should give you all of the records packed up neatly in a dictionary, using the name as a key.
HTH
A:
a colon required after defs:
def getItemValue(item, key, defval):
...
boolean operators: In python !->not; &&->and and ||->or (see http://docs.python.org/release/2.5.2/lib/boolean.html for boolean operators). There's no ? : operator in python, there is a return (x) if (x) else (x) expression although I personally rarely use it in favour of plain if's.
booleans/None: True, False and None have capitals before them.
checking types of arguments: In python, you generally don't declare types of function parameters. You could go e.g. assert isinstance(item, dict), "dicts must be passed as the first parameter!" in the function although this kind of "strict checking" is often discouraged as it's not always necessary in python.
python keywords: default isn't a reserved python keyword and is acceptable as arguments and variables (just for the reference.)
style guidelines: PEP 8 (the python style guideline) states that module imports should generally only be one per line, though there are some exceptions (I have to admit I often don't follow the import sys and os on separate lines, though I usually follow it otherwise.)
file open modes: rt isn't valid in python 2.x - it will work, though the t will be ignored. See also http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files. It is valid in python 3 though, so I don't think it it'd hurt if you want to force text mode, raising exceptions on binary characters (use rb if you want to read non-ASCII characters.)
working with dictionaries: Python used to use dict.has_key(key) but you should use key in dict now (which has largely replaced it, see http://docs.python.org/library/stdtypes.html#mapping-types-dict.)
split file extensions: code = infile[0:-4] could be replaced with code = os.path.splitext(infile)[0] (which returns e.g. ('root', '.ext') with the dot in the extension (see http://docs.python.org/library/os.path.html#os.path.splitext).
EDIT: removed multiple variable declarations on a single line stuff and added some formatting. Also corrected the rt isn't a valid mode in python when in python 3 it is.
| How to write this snippet in Python? | I am learning Python (I have a C/C++ background).
I need to write something practical in Python though, whilst learning. I have the following pseudocode (my first attempt at writing a Python script, since reading about Python yesterday). Hopefully, the snippet details the logic of what I want to do. BTW I am using python 2.6 on Ubuntu Karmic.
Assume the script is invoked as: script_name.py directory_path
import csv, sys, os, glob
# Can I declare that the function accepts a dictionary as first arg?
def getItemValue(item, key, defval)
return !item.haskey(key) ? defval : item[key]
dirname = sys.argv[1]
# declare some default values here
weight, is_male, default_city_id = 100, true, 1
# fetch some data from a database table into a nested dictionary, indexed by a string
curr_dict = load_dict_from_db('foo')
#iterate through all the files matching *.csv in the specified folder
for infile in glob.glob( os.path.join(dirname, '*.csv') ):
#get the file name (without the '.csv' extension)
code = infile[0:-4]
# open file, and iterate through the rows of the current file (a CSV file)
f = open(infile, 'rt')
try:
reader = csv.reader(f)
for row in reader:
#lookup the id for the code in the dictionary
id = curr_dict[code]['id']
name = row['name']
address1 = row['address1']
address2 = row['address2']
city_id = getItemValue(row, 'city_id', default_city_id)
# insert row to database table
finally:
f.close()
I have the following questions:
Is the code written in a Pythonic enough way (is there a better way of implementing it)?
Given a table with a schema like shown below, how may I write a Python function that fetches data from the table and returns is in a dictionary indexed by string (name).
How can I insert the row data into the table (actually I would like to use a transaction if possible, and commit just before the file is closed)
Table schema:
create table demo (id int, name varchar(32), weight float, city_id int);
BTW, my backend database is postgreSQL
[Edit]
Wayne et al:
To clarify, what I want is a set of rows. Each row can be indexed by a key (so that means the rows container is a dictionary (right)?. Ok, now once we have retrieved a row by using the key, I also want to be able to access the 'columns' in the row - meaning that the row data itself is a dictionary. I dont know if Python supports multidimensional array syntax when dealing with dictionaries - but the following statement will help explain how I intend to conceptually use the data returned from the db. A statement like dataset['joe']['weight'] will first fetch the row data indexed by the key 'joe' (which is a dictionary) and then index that dictionary for the key 'weight'. I want to know how to build such a dictionary of dictionaries from the retrieved data in a Pythonic way like you did before.
A simplistic way would be to write something like:
import pyodbc
mydict = {}
cnxn = pyodbc.connect(params)
cursor = cnxn.cursor()
cursor.execute("select user_id, user_name from users"):
for row in cursor:
mydict[row.id] = row
Is this correct/can it be written in a more pythonic way?
| [
"to get the value from the dictionary you need to use .get method of the dict:\n>>> d = {1: 2}\n>>> d.get(1, 3)\n2\n>>> d.get(5, 3)\n3\n\nThis will remove the need for getItemValue function. I wont' comment on the existing syntax since it's clearly alien to Python. Correct syntax for the ternary in Python is:\ntrue_val if true_false_check else false_val\n>>> 'a' if False else 'b'\n'b'\n\nBut as I'm saying below, you don't need it at all.\nIf you're using Python > 2.6, you should use with statement over the try-finally:\nwith open(infile) as f:\n reader = csv.reader(f)\n ... etc\n\nSeeing that you want to have row as dictionary, you should be using csv.DictReader and not a simple csv. reader. However, it is unnecessary in your case. Your sql query could just be constructed to access the fields of the row dict. In this case you wouldn't need to create separate items city_id, name, etc. To add default city_id to row if it doesn't exist, you could use .setdefault method:\n>>> d\n{1: 2}\n>>> d.setdefault(1, 3)\n2\n>>> d\n{1: 2}\n>>> d.setdefault(3, 3)\n3\n>>> d\n{1: 2, 3: 3}\n\nand for id, simply row[id] = curr_dict[code]['id']\nWhen slicing, you could skip 0:\n>>> 'abc.txt'[:-4]\n'abc'\n\nGenerally, Python's library provide a fetchone, fetchmany, fetchall methods on cursor, which return Row object, that might support dict-like access or return a simple tuple. It will depend on the particular module you're using.\n",
"It looks mostly Pythonic enough for me.\nThe ternary operation should look like this though (I think this will return the result you expect):\nreturn defval if not key in item else item[key]\n\nYeah, you can pass a dictionary (or any other value) in basically any order. The only difference is if you use the *args, **kwargs (named by convention. Technically you can use any name you want) which expect to be in that order and the last one or two arguments.\nFor inserting into a DB you can use the odbc module:\nimport odbc\nconn = odbc.odbc('servernamehere')\ncursor = conn.cursor()\ncursor.execute(\"INSERT INTO mytable VALUES (42, 'Spam on Eggs', 'Spam on Wheat')\")\nconn.commit()\n\nYou can read up or find plenty of examples on the odbc module - I'm sure there are other modules as well, but that one should work fine for you.\nFor retrieval you would use\ncursor.execute(\"SELECT * FROM demo\")\n#Reads one record - returns a tuple\nprint cursor.fetchone()\n#Reads the rest of the records - a list of tuples\nprint cursor.fetchall()\n\nto make one of those records into a dictionary:\nrecord = cursor.fetchone()\n# Removes the 2nd element (at index 1) from the record\nmydict[record[1]] = record[:1] + record[2:]\n\nThough that practically screams for a generator expression if you want the whole shebang at once\nmydict = dict((record[1], record[:1] + record[2:] for record in cursor.fetchall())\n\nwhich should give you all of the records packed up neatly in a dictionary, using the name as a key.\nHTH\n",
"a colon required after defs:\ndef getItemValue(item, key, defval):\n ...\n\nboolean operators: In python !->not; &&->and and ||->or (see http://docs.python.org/release/2.5.2/lib/boolean.html for boolean operators). There's no ? : operator in python, there is a return (x) if (x) else (x) expression although I personally rarely use it in favour of plain if's.\nbooleans/None: True, False and None have capitals before them.\nchecking types of arguments: In python, you generally don't declare types of function parameters. You could go e.g. assert isinstance(item, dict), \"dicts must be passed as the first parameter!\" in the function although this kind of \"strict checking\" is often discouraged as it's not always necessary in python.\npython keywords: default isn't a reserved python keyword and is acceptable as arguments and variables (just for the reference.)\nstyle guidelines: PEP 8 (the python style guideline) states that module imports should generally only be one per line, though there are some exceptions (I have to admit I often don't follow the import sys and os on separate lines, though I usually follow it otherwise.)\nfile open modes: rt isn't valid in python 2.x - it will work, though the t will be ignored. See also http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files. It is valid in python 3 though, so I don't think it it'd hurt if you want to force text mode, raising exceptions on binary characters (use rb if you want to read non-ASCII characters.)\nworking with dictionaries: Python used to use dict.has_key(key) but you should use key in dict now (which has largely replaced it, see http://docs.python.org/library/stdtypes.html#mapping-types-dict.)\nsplit file extensions: code = infile[0:-4] could be replaced with code = os.path.splitext(infile)[0] (which returns e.g. ('root', '.ext') with the dot in the extension (see http://docs.python.org/library/os.path.html#os.path.splitext).\nEDIT: removed multiple variable declarations on a single line stuff and added some formatting. Also corrected the rt isn't a valid mode in python when in python 3 it is.\n"
] | [
5,
2,
2
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0002874270_postgresql_python.txt |
Q:
Is it possible to use template tags in ValidationError's strings?
I need to throw ValidationError containing anchor.
if not profile.activated():
raise ValidationError('Your profile is not activated. <a href="{% url resend_activation_key %}">Resend activation key</a>.')
What I need to modify to make this work?
A:
Why do you want to use a template tag here? Template tags are for use in templates. If you want to find a reverse URL, use the reverse function.
A:
First: just don't do this! Put HTML code where it belongs: into the template.
Second: you might be able to do this with
from django.template import Context, Template
t = Template(u"Your profile is not.... {% url blah %} ...")
raise ValidationError( t.render(Context())
But html tags will be escaped unless you mark them as safe in your template.
| Is it possible to use template tags in ValidationError's strings? | I need to throw ValidationError containing anchor.
if not profile.activated():
raise ValidationError('Your profile is not activated. <a href="{% url resend_activation_key %}">Resend activation key</a>.')
What I need to modify to make this work?
| [
"Why do you want to use a template tag here? Template tags are for use in templates. If you want to find a reverse URL, use the reverse function.\n",
"First: just don't do this! Put HTML code where it belongs: into the template.\nSecond: you might be able to do this with \nfrom django.template import Context, Template\nt = Template(u\"Your profile is not.... {% url blah %} ...\")\nraise ValidationError( t.render(Context())\n\nBut html tags will be escaped unless you mark them as safe in your template.\n"
] | [
3,
0
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python",
"validation"
] | stackoverflow_0002874324_django_django_forms_django_templates_python_validation.txt |
Q:
PyQt Drag and Drop - Nothing happens
I'm trying to get drop a file onto a Window (I've tried the same thing with a QListWidget without success there too)
test.py:
#! /usr/bin/python
# Test
from PyQt4 import QtCore, QtGui
import sys
from qt_test import Ui_MainWindow
class MyForm(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.__class__.dragEnterEvent = self.DragEnterEvent
self.__class__.dragMoveEvent = self.DragEnterEvent
self.__class__.dropEvent = self.drop
self.setAcceptDrops(True)
print "Initialized"
self.show()
def DragEnterEvent(self, event):
event.accept()
def drop(self, event):
link=event.mimeData().text()
print link
def main():
app = QtGui.QApplication(sys.argv)
mw = MyForm()
sys.exit(app.exec_())
if __name__== "__main__":
main()
And here's qt_test.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created: Thu May 20 12:23:19 2010
# by: PyQt4 UI code generator 4.6
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
MainWindow.setAcceptDrops(True)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
I've read this email and I've followed everything said there. I still don't get any output except "Initialized" and the drag doesn't seem to get accepted (both for files from a file manager and plain text dragged from a text editor). Do you know what I'm doing wrong?
Thanks!
A:
Yes. Well... sort of.
Dragging plain text from an editor worked fine for me, as for files...
When you drop a file onto your app, it's type is "text/uri-list". For this you will want to use the event.mimeData().urls() method to get a list of PyQt4.QtCore.QUrl objects.
You will need to handle different mime data formats differently. You can use the following methods of the mimeData() to find out what attributes it has:
hasColor()
hasFormat()
hasHtml()
hasImage()
hasText()
hasUrls()
| PyQt Drag and Drop - Nothing happens | I'm trying to get drop a file onto a Window (I've tried the same thing with a QListWidget without success there too)
test.py:
#! /usr/bin/python
# Test
from PyQt4 import QtCore, QtGui
import sys
from qt_test import Ui_MainWindow
class MyForm(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setupUi(self)
self.__class__.dragEnterEvent = self.DragEnterEvent
self.__class__.dragMoveEvent = self.DragEnterEvent
self.__class__.dropEvent = self.drop
self.setAcceptDrops(True)
print "Initialized"
self.show()
def DragEnterEvent(self, event):
event.accept()
def drop(self, event):
link=event.mimeData().text()
print link
def main():
app = QtGui.QApplication(sys.argv)
mw = MyForm()
sys.exit(app.exec_())
if __name__== "__main__":
main()
And here's qt_test.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created: Thu May 20 12:23:19 2010
# by: PyQt4 UI code generator 4.6
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
MainWindow.setAcceptDrops(True)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
I've read this email and I've followed everything said there. I still don't get any output except "Initialized" and the drag doesn't seem to get accepted (both for files from a file manager and plain text dragged from a text editor). Do you know what I'm doing wrong?
Thanks!
| [
"Yes. Well... sort of.\nDragging plain text from an editor worked fine for me, as for files...\nWhen you drop a file onto your app, it's type is \"text/uri-list\". For this you will want to use the event.mimeData().urls() method to get a list of PyQt4.QtCore.QUrl objects.\nYou will need to handle different mime data formats differently. You can use the following methods of the mimeData() to find out what attributes it has:\nhasColor()\nhasFormat()\nhasHtml()\nhasImage()\nhasText()\nhasUrls()\n\n"
] | [
3
] | [] | [] | [
"drag_and_drop",
"pyqt",
"python"
] | stackoverflow_0002871663_drag_and_drop_pyqt_python.txt |
Q:
Catching single-character input on stdin while outputting to stdout in Python
I'm writing a simple dual timer in Python. (I'm running Linux, and this should only need to run on my system.) The idea is that the script has two separate timers, one of which is running at any one time. The user should be able to press a button to either switch which timer is running, or pause both. Currently, the test script looks like this:
now = datetime.datetime.now()
until = now + datetime.timedelta(minutes=2)
print now,
while now < until:
print "\r",
now = datetime.datetime.now()
print now,
sys.stdout.flush()
# check stdin here
time.sleep(0.1)
(I've skipped the imports in the code here.)
This outputs the current value of the timer to stdout every 0.1 seconds, overwriting the previous value when it does so.
I'm having problems, however, working out how to implement the # check stdin here line. Ideally, the user should just be able to press, say, "p", and the timer would be paused. At the moment, I have this in place of time.sleep(0.1):
if select.select([sys.stdin],[],[],0.1)[0]:
print sys.stdin.readline().strip()
...which works, except that it requires the user to press enter for a command to be recognised. Is there a way of doing this without needing enter to be pressed?
A:
See this SO question and this article.
Both of those describe either platform-specific options or using something like pygame.
However, if you need a cross-platform solution that doesn't require any external dependencies (e.g. pygame), I think you should also be able to do it through the threading module in the standard library. (Give me a bit and I'll try to cobble something using the threading module together...)
| Catching single-character input on stdin while outputting to stdout in Python | I'm writing a simple dual timer in Python. (I'm running Linux, and this should only need to run on my system.) The idea is that the script has two separate timers, one of which is running at any one time. The user should be able to press a button to either switch which timer is running, or pause both. Currently, the test script looks like this:
now = datetime.datetime.now()
until = now + datetime.timedelta(minutes=2)
print now,
while now < until:
print "\r",
now = datetime.datetime.now()
print now,
sys.stdout.flush()
# check stdin here
time.sleep(0.1)
(I've skipped the imports in the code here.)
This outputs the current value of the timer to stdout every 0.1 seconds, overwriting the previous value when it does so.
I'm having problems, however, working out how to implement the # check stdin here line. Ideally, the user should just be able to press, say, "p", and the timer would be paused. At the moment, I have this in place of time.sleep(0.1):
if select.select([sys.stdin],[],[],0.1)[0]:
print sys.stdin.readline().strip()
...which works, except that it requires the user to press enter for a command to be recognised. Is there a way of doing this without needing enter to be pressed?
| [
"See this SO question and this article.\nBoth of those describe either platform-specific options or using something like pygame.\nHowever, if you need a cross-platform solution that doesn't require any external dependencies (e.g. pygame), I think you should also be able to do it through the threading module in the standard library. (Give me a bit and I'll try to cobble something using the threading module together...)\n"
] | [
2
] | [] | [] | [
"python"
] | stackoverflow_0002874469_python.txt |
Q:
Why subtract a value from itself (x - x) in Python?
In NumPy functions, there are often initial lines that do checking of variable types, forcing them to be certain types, etc. Can someone explain the point of these lines in scipy.signal.square? What does subtracting a value from itself do?
t,w = asarray(t), asarray(duty)
w = asarray(w + (t-t))
t = asarray(t + (w-w))
source
A:
I believe that this will make the final w and t have the same type. For example, if you start with float and int, you will end up with both being float arrays which is better for subsequent operations.
| Why subtract a value from itself (x - x) in Python? | In NumPy functions, there are often initial lines that do checking of variable types, forcing them to be certain types, etc. Can someone explain the point of these lines in scipy.signal.square? What does subtracting a value from itself do?
t,w = asarray(t), asarray(duty)
w = asarray(w + (t-t))
t = asarray(t + (w-w))
source
| [
"I believe that this will make the final w and t have the same type. For example, if you start with float and int, you will end up with both being float arrays which is better for subsequent operations.\n"
] | [
14
] | [] | [] | [
"numpy",
"python",
"type_conversion"
] | stackoverflow_0002875024_numpy_python_type_conversion.txt |
Q:
Wizard Page load event in wxWizard
I'm using a wxWizard control. I know about the on EVT_WIZARD_PAGE_CHANGED and the EVT_WIZARD_PAGE_CHANGING events but could anyone please tell me how to trigger an event when a particular wizard page loads?
Thanks.
A:
from the Wxwizard.py example included with wx distribution
def OnWizPageChanged(self, evt):
if evt.GetDirection():
dir = "forward"
else:
dir = "backward"
page = evt.GetPage()
self.log.write("OnWizPageChanged: %s, %s\n" % (dir, page.__class__))
This could be modified
def OnWizPageChanged(self, evt):
page = evt.GetPage()
if (isinstance(page,MyParticularClass):
# do something, generate event, whatever
pass
| Wizard Page load event in wxWizard | I'm using a wxWizard control. I know about the on EVT_WIZARD_PAGE_CHANGED and the EVT_WIZARD_PAGE_CHANGING events but could anyone please tell me how to trigger an event when a particular wizard page loads?
Thanks.
| [
"from the Wxwizard.py example included with wx distribution\n def OnWizPageChanged(self, evt):\n if evt.GetDirection():\n dir = \"forward\"\n else:\n dir = \"backward\"\n\n page = evt.GetPage()\n self.log.write(\"OnWizPageChanged: %s, %s\\n\" % (dir, page.__class__))\n\nThis could be modified\n def OnWizPageChanged(self, evt):\n page = evt.GetPage()\n if (isinstance(page,MyParticularClass):\n # do something, generate event, whatever\n pass\n\n"
] | [
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002873171_python_wxpython.txt |
Q:
How can I put all twill commands together into one piece of code in a .py file?
I have just started exploring TWILL.
Twill is an amazing scripting language for Web browsing and it does all I want!!!
So far I've been using twill from a Python shell (IDLE (Python GUI) to be precise) and I do things there in the way of executing commands one by one (I mean, I type one command, run it, then type the next command):
(source: narod.ru)
(source: narod.ru)
(source: narod.ru)
(source: narod.ru)
(source: narod.ru)
(source: narod.ru)
(source: narod.ru)
But I don't know how to put all these commands together in one .py file, so that they would all be executed one by one automatically.
It seems that there is such possibility in twill. This example from the twill documentation page (you can see it HERE) shows us one piece of code consisting of several commands:
(source: narod.ru)
So, my question is: How can I put all commands together in twill?
Update 1:
(this update is my response to S.Mark)
Hello, S.Mark!!! I am sorry for the late response.
First of all, some info about the location of my twill and python related folders:
The path where Python2.5 is installed on my computer: C:\Python25
The path to my twill-0.9 on my computer now: E:\tmp\twill-0.9
Let’s say I want the following commands to be carried out automatically:
go http://www.yahoo.com
save_html result.html
This code should look into yahoo page and then save its HTML code into result.html file.
So, trying to follow Your instructions, I firstly created “test.txt” file containing this code consisting of only 2 lines and saved that file as “test.twill” in the twill-0.9 folder, which means that the full path to that file now was E:\tmp\twill-0.9\test.twill
Then I tried to pass the file name as parameter to twill-sh command in many different ways, but it never worked (I must’ve been doing something wrong):
(source: narod.ru)
(source: narod.ru)
But you know what, I decided to experiment a bit and created a test.py file that also contained only those two commands. This file I also placed in the twill-0.9 folder (E:\tmp\twill-0.9\test.py) and then I decided to try running it from twill shell using twill’s runfile command, and, surprisingly, it worked! :
(source: narod.ru)
After running it, I looked up my C:\Python25 folder and found the newly-created result.html file there!
Well, what I've done here is simply running a file from the twill shell using a twill command. While at the moment it is exactly what I need, other supporters (as you can see below) suggest I should do all things from python shell, not from twill shell, and that is something that I still don’t know how to do.
My next step will be to try running a similar code on “Google App Engine”, but there, as far as I know, only Python is recognized, not twill, which means that if I only know how to do things in twill, but not in python, I won’t be able to have “Google App Engine” execute my commands.
Update 2:
(Friday 23, April, 2010, 3:48:15 a.m.(GMT+0.00))
(This update is my second response to S.Mark)
It seems that running it from command prompt isn't successful either:
(source: narod.ru)
A:
Put your twill commands into a file, for example test.twill
setlocal query "twill Python"
go http://google.com/
fv 1 q $query
submit btnI # use the "I'm feeling lucky" button
show
And then just pass filename as parameter to twill-sh command, like
python twill-sh test.twill
And you might want to check .twill sample codes in tests folder of twill source
test-back.twill
test-basic.twill
test-dns.twill
test-equiv-refresh.twill
test-find.twill
test-form.twill
test-formfill.twill
test-global-form.twill
test-go-exit.twill
....
A:
Here it is in action (changed a wee bit):
>>> import twill.commands
>>> import BeautifulSoup
>>>
>>> class browser:
... def __init__(self, url="http://www.google.com",log = None):
... self.a=twill.commands
... self.a.config("readonly_controls_writeable", 1)
... self.b = self.a.get_browser()
... self.b.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14")
... self.log = log
... self.b.clear_cookies()
... self.url=url
... def googleQuery(self, query="python code"):
... self.b.go(self.url)
... #self.b.showforms()
... f = self.b.get_form("f")
... #print "form is %s" % f
... f["q"] = query
... self.b.clicked(f, "btnG")
... self.b.submit()
... pageContent = self.b.get_html()
... soup=BeautifulSoup.BeautifulSoup(pageContent)
... ths = soup.findAll(attrs={"class" : "l"})
... for a in ths:
... print a
...
>>> t=browser()
>>> t.googleQuery("twill queries")
==> at http://www.google.ie/
Note: submit is using submit button: name="btnG", value="Google Search"
<a href="http://pyparsing.wikispaces.com/WhosUsingPyparsing" class="l" onmousedown="return clk(this.href,'','','res','1','','0CBMQFjAA')">pyparsing - WhosUsingPyparsing</a>
<a href="http://www.mail-archive.com/twill@lists.idyll.org/msg00048.html" class="l" onmousedown="return clk(this.href,'','','res','2','','0CBcQFjAB')">Re: [<em>twill</em>] <em>query</em>: docs, and web site.</a>
<a href="http://www.mail-archive.com/twill@lists.idyll.org/msg00050.html" class="l" onmousedown="return clk(this.href,'','','res','3','','0CBkQFjAC')">Re: [<em>twill</em>] <em>query</em>: docs, and web site.</a>
<a href="http://www.genealogytoday.com/surname/finder.mv?Surname=Twill" class="l" onmousedown="return clk(this.href,'','','res','4','','0CB4QFjAD')"><em>Twill</em> Genealogy and Family Tree Resources - Surname Finder</a>
<a href="http://a706cheap-apparel.hobby-site.com/ladies-cotton-faded-twill-le-chameau-breeks-42" class="l" onmousedown="return clk(this.href,'','','res','5','','0CCEQFjAE')">Ladies Cotton Faded <em>Twill</em> Le Chameau Breeks 42</a>
<a href="http://twill.idyll.org/examples.html" class="l" onmousedown="return clk(this.href,'','','res','6','','0CCMQFjAF')"><em>twill</em> Examples</a>
<a href="http://panjiva.com/Sri-Lankan-Manufacturers-Of/twill+capri" class="l" onmousedown="return clk(this.href,'','','res','7','','0CCcQFjAG')">Sri-Lankan <em>Twill</em> Capri Manufacturers | Sri-Lankan Suppliers of <b>...</b></a>
<a href="http://c586cheap-apparel.dyndns.ws/twill-beige-blazer" class="l" onmousedown="return clk(this.href,'','','res','8','','0CCoQFjAH')"><em>Twill</em> beige blazer</a>
<a href="http://stackoverflow.com/questions/2267537/how-do-you-use-relative-paths-for-twill-tests" class="l" onmousedown="return clk(this.href,'','','res','9','','0CCwQFjAI')">How do you use Relative Paths for <em>Twill</em> tests? - Stack Overflow</a>
<a href="http://mytextilenotes.blogspot.com/2010/01/introduction-to-twill-weave.html" class="l" onmousedown="return clk(this.href,'','','res','10','','0CC8QFjAJ')">My Textile Notes: Introduction to <em>Twill</em> Weave</a>
>>>
I use ubuntu so I use the following to install BeautifulSoup and twill:
sudo apt-get install BeautifulSoup*
sudo apt-get install python-twill*
How this helps
A
A:
I think that instead of using the twill shell, you should instead directly call the functions using the twill python api http://twill.idyll.org/python-api.html.
A:
import string, re, sys, os
import twill.commands
class browser:
def __init__(self, url="www.google.com", query="python code", log = None):
self.a=twill.commands
self.a.config("readonly_controls_writeable", 1)
self.b = self.a.get_browser()
self.b.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14")
self.log = log
self.b.clear_cookies()
self.url=url
self.b.go(self.url)
f = self.b.get_form("1")
# self.log.debug("form is %s" % f)
f["q"] = query
self.b.submit()
self.log.debug( "Links\n%s" % self.b.showlinks())
self.log.debug( "Forms\n%s" % self.b.showforms())
pageContent = self.b.get_html()
self.log.debug("html is <<%s>>" % pageContent)
| How can I put all twill commands together into one piece of code in a .py file? | I have just started exploring TWILL.
Twill is an amazing scripting language for Web browsing and it does all I want!!!
So far I've been using twill from a Python shell (IDLE (Python GUI) to be precise) and I do things there in the way of executing commands one by one (I mean, I type one command, run it, then type the next command):
(source: narod.ru)
(source: narod.ru)
(source: narod.ru)
(source: narod.ru)
(source: narod.ru)
(source: narod.ru)
(source: narod.ru)
But I don't know how to put all these commands together in one .py file, so that they would all be executed one by one automatically.
It seems that there is such possibility in twill. This example from the twill documentation page (you can see it HERE) shows us one piece of code consisting of several commands:
(source: narod.ru)
So, my question is: How can I put all commands together in twill?
Update 1:
(this update is my response to S.Mark)
Hello, S.Mark!!! I am sorry for the late response.
First of all, some info about the location of my twill and python related folders:
The path where Python2.5 is installed on my computer: C:\Python25
The path to my twill-0.9 on my computer now: E:\tmp\twill-0.9
Let’s say I want the following commands to be carried out automatically:
go http://www.yahoo.com
save_html result.html
This code should look into yahoo page and then save its HTML code into result.html file.
So, trying to follow Your instructions, I firstly created “test.txt” file containing this code consisting of only 2 lines and saved that file as “test.twill” in the twill-0.9 folder, which means that the full path to that file now was E:\tmp\twill-0.9\test.twill
Then I tried to pass the file name as parameter to twill-sh command in many different ways, but it never worked (I must’ve been doing something wrong):
(source: narod.ru)
(source: narod.ru)
But you know what, I decided to experiment a bit and created a test.py file that also contained only those two commands. This file I also placed in the twill-0.9 folder (E:\tmp\twill-0.9\test.py) and then I decided to try running it from twill shell using twill’s runfile command, and, surprisingly, it worked! :
(source: narod.ru)
After running it, I looked up my C:\Python25 folder and found the newly-created result.html file there!
Well, what I've done here is simply running a file from the twill shell using a twill command. While at the moment it is exactly what I need, other supporters (as you can see below) suggest I should do all things from python shell, not from twill shell, and that is something that I still don’t know how to do.
My next step will be to try running a similar code on “Google App Engine”, but there, as far as I know, only Python is recognized, not twill, which means that if I only know how to do things in twill, but not in python, I won’t be able to have “Google App Engine” execute my commands.
Update 2:
(Friday 23, April, 2010, 3:48:15 a.m.(GMT+0.00))
(This update is my second response to S.Mark)
It seems that running it from command prompt isn't successful either:
(source: narod.ru)
| [
"Put your twill commands into a file, for example test.twill\nsetlocal query \"twill Python\"\n\ngo http://google.com/\n\nfv 1 q $query\nsubmit btnI # use the \"I'm feeling lucky\" button\n\nshow\n\nAnd then just pass filename as parameter to twill-sh command, like\npython twill-sh test.twill\n\nAnd you might want to check .twill sample codes in tests folder of twill source\ntest-back.twill\ntest-basic.twill\ntest-dns.twill\ntest-equiv-refresh.twill\ntest-find.twill\ntest-form.twill\ntest-formfill.twill\ntest-global-form.twill\ntest-go-exit.twill\n....\n\n",
"Here it is in action (changed a wee bit):\n>>> import twill.commands\n>>> import BeautifulSoup\n>>> \n>>> class browser:\n... def __init__(self, url=\"http://www.google.com\",log = None):\n... self.a=twill.commands\n... self.a.config(\"readonly_controls_writeable\", 1)\n... self.b = self.a.get_browser()\n... self.b.set_agent_string(\"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14\")\n... self.log = log\n... self.b.clear_cookies()\n... self.url=url\n... def googleQuery(self, query=\"python code\"):\n... self.b.go(self.url)\n... #self.b.showforms()\n... f = self.b.get_form(\"f\")\n... #print \"form is %s\" % f\n... f[\"q\"] = query\n... self.b.clicked(f, \"btnG\")\n... self.b.submit()\n... pageContent = self.b.get_html()\n... soup=BeautifulSoup.BeautifulSoup(pageContent)\n... ths = soup.findAll(attrs={\"class\" : \"l\"})\n... for a in ths:\n... print a\n... \n>>> t=browser()\n>>> t.googleQuery(\"twill queries\")\n==> at http://www.google.ie/\nNote: submit is using submit button: name=\"btnG\", value=\"Google Search\"\n\n<a href=\"http://pyparsing.wikispaces.com/WhosUsingPyparsing\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','1','','0CBMQFjAA')\">pyparsing - WhosUsingPyparsing</a>\n<a href=\"http://www.mail-archive.com/twill@lists.idyll.org/msg00048.html\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','2','','0CBcQFjAB')\">Re: [<em>twill</em>] <em>query</em>: docs, and web site.</a>\n<a href=\"http://www.mail-archive.com/twill@lists.idyll.org/msg00050.html\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','3','','0CBkQFjAC')\">Re: [<em>twill</em>] <em>query</em>: docs, and web site.</a>\n<a href=\"http://www.genealogytoday.com/surname/finder.mv?Surname=Twill\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','4','','0CB4QFjAD')\"><em>Twill</em> Genealogy and Family Tree Resources - Surname Finder</a>\n<a href=\"http://a706cheap-apparel.hobby-site.com/ladies-cotton-faded-twill-le-chameau-breeks-42\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','5','','0CCEQFjAE')\">Ladies Cotton Faded <em>Twill</em> Le Chameau Breeks 42</a>\n<a href=\"http://twill.idyll.org/examples.html\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','6','','0CCMQFjAF')\"><em>twill</em> Examples</a>\n<a href=\"http://panjiva.com/Sri-Lankan-Manufacturers-Of/twill+capri\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','7','','0CCcQFjAG')\">Sri-Lankan <em>Twill</em> Capri Manufacturers | Sri-Lankan Suppliers of <b>...</b></a>\n<a href=\"http://c586cheap-apparel.dyndns.ws/twill-beige-blazer\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','8','','0CCoQFjAH')\"><em>Twill</em> beige blazer</a>\n<a href=\"http://stackoverflow.com/questions/2267537/how-do-you-use-relative-paths-for-twill-tests\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','9','','0CCwQFjAI')\">How do you use Relative Paths for <em>Twill</em> tests? - Stack Overflow</a>\n<a href=\"http://mytextilenotes.blogspot.com/2010/01/introduction-to-twill-weave.html\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','10','','0CC8QFjAJ')\">My Textile Notes: Introduction to <em>Twill</em> Weave</a>\n>>> \n\nI use ubuntu so I use the following to install BeautifulSoup and twill:\nsudo apt-get install BeautifulSoup* \nsudo apt-get install python-twill*\n\nHow this helps\nA \n",
"I think that instead of using the twill shell, you should instead directly call the functions using the twill python api http://twill.idyll.org/python-api.html.\n",
"import string, re, sys, os\nimport twill.commands\n\nclass browser:\n def __init__(self, url=\"www.google.com\", query=\"python code\", log = None):\n self.a=twill.commands\n self.a.config(\"readonly_controls_writeable\", 1)\n self.b = self.a.get_browser()\n self.b.set_agent_string(\"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14\")\n self.log = log\n self.b.clear_cookies()\n self.url=url\n self.b.go(self.url)\n f = self.b.get_form(\"1\")\n# self.log.debug(\"form is %s\" % f)\n f[\"q\"] = query\n self.b.submit()\n self.log.debug( \"Links\\n%s\" % self.b.showlinks())\n self.log.debug( \"Forms\\n%s\" % self.b.showforms())\n pageContent = self.b.get_html()\n self.log.debug(\"html is <<%s>>\" % pageContent)\n\n"
] | [
3,
3,
2,
1
] | [] | [] | [
"command",
"python",
"twill"
] | stackoverflow_0002688408_command_python_twill.txt |
Q:
How to combine twill and python into one code that could be run on "Google App Engine"?
I have installed twill on my computer (having previously installed Python 2.5) and have been using it recently.
Python is installed on disk C on my computer: C:\Python25
And the twill folder (“twill-0.9”) is located here: E:\tmp\twill-0.9
Here is a code that I’ve been using in twill:
go “some website’s sign-in page URL”
formvalue 2 userid “my login”
formvalue 2 pass “my password”
submit
go “URL of some other page from that website”
save_html result.txt
This code helps me to log in to one website, in which I have an account, record the HTML code of some other page of that website (that I can access only after logging in), and store it in a file named “result.txt” (of course, before using this code I firstly need to replace “my login” with my real login, “my password” with my real password, “some website’s sign-in page URL” and “URL of some other page from that website” with real URLs of that website, and number 2 with the number of the form on that website that is used as a sign-in form on that website’s log-in page)
This code I store in “test.twill” file that is located in my “twill-0.9” folder: E:\tmp\twill-0.9\test.twill
I run this file from my command prompt: python twill-sh test.twill
Now, I also have installed “Google App Engine SDK” from “Google App Engine” and have also been using it for awhile.
For example, I’ve been using this code:
import hashlib
m = hashlib.md5()
m.update("Nobody inspects")
m.update(" the spammish repetition ")
print m.hexdigest()
This code helps me transform the phrase “Nobody inspects the spammish repetition” into md5 digest.
Now, how can I put these two pieces of code together into one python script that I could run on “Google App Engine”?
Let’s say, I want my code to log in to a website from “Google App Engine”, go to another page on that website, record its HTML code (that’s what my twill code does) and than transform this HTML code into its md5 digest (that’s what my second code does). So, how can I combine those two codes into one python code?
I guess, it should be done somehow by importing twill, but how can it be done? Can a python code - the one that is being run by “Google App Engine” - import twill from somewhere on the internet? Or, perhaps, twill is already installed on “Google App Engine”?
Update 1:
(this update is my response to Wooble’s answer)
Here is the list of all folders (in my “twill-0.9” folder) that contain __init__.py files. (some folders on this list are located inside of other folders, which are also mentioned in this list) :
E:\twill-0.9\build\lib\twill\extensions\match_parse
E:\twill-0.9\build\lib\twill\extensions
E:\twill-0.9\build\lib\twill\other_packages\_mechanize_dist
E:\twill-0.9\build\lib\twill\other_packages
E:\twill-0.9\build\lib\twill
E:\twill-0.9\twill\extensions\match_parse
E:\twill-0.9\twill\extensions
E:\twill-0.9\twill\other_packages\_mechanize_dist
E:\twill-0.9\twill\other_packages
E:\twill-0.9\twill
A:
here is an example of using twill to run a google search if this helps. It shows using twill and beautifulsoup together to parse web pages:
>>> import twill.commands
>>> import BeautifulSoup
>>>
>>> class browser:
... def __init__(self, url="http://www.google.com",log = None):
... self.a=twill.commands
... self.a.config("readonly_controls_writeable", 1)
... self.b = self.a.get_browser()
... self.b.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14")
... self.log = log
... self.b.clear_cookies()
... self.url=url
... def googleQuery(self, query="python code"):
... self.b.go(self.url)
... #self.b.showforms()
... f = self.b.get_form("f")
... #print "form is %s" % f
... f["q"] = query
... self.b.clicked(f, "btnG")
... self.b.submit()
... pageContent = self.b.get_html()
... soup=BeautifulSoup.BeautifulSoup(pageContent)
... ths = soup.findAll(attrs={"class" : "l"})
... for a in ths:
... print a
...
>>> t=browser()
>>> t.googleQuery("twill queries")
==> at http://www.google.ie/
Note: submit is using submit button: name="btnG", value="Google Search"
<a href="http://pyparsing.wikispaces.com/WhosUsingPyparsing" class="l" onmousedown="return clk(this.href,'','','res','1','','0CBMQFjAA')">pyparsing - WhosUsingPyparsing</a>
<a href="http://www.mail-archive.com/twill@lists.idyll.org/msg00048.html" class="l" onmousedown="return clk(this.href,'','','res','2','','0CBcQFjAB')">Re: [<em>twill</em>] <em>query</em>: docs, and web site.</a>
<a href="http://www.mail-archive.com/twill@lists.idyll.org/msg00050.html" class="l" onmousedown="return clk(this.href,'','','res','3','','0CBkQFjAC')">Re: [<em>twill</em>] <em>query</em>: docs, and web site.</a>
<a href="http://www.genealogytoday.com/surname/finder.mv?Surname=Twill" class="l" onmousedown="return clk(this.href,'','','res','4','','0CB4QFjAD')"><em>Twill</em> Genealogy and Family Tree Resources - Surname Finder</a>
<a href="http://a706cheap-apparel.hobby-site.com/ladies-cotton-faded-twill-le-chameau-breeks-42" class="l" onmousedown="return clk(this.href,'','','res','5','','0CCEQFjAE')">Ladies Cotton Faded <em>Twill</em> Le Chameau Breeks 42</a>
<a href="http://twill.idyll.org/examples.html" class="l" onmousedown="return clk(this.href,'','','res','6','','0CCMQFjAF')"><em>twill</em> Examples</a>
<a href="http://panjiva.com/Sri-Lankan-Manufacturers-Of/twill+capri" class="l" onmousedown="return clk(this.href,'','','res','7','','0CCcQFjAG')">Sri-Lankan <em>Twill</em> Capri Manufacturers | Sri-Lankan Suppliers of <b>...</b></a>
<a href="http://c586cheap-apparel.dyndns.ws/twill-beige-blazer" class="l" onmousedown="return clk(this.href,'','','res','8','','0CCoQFjAH')"><em>Twill</em> beige blazer</a>
<a href="http://stackoverflow.com/questions/2267537/how-do-you-use-relative-paths-for-twill-tests" class="l" onmousedown="return clk(this.href,'','','res','9','','0CCwQFjAI')">How do you use Relative Paths for <em>Twill</em> tests? - Stack Overflow</a>
<a href="http://mytextilenotes.blogspot.com/2010/01/introduction-to-twill-weave.html" class="l" onmousedown="return clk(this.href,'','','res','10','','0CC8QFjAJ')">My Textile Notes: Introduction to <em>Twill</em> Weave</a>
>>>
A:
No idea what twill does (well, googled), but AppEngine offers fetch() function which can be used to fetch web pages. It also supports POST method e.g. for logins.
(I doubt twill works in AppEngine, because AppEngine has limited python libraries available for security reasons. Just a guess, though.)
A:
I believe you're looking for a way to import the twill module into App-Engine. You'll have to figure out either where the twill python files are or how to get a source package of them to package it with your website, but it looks like importing 3rd party modules can be done with a few exceptions, see below.
Try ZipImport following the directions from Google's site here and here.
from Google's third Party Library page:
App Engine uses a custom version of the zipimport feature instead of the standard implementation. It generally works the usual way: add the Zip archive to sys.path, then import as usual. With these exceptions:
zipimport can only import modules stored in the archive as .py source files. It cannot import modules stored as .pyc or .pyo files.
zipimport is implemented in pure Python, and does not use native code for decompression (C code).
A:
To use third-party libraries in App Engine projects, you simply have to include them with your application when you deploy. Copy the twill folder (the one containing __init__.py) into your application's folder and deploy it.
Looking at the twill Google Code project, it appears that twill includes its dependencies (pyparsing, mechanize, etc.) in the package, so you may not need to include anything else.
| How to combine twill and python into one code that could be run on "Google App Engine"? | I have installed twill on my computer (having previously installed Python 2.5) and have been using it recently.
Python is installed on disk C on my computer: C:\Python25
And the twill folder (“twill-0.9”) is located here: E:\tmp\twill-0.9
Here is a code that I’ve been using in twill:
go “some website’s sign-in page URL”
formvalue 2 userid “my login”
formvalue 2 pass “my password”
submit
go “URL of some other page from that website”
save_html result.txt
This code helps me to log in to one website, in which I have an account, record the HTML code of some other page of that website (that I can access only after logging in), and store it in a file named “result.txt” (of course, before using this code I firstly need to replace “my login” with my real login, “my password” with my real password, “some website’s sign-in page URL” and “URL of some other page from that website” with real URLs of that website, and number 2 with the number of the form on that website that is used as a sign-in form on that website’s log-in page)
This code I store in “test.twill” file that is located in my “twill-0.9” folder: E:\tmp\twill-0.9\test.twill
I run this file from my command prompt: python twill-sh test.twill
Now, I also have installed “Google App Engine SDK” from “Google App Engine” and have also been using it for awhile.
For example, I’ve been using this code:
import hashlib
m = hashlib.md5()
m.update("Nobody inspects")
m.update(" the spammish repetition ")
print m.hexdigest()
This code helps me transform the phrase “Nobody inspects the spammish repetition” into md5 digest.
Now, how can I put these two pieces of code together into one python script that I could run on “Google App Engine”?
Let’s say, I want my code to log in to a website from “Google App Engine”, go to another page on that website, record its HTML code (that’s what my twill code does) and than transform this HTML code into its md5 digest (that’s what my second code does). So, how can I combine those two codes into one python code?
I guess, it should be done somehow by importing twill, but how can it be done? Can a python code - the one that is being run by “Google App Engine” - import twill from somewhere on the internet? Or, perhaps, twill is already installed on “Google App Engine”?
Update 1:
(this update is my response to Wooble’s answer)
Here is the list of all folders (in my “twill-0.9” folder) that contain __init__.py files. (some folders on this list are located inside of other folders, which are also mentioned in this list) :
E:\twill-0.9\build\lib\twill\extensions\match_parse
E:\twill-0.9\build\lib\twill\extensions
E:\twill-0.9\build\lib\twill\other_packages\_mechanize_dist
E:\twill-0.9\build\lib\twill\other_packages
E:\twill-0.9\build\lib\twill
E:\twill-0.9\twill\extensions\match_parse
E:\twill-0.9\twill\extensions
E:\twill-0.9\twill\other_packages\_mechanize_dist
E:\twill-0.9\twill\other_packages
E:\twill-0.9\twill
| [
"here is an example of using twill to run a google search if this helps. It shows using twill and beautifulsoup together to parse web pages:\n>>> import twill.commands\n>>> import BeautifulSoup\n>>> \n>>> class browser:\n... def __init__(self, url=\"http://www.google.com\",log = None):\n... self.a=twill.commands\n... self.a.config(\"readonly_controls_writeable\", 1)\n... self.b = self.a.get_browser()\n... self.b.set_agent_string(\"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14\")\n... self.log = log\n... self.b.clear_cookies()\n... self.url=url\n... def googleQuery(self, query=\"python code\"):\n... self.b.go(self.url)\n... #self.b.showforms()\n... f = self.b.get_form(\"f\")\n... #print \"form is %s\" % f\n... f[\"q\"] = query\n... self.b.clicked(f, \"btnG\")\n... self.b.submit()\n... pageContent = self.b.get_html()\n... soup=BeautifulSoup.BeautifulSoup(pageContent)\n... ths = soup.findAll(attrs={\"class\" : \"l\"})\n... for a in ths:\n... print a\n... \n>>> t=browser()\n>>> t.googleQuery(\"twill queries\")\n==> at http://www.google.ie/\nNote: submit is using submit button: name=\"btnG\", value=\"Google Search\"\n\n<a href=\"http://pyparsing.wikispaces.com/WhosUsingPyparsing\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','1','','0CBMQFjAA')\">pyparsing - WhosUsingPyparsing</a>\n<a href=\"http://www.mail-archive.com/twill@lists.idyll.org/msg00048.html\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','2','','0CBcQFjAB')\">Re: [<em>twill</em>] <em>query</em>: docs, and web site.</a>\n<a href=\"http://www.mail-archive.com/twill@lists.idyll.org/msg00050.html\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','3','','0CBkQFjAC')\">Re: [<em>twill</em>] <em>query</em>: docs, and web site.</a>\n<a href=\"http://www.genealogytoday.com/surname/finder.mv?Surname=Twill\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','4','','0CB4QFjAD')\"><em>Twill</em> Genealogy and Family Tree Resources - Surname Finder</a>\n<a href=\"http://a706cheap-apparel.hobby-site.com/ladies-cotton-faded-twill-le-chameau-breeks-42\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','5','','0CCEQFjAE')\">Ladies Cotton Faded <em>Twill</em> Le Chameau Breeks 42</a>\n<a href=\"http://twill.idyll.org/examples.html\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','6','','0CCMQFjAF')\"><em>twill</em> Examples</a>\n<a href=\"http://panjiva.com/Sri-Lankan-Manufacturers-Of/twill+capri\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','7','','0CCcQFjAG')\">Sri-Lankan <em>Twill</em> Capri Manufacturers | Sri-Lankan Suppliers of <b>...</b></a>\n<a href=\"http://c586cheap-apparel.dyndns.ws/twill-beige-blazer\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','8','','0CCoQFjAH')\"><em>Twill</em> beige blazer</a>\n<a href=\"http://stackoverflow.com/questions/2267537/how-do-you-use-relative-paths-for-twill-tests\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','9','','0CCwQFjAI')\">How do you use Relative Paths for <em>Twill</em> tests? - Stack Overflow</a>\n<a href=\"http://mytextilenotes.blogspot.com/2010/01/introduction-to-twill-weave.html\" class=\"l\" onmousedown=\"return clk(this.href,'','','res','10','','0CC8QFjAJ')\">My Textile Notes: Introduction to <em>Twill</em> Weave</a>\n>>> \n\n",
"No idea what twill does (well, googled), but AppEngine offers fetch() function which can be used to fetch web pages. It also supports POST method e.g. for logins.\n(I doubt twill works in AppEngine, because AppEngine has limited python libraries available for security reasons. Just a guess, though.)\n",
"I believe you're looking for a way to import the twill module into App-Engine. You'll have to figure out either where the twill python files are or how to get a source package of them to package it with your website, but it looks like importing 3rd party modules can be done with a few exceptions, see below.\nTry ZipImport following the directions from Google's site here and here. \nfrom Google's third Party Library page:\n\nApp Engine uses a custom version of the zipimport feature instead of the standard implementation. It generally works the usual way: add the Zip archive to sys.path, then import as usual. With these exceptions:\n zipimport can only import modules stored in the archive as .py source files. It cannot import modules stored as .pyc or .pyo files.\n zipimport is implemented in pure Python, and does not use native code for decompression (C code).\n\n",
"To use third-party libraries in App Engine projects, you simply have to include them with your application when you deploy. Copy the twill folder (the one containing __init__.py) into your application's folder and deploy it. \nLooking at the twill Google Code project, it appears that twill includes its dependencies (pyparsing, mechanize, etc.) in the package, so you may not need to include anything else.\n"
] | [
3,
1,
1,
1
] | [] | [] | [
"google_app_engine",
"import",
"python",
"twill"
] | stackoverflow_0002717325_google_app_engine_import_python_twill.txt |
Q:
Resolving a relative path from py:match in a genshi template
<py:match path="foo">
<?python
import os
href = select('@href').render()
SOMEWHERE = ... # what file contained the foo tag?
path = os.path.abspath(os.path.join(os.path.dirname(SOMEWHERE), href)
f = file(path,'r')
# (do something interesting with f)
?>
</py:match>
...
<foo href="../path/relative/to/this/template/abcd.xyz"/>
What should go as "somewhere" above? I want that href attribute to be relative to the file with the foo tag in it, like href attributes on other tags.
Alternatively, what file contained the py:match block? This is less good because it may be in a different directory from the file with the foo tag.
Even less good: I could supply the path of the file I'm rendering as a context argument from outside Genshi, but that might be in a different directory from both of the above.
A:
You need to make sure that the driver program (i.e., the Python program that parses the input file) runs in the directory of the file containing the foo tag. Otherwise, you need to pass down the relative path (i.e., how to get from the directory in which the reader runs to the directory of the file being read) as a context argument to your Python code and add it to the os.path.join command.
With this setup (and using Genshi 0.6 installed on MacOS X 10.6.3 via the Fink package genshi-py26) the command os.getcwd() returns the current working directory of the file containing the foo tag.
For such complicated path constructs I also strongly recommend to use path=os.path.normpath(path), since you may not want such things to leak in your resulting HTML code.
| Resolving a relative path from py:match in a genshi template | <py:match path="foo">
<?python
import os
href = select('@href').render()
SOMEWHERE = ... # what file contained the foo tag?
path = os.path.abspath(os.path.join(os.path.dirname(SOMEWHERE), href)
f = file(path,'r')
# (do something interesting with f)
?>
</py:match>
...
<foo href="../path/relative/to/this/template/abcd.xyz"/>
What should go as "somewhere" above? I want that href attribute to be relative to the file with the foo tag in it, like href attributes on other tags.
Alternatively, what file contained the py:match block? This is less good because it may be in a different directory from the file with the foo tag.
Even less good: I could supply the path of the file I'm rendering as a context argument from outside Genshi, but that might be in a different directory from both of the above.
| [
"You need to make sure that the driver program (i.e., the Python program that parses the input file) runs in the directory of the file containing the foo tag. Otherwise, you need to pass down the relative path (i.e., how to get from the directory in which the reader runs to the directory of the file being read) as a context argument to your Python code and add it to the os.path.join command.\nWith this setup (and using Genshi 0.6 installed on MacOS X 10.6.3 via the Fink package genshi-py26) the command os.getcwd() returns the current working directory of the file containing the foo tag.\nFor such complicated path constructs I also strongly recommend to use path=os.path.normpath(path), since you may not want such things to leak in your resulting HTML code.\n"
] | [
1
] | [] | [] | [
"genshi",
"python",
"relative_path"
] | stackoverflow_0001024475_genshi_python_relative_path.txt |
Q:
Testing with Unittest Python
I am runninig test's with Python Unittest. I am running tests but I want to do negative testing and I would like to test if a function throw's an exception, it passes but if no exception is thrown the test fail's. The script I have is:
try:
result = self.client.service.GetStreamUri(self.stream, self.token)
self.assertFalse
except suds.WebFault, e:
self.assertTrue
else:
self.assertTrue
This alway's passes as True even when the function work's perfectly. I have also tried various other way's including:
try:
result = self.client.service.GetStreamUri(self.stream, self.token)
self.assertFalse
except suds.WebFault, e:
self.assertTrue
except Exception, e:
self.assertTrue
Does anyone have any suggestions?
Thanks
I have tried assertRaises with no luck.
try:
result = self.client.service.GetStreamUri(self.stream, self.token)
self.assertRaises(WebFault)
except suds.WebFault, e:
self.assertFalse
except Exception, e:
self.assertTrue
It still passes. For some reason it does not try and do the assertRaises statement. I have also tried: (The function should fail but the test should pass)
try:
result = self.client.service.GetStreamUri(self.stream, self.token)
except suds.WebFault, e:
self.assertFalse
except Exception, e:
self.assertTrue
else:
self.assertFalse
For some reason even when the function passes it will not raise an error. It always no matter what goes to Exception. Unless there is an else statement then it goes to that.
Found a way that work's but it seem's a very poor way of doing things:
Can anyone suggest a cleaner way of doing this?
try:
result = self.client.service.GetStreamUri(self.stream, self.token)
except suds.WebFault, e:
self.assertFalse
except Exception, e:
pass
try:
result==result
except:
result=None
if result==None:
assert True
else:
assert False
A:
TestCase.assertRaises is what you need however in your example you appear to be misusing it slightly. You need something like:
def test_GetStreamUri(self):
self.assertRaises(WebFault, self.client.service.GetStreamUri)
result = self.client.service.GetStreamUri(self.stream, self.token)
You need to tell unittest about the callable the will raise the exception before you invoke the callable.
A:
Have you tried assertRaises?
A:
The excellent nose unit testing provides a @raises decorator:
@raises(TypeError)
def test_raises_type_error():
raise TypeError("This test passes")
A:
You should maybe call self.assertTrue(True) and self.assertFalse(True), because you are not realy calling the functions right now, just referencing them. Still, there has to be a cleaner way to do this.
| Testing with Unittest Python | I am runninig test's with Python Unittest. I am running tests but I want to do negative testing and I would like to test if a function throw's an exception, it passes but if no exception is thrown the test fail's. The script I have is:
try:
result = self.client.service.GetStreamUri(self.stream, self.token)
self.assertFalse
except suds.WebFault, e:
self.assertTrue
else:
self.assertTrue
This alway's passes as True even when the function work's perfectly. I have also tried various other way's including:
try:
result = self.client.service.GetStreamUri(self.stream, self.token)
self.assertFalse
except suds.WebFault, e:
self.assertTrue
except Exception, e:
self.assertTrue
Does anyone have any suggestions?
Thanks
I have tried assertRaises with no luck.
try:
result = self.client.service.GetStreamUri(self.stream, self.token)
self.assertRaises(WebFault)
except suds.WebFault, e:
self.assertFalse
except Exception, e:
self.assertTrue
It still passes. For some reason it does not try and do the assertRaises statement. I have also tried: (The function should fail but the test should pass)
try:
result = self.client.service.GetStreamUri(self.stream, self.token)
except suds.WebFault, e:
self.assertFalse
except Exception, e:
self.assertTrue
else:
self.assertFalse
For some reason even when the function passes it will not raise an error. It always no matter what goes to Exception. Unless there is an else statement then it goes to that.
Found a way that work's but it seem's a very poor way of doing things:
Can anyone suggest a cleaner way of doing this?
try:
result = self.client.service.GetStreamUri(self.stream, self.token)
except suds.WebFault, e:
self.assertFalse
except Exception, e:
pass
try:
result==result
except:
result=None
if result==None:
assert True
else:
assert False
| [
"TestCase.assertRaises is what you need however in your example you appear to be misusing it slightly. You need something like:\ndef test_GetStreamUri(self):\n self.assertRaises(WebFault, self.client.service.GetStreamUri)\n result = self.client.service.GetStreamUri(self.stream, self.token)\n\nYou need to tell unittest about the callable the will raise the exception before you invoke the callable.\n",
"Have you tried assertRaises?\n",
"The excellent nose unit testing provides a @raises decorator:\n@raises(TypeError)\ndef test_raises_type_error():\n raise TypeError(\"This test passes\")\n\n",
"You should maybe call self.assertTrue(True) and self.assertFalse(True), because you are not realy calling the functions right now, just referencing them. Still, there has to be a cleaner way to do this.\n"
] | [
5,
1,
1,
0
] | [] | [] | [
"exception",
"python",
"testing",
"unit_testing"
] | stackoverflow_0002874753_exception_python_testing_unit_testing.txt |
Q:
How do I parse a templated string in Python?
I'm new to Python, so I'm not sure exactly what this operation is called, hence I'm having a hard time searching for information in it.
Basically I'd like to have a string such as:
"[[size]] widget that [[verb]] [[noun]]"
Where size, verb, and noun are each a list.
I'd like to interpret the string as a metalanguage, such that I can make lots of sentences out permutations from the lists. As a metalanguage, I'd also be able to make other strings that use those pre-defined lists to generate more permutations.
Are there any capabilities for variable substitution like this in Python? What term describes this operation if I should just Google it?
A:
If you change your syntax to
"{size} widget that {verb} {noun}"
Then you could use string's format method to do the substitutions:
"{size} widget that {verb} {noun}".format(size='Tiny',verb='pounds',noun='nails')
or
choice={'size':'Big',
'verb':'plugs',
'noun':'holes'}
"{size} widget that {verb} {noun}".format(**choice)
A:
Here's one possible implementation if you have sizes, verbes, nounes lists:
import itertools, string
t = string.Template("$size widget that $verb $noun")
for size, verb, noun in itertools.product(sizes, verbes, nounes):
print t.safe_substitute(size=size, verb=verb, noun=noun)
A:
Try this script:
import random #just needed for the example, not the technique itself
import re # regular expression module for Python
template = '[[size]] widget that [[verb]] [[noun]]'
p = re.compile('(\[\[([a-z]+)\]\])') # match placeholder and the word inside
matches = p.findall(template) # find all matches in template as a list
#example values to show you can do substitution
values = {
'size': ('tiny', 'small', 'large'),
'verb': ('jumps', 'throws', 'raises'),
'noun': ('shark', 'ball', 'roof')
}
print 'After each sentence is printed, hit Enter to continue or Ctrl-C to stop.'
while True: # forever
s = template
#this loop replaces each placeholder [[word]] with random value based on word
for placeholder, key in matches:
s = s.replace(placeholder, random.choice(values[key]))
print s
try:
raw_input('') # pause for input
except KeyboardInterrupt: #Ctrl-C
break # out of loop
Example output:
large widget that jumps ball
small widget that raises ball
small widget that raises ball
large widget that jumps ball
small widget that raises ball
tiny widget that raises shark
small widget that jumps ball
tiny widget that raises shark
A:
You want to use re.sub() or its regex object equivalent method with a callback function.
A:
Regex is overkill. Use loops to set the size verb and noun variables then:
print("%(size)s widget that %(verb)s %(noun)s" % {"size":size, "verb":verb, "noun":noun})
| How do I parse a templated string in Python? | I'm new to Python, so I'm not sure exactly what this operation is called, hence I'm having a hard time searching for information in it.
Basically I'd like to have a string such as:
"[[size]] widget that [[verb]] [[noun]]"
Where size, verb, and noun are each a list.
I'd like to interpret the string as a metalanguage, such that I can make lots of sentences out permutations from the lists. As a metalanguage, I'd also be able to make other strings that use those pre-defined lists to generate more permutations.
Are there any capabilities for variable substitution like this in Python? What term describes this operation if I should just Google it?
| [
"If you change your syntax to\n\"{size} widget that {verb} {noun}\"\n\nThen you could use string's format method to do the substitutions:\n\"{size} widget that {verb} {noun}\".format(size='Tiny',verb='pounds',noun='nails')\n\nor \nchoice={'size':'Big',\n 'verb':'plugs',\n 'noun':'holes'}\n\"{size} widget that {verb} {noun}\".format(**choice)\n\n",
"Here's one possible implementation if you have sizes, verbes, nounes lists:\nimport itertools, string\n\nt = string.Template(\"$size widget that $verb $noun\")\nfor size, verb, noun in itertools.product(sizes, verbes, nounes):\n print t.safe_substitute(size=size, verb=verb, noun=noun)\n\n",
"Try this script:\nimport random #just needed for the example, not the technique itself\nimport re # regular expression module for Python\n\ntemplate = '[[size]] widget that [[verb]] [[noun]]'\np = re.compile('(\\[\\[([a-z]+)\\]\\])') # match placeholder and the word inside\nmatches = p.findall(template) # find all matches in template as a list\n\n#example values to show you can do substitution\nvalues = {\n 'size': ('tiny', 'small', 'large'),\n 'verb': ('jumps', 'throws', 'raises'),\n 'noun': ('shark', 'ball', 'roof')\n}\n\nprint 'After each sentence is printed, hit Enter to continue or Ctrl-C to stop.'\n\nwhile True: # forever\n s = template\n #this loop replaces each placeholder [[word]] with random value based on word\n for placeholder, key in matches:\n s = s.replace(placeholder, random.choice(values[key]))\n print s\n try:\n raw_input('') # pause for input\n except KeyboardInterrupt: #Ctrl-C\n break # out of loop\n\nExample output:\nlarge widget that jumps ball\n\nsmall widget that raises ball\n\nsmall widget that raises ball\n\nlarge widget that jumps ball\n\nsmall widget that raises ball\n\ntiny widget that raises shark\n\nsmall widget that jumps ball\n\ntiny widget that raises shark\n\n",
"You want to use re.sub() or its regex object equivalent method with a callback function.\n",
"Regex is overkill. Use loops to set the size verb and noun variables then:\nprint(\"%(size)s widget that %(verb)s %(noun)s\" % {\"size\":size, \"verb\":verb, \"noun\":noun})\n\n"
] | [
7,
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002869128_python.txt |
Q:
Preprocess SHPAML in Django's template loader?
Is there any way to make Django's template loader run all templates it loads (i.e. directly or via extend/include) through SHPAML if it figures the HTML is out of date?
I know how to invoke SHPAML recursively over an entire directory, but I would prefer to be able to run it on demand so I don't have to remember to sync the HTML every time I change the SHPAML source.
I guess invoking SHPAML from manage.py would work too (at least for test servers), but being able to hack into Django's template engine and make it run every file it loads through a preprocessor would be nicer.
A:
I suspect you can achieve what you want by inheriting from django.template.loaders.app_directories.Loader (or whatever loader you use) and overwriting the load_template_source method, e.g.:
from django.template.loaders.app_directories import Loader
from shpaml import convert_text
class SHPAMLLoader(Loader):
def load_template_source(self, *args, **kwargs):
shpaml_source = super(SHPAMLLoader, self).load_template_source(*args, **kwargs)
html = convert_text(shpaml_source)
return html
Then put your loader at the beginning of the TEMPLATE_LOADERS tuple in your settings.py. Of course, you will be doing the SHPAML to HTML dance every time a template is loaded, so you may see some overhead. The upcoming Django 1.2 features template caching, which could help mitigating that overhead...
Disclaimer: this code is completely untested, sorry.
A:
Just created a project based on the snippet in piquadrat's answer. It's a little more feature complete and supports django 1.1 and 1.2 (probably 1.0 as well)
django-shpaml-template-loader on bitbucket
Thought it might come in handy for the future :)
| Preprocess SHPAML in Django's template loader? | Is there any way to make Django's template loader run all templates it loads (i.e. directly or via extend/include) through SHPAML if it figures the HTML is out of date?
I know how to invoke SHPAML recursively over an entire directory, but I would prefer to be able to run it on demand so I don't have to remember to sync the HTML every time I change the SHPAML source.
I guess invoking SHPAML from manage.py would work too (at least for test servers), but being able to hack into Django's template engine and make it run every file it loads through a preprocessor would be nicer.
| [
"I suspect you can achieve what you want by inheriting from django.template.loaders.app_directories.Loader (or whatever loader you use) and overwriting the load_template_source method, e.g.:\nfrom django.template.loaders.app_directories import Loader\nfrom shpaml import convert_text\n\nclass SHPAMLLoader(Loader):\n def load_template_source(self, *args, **kwargs):\n shpaml_source = super(SHPAMLLoader, self).load_template_source(*args, **kwargs)\n html = convert_text(shpaml_source)\n return html\n\nThen put your loader at the beginning of the TEMPLATE_LOADERS tuple in your settings.py. Of course, you will be doing the SHPAML to HTML dance every time a template is loaded, so you may see some overhead. The upcoming Django 1.2 features template caching, which could help mitigating that overhead...\nDisclaimer: this code is completely untested, sorry.\n",
"Just created a project based on the snippet in piquadrat's answer. It's a little more feature complete and supports django 1.1 and 1.2 (probably 1.0 as well)\n\ndjango-shpaml-template-loader on bitbucket\n\nThought it might come in handy for the future :)\n"
] | [
3,
1
] | [] | [] | [
"django",
"preprocessor",
"python",
"shpaml",
"templates"
] | stackoverflow_0002131029_django_preprocessor_python_shpaml_templates.txt |
Q:
How can I create a GUI on top of a Python APP so it can do either GUI or CLI?
I am trying to write an app in python to control a motor using serial. This all works in a CLI situation fine and is generally stable. but I was wondering how simple it was to add a GUI on top of this code base?
I assume there will be more code, but is there a simple way of detecting something like GTK, so it only applied the code when GTK was present?
Also, GUI creation in Python in general: is it best to keep as little GUI specifics out of the code and use something like GTK's XML based approach (using gtk.glade.XML() function)? Are there other GUI toolkits that have a similar approach to the Glade / XML / "Explode in Code" approach?
Thanks for any advice.
Andy
A:
is there a simple way of detecting something like GTK, so it only applied the code when GTK was present?
First, break your app into 3 separate modules.
The actual work: foo_core.py.
A CLI module that imports foo_core. Call it foo_cli.py.
A GUI module that imports foo_core. Call it foo_gui.pyw.
The foo_cli module looks like this.
import foo_core
import optparse
def main():
# parse the command-line options
# the real work is done by foo_core
if __name__ == "__main__":
main()
The foo_gui module can look like this.
import foo_core
import gtk # or whatever
def main()
# build the GUI
# real work is done by foo_core under control of the GUI
if __name__ == "__main__":
main()
That's generally sufficient. People can be trusted to decide for themselves if they want CLI or GUI.
If you want to confuse people, you can write a foo.py script that does something like the following.
try:
import foo_gui
foo_gui.main()
except ImportError:
import foo_cli
foo_cli.main()
A:
It depends on which kind of interaction you want.
If you want a real GUI you can use the humble dialog pattern to decouple the GUI stuff from the program logic, and use a text "GUI" to handle the CLI. This also has the nice side-effect that big parts of the GUI get programmable testable.
Another way is to assign sys.stdin and sys.stout with own objects, which redirect your programs IO to the GUI (this does not work with non-python libraries). This means that you have fewer interaction possibilities in the GUI, but much less programming effort.
A:
I don't recommend doing a GUI in XML. All the XML does is give you a mini language for describing a layout. Why use a mini language when you can have the full power of python?
As for detecting GTK, I wouldn't suggest that. Instead, add a command line argument to determine whether to create a GUI or not (eg: myprogram -g). It then becomes easy to create a desktop shortcut or command line alias to start in GUI mode, while still being able to use the command line tool from any terminal.
You do, however, want to keep the GUI code separate from the bits that do the real work. Give youself a class that contains all the business logic, then have the GUI and CLI both access this object to do work.
A:
Well, what I do is that I have a one and only bash script with the following:
if [ "${0}" == "mcm" ]; then
/usr/bin/python ${inst_dir}/terminal/mcm-terminal.py ${@}
else
/usr/bin/python ${inst_dir}/gtk/mcm-gtk.py &
fi
Then I create two symlinks: /usr/sbin/mcm and /usr/bin/mcm-gtk
Works very nice.
| How can I create a GUI on top of a Python APP so it can do either GUI or CLI? | I am trying to write an app in python to control a motor using serial. This all works in a CLI situation fine and is generally stable. but I was wondering how simple it was to add a GUI on top of this code base?
I assume there will be more code, but is there a simple way of detecting something like GTK, so it only applied the code when GTK was present?
Also, GUI creation in Python in general: is it best to keep as little GUI specifics out of the code and use something like GTK's XML based approach (using gtk.glade.XML() function)? Are there other GUI toolkits that have a similar approach to the Glade / XML / "Explode in Code" approach?
Thanks for any advice.
Andy
| [
"\nis there a simple way of detecting something like GTK, so it only applied the code when GTK was present?\n\nFirst, break your app into 3 separate modules.\n\nThe actual work: foo_core.py.\nA CLI module that imports foo_core. Call it foo_cli.py.\nA GUI module that imports foo_core. Call it foo_gui.pyw. \n\nThe foo_cli module looks like this.\nimport foo_core\nimport optparse\n\ndef main():\n # parse the command-line options\n # the real work is done by foo_core\n\nif __name__ == \"__main__\":\n main()\n\nThe foo_gui module can look like this.\n import foo_core\n import gtk # or whatever\n\n def main()\n # build the GUI\n # real work is done by foo_core under control of the GUI\n\n if __name__ == \"__main__\":\n main()\n\nThat's generally sufficient. People can be trusted to decide for themselves if they want CLI or GUI.\nIf you want to confuse people, you can write a foo.py script that does something like the following.\ntry:\n import foo_gui\n foo_gui.main()\nexcept ImportError:\n import foo_cli\n foo_cli.main()\n\n",
"It depends on which kind of interaction you want.\nIf you want a real GUI you can use the humble dialog pattern to decouple the GUI stuff from the program logic, and use a text \"GUI\" to handle the CLI. This also has the nice side-effect that big parts of the GUI get programmable testable.\nAnother way is to assign sys.stdin and sys.stout with own objects, which redirect your programs IO to the GUI (this does not work with non-python libraries). This means that you have fewer interaction possibilities in the GUI, but much less programming effort.\n",
"I don't recommend doing a GUI in XML. All the XML does is give you a mini language for describing a layout. Why use a mini language when you can have the full power of python?\nAs for detecting GTK, I wouldn't suggest that. Instead, add a command line argument to determine whether to create a GUI or not (eg: myprogram -g). It then becomes easy to create a desktop shortcut or command line alias to start in GUI mode, while still being able to use the command line tool from any terminal.\nYou do, however, want to keep the GUI code separate from the bits that do the real work. Give youself a class that contains all the business logic, then have the GUI and CLI both access this object to do work.\n",
"Well, what I do is that I have a one and only bash script with the following:\nif [ \"${0}\" == \"mcm\" ]; then\n /usr/bin/python ${inst_dir}/terminal/mcm-terminal.py ${@}\nelse\n /usr/bin/python ${inst_dir}/gtk/mcm-gtk.py &\nfi\n\nThen I create two symlinks: /usr/sbin/mcm and /usr/bin/mcm-gtk\nWorks very nice.\n"
] | [
12,
1,
0,
0
] | [] | [] | [
"glade",
"gtk",
"python",
"user_interface",
"xml"
] | stackoverflow_0002857634_glade_gtk_python_user_interface_xml.txt |
Q:
cx_Freeze and PYC/PYD files
I'm using cx_Freeze to freeze my python program. On running cx_Freeze, a bunch of PYD files are created, a whole bunch of PYC files are put into a archive named library.zip and a few DLL files are there too.
Could someone tell me the difference between the PYC and the PYD files?
What's the reason for the PYD files not in the library.zip?
Is it possible to put the PYD files into the archive as well?
Thanks.
A:
Disclaimer: I haven't used cx_Freeze in awhile......
.PYD files are DLL machine-code files that contain specific python-required functions.
.PYC files are .py files that have been compiled into bytecode.
so PYDs are machine code and PYCs are bytecode
Now as for why the PYDs aren't in the .zip....I'd imagine it's because those .PYDs are needed by the python interpreter to run the program. What cx_Freeze does is basically this:
compile all .py files and throw the .pyc files in a zip
put all needed .pyd files in the zip
create a stub .py file and put it in the output directory
copy the python.exe and rename to myprogram.exe
copy all .pyd files needed to open the .zip and run the contents
So you're not actually compiling your python file, you're instead renaming the interpeter and freezing all the source files.
I hope this helps.
| cx_Freeze and PYC/PYD files | I'm using cx_Freeze to freeze my python program. On running cx_Freeze, a bunch of PYD files are created, a whole bunch of PYC files are put into a archive named library.zip and a few DLL files are there too.
Could someone tell me the difference between the PYC and the PYD files?
What's the reason for the PYD files not in the library.zip?
Is it possible to put the PYD files into the archive as well?
Thanks.
| [
"Disclaimer: I haven't used cx_Freeze in awhile......\n.PYD files are DLL machine-code files that contain specific python-required functions. \n.PYC files are .py files that have been compiled into bytecode.\nso PYDs are machine code and PYCs are bytecode\nNow as for why the PYDs aren't in the .zip....I'd imagine it's because those .PYDs are needed by the python interpreter to run the program. What cx_Freeze does is basically this:\n\ncompile all .py files and throw the .pyc files in a zip\nput all needed .pyd files in the zip\ncreate a stub .py file and put it in the output directory\ncopy the python.exe and rename to myprogram.exe\ncopy all .pyd files needed to open the .zip and run the contents\n\nSo you're not actually compiling your python file, you're instead renaming the interpeter and freezing all the source files. \nI hope this helps.\n"
] | [
6
] | [] | [] | [
"cx_freeze",
"python"
] | stackoverflow_0002875530_cx_freeze_python.txt |
Q:
Shuttle control in wxPython
I'm trying to implement a shuttle control in wxPython but there doesn't seem to be one. I've decided to use two listbox controls. The shuttle control looks like this:
alt text http://knol.google.com/k/-/-/153594c4goidl/p559ta/picture-52.png
I've got two listboxes — one's populated, one's not. Could someone show me how to add a selected item to the second list box when it is double clicked? It should be removed from the first. When it is double clicked in the second, it should be added to the first and removed from the second. The shuttle control implements these by default but it's a pity it isn't there.
Thank you.
A:
i don't know what a shuttle control is exactly, maybe for videos? maybe this will help
# in your init method
self.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, self.mainlist)
# the callback
def EvtListBoxDClick(self, event):
self.otherlist.Append(self.mainlist.GetSelection())
self.mainlist.Delete(self.lb1.GetSelection())
Take a look at the WxPython example file included with the distribution (ListBox.py)
Cheers
| Shuttle control in wxPython | I'm trying to implement a shuttle control in wxPython but there doesn't seem to be one. I've decided to use two listbox controls. The shuttle control looks like this:
alt text http://knol.google.com/k/-/-/153594c4goidl/p559ta/picture-52.png
I've got two listboxes — one's populated, one's not. Could someone show me how to add a selected item to the second list box when it is double clicked? It should be removed from the first. When it is double clicked in the second, it should be added to the first and removed from the second. The shuttle control implements these by default but it's a pity it isn't there.
Thank you.
| [
"i don't know what a shuttle control is exactly, maybe for videos? maybe this will help\n# in your init method\nself.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, self.mainlist)\n\n\n# the callback\ndef EvtListBoxDClick(self, event):\n self.otherlist.Append(self.mainlist.GetSelection())\n self.mainlist.Delete(self.lb1.GetSelection())\n\nTake a look at the WxPython example file included with the distribution (ListBox.py)\nCheers\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002871762_python_wxpython.txt |
Q:
Does setup.py's extras_require keyword support comma-separated extras?
Setuptools lets you list requirements for optional features
# mypackage
'extras_require' : { 'PDF' : ['reportlab'], 'DOCX' : ['docxlib'] }
and another package can specify 'requires' : [ 'mypackage[PDF]' ].
If another package wants to require more than one extra from the first package, can it ask for 'requires' : [ 'mypackage[PDF, DOCX]' ]?
A:
from: http://peak.telecommunity.com/DevCenter/setuptools#declaring-dependencies
setuptools and pkg_resources use a common syntax for specifying a project's required dependencies. This syntax consists of a project's PyPI name, optionally followed by a comma-separated list of "extras" in square brackets, optionally followed by a comma-separated list of version specifiers
...so your answer is yes
| Does setup.py's extras_require keyword support comma-separated extras? | Setuptools lets you list requirements for optional features
# mypackage
'extras_require' : { 'PDF' : ['reportlab'], 'DOCX' : ['docxlib'] }
and another package can specify 'requires' : [ 'mypackage[PDF]' ].
If another package wants to require more than one extra from the first package, can it ask for 'requires' : [ 'mypackage[PDF, DOCX]' ]?
| [
"from: http://peak.telecommunity.com/DevCenter/setuptools#declaring-dependencies\nsetuptools and pkg_resources use a common syntax for specifying a project's required dependencies. This syntax consists of a project's PyPI name, optionally followed by a comma-separated list of \"extras\" in square brackets, optionally followed by a comma-separated list of version specifiers\n...so your answer is yes\n"
] | [
6
] | [] | [] | [
"distutils",
"python",
"setuptools"
] | stackoverflow_0002321798_distutils_python_setuptools.txt |
Q:
What's the fastest way to strip and replace a document of high unicode characters using Python?
I am looking to replace from a large document all high unicode characters, such as accented Es, left and right quotes, etc., with "normal" counterparts in the low range, such as a regular 'E', and straight quotes. I need to perform this on a very large document rather often. I see an example of this in what I think might be perl here: http://www.designmeme.com/mtplugins/lowdown.txt
Is there a fast way of doing this in Python without using s.replace(...).replace(...).replace(...)...? I've tried this on just a few characters to replace and the document stripping became really slow.
EDIT, my version of unutbu's code that doesn't seem to work:
# -*- coding: iso-8859-15 -*-
import unidecode
def ascii_map():
data={}
for num in range(256):
h=num
filename='x{num:02x}'.format(num=num)
try:
mod = __import__('unidecode.'+filename,
fromlist=True)
except ImportError:
pass
else:
for l,val in enumerate(mod.data):
i=h<<8
i+=l
if i >= 0x80:
data[i]=unicode(val)
return data
if __name__=='__main__':
s = u'“fancy“fancy2'
print(s.translate(ascii_map()))
A:
# -*- encoding: utf-8 -*-
import unicodedata
def shoehorn_unicode_into_ascii(s):
return unicodedata.normalize('NFKD', s).encode('ascii','ignore')
if __name__=='__main__':
s = u"éèêàùçÇ"
print(shoehorn_unicode_into_ascii(s))
# eeeaucC
Note, as @Mark Tolonen kindly points out, the method above removes some characters like
ß‘’“”. If the above code truncates characters that you wish translated, then you may have to use the string's translate method to manually fix these problems. Another option is to use unidecode (see J.F. Sebastian's answer).
When you have a large unicode string, using its translate method will be much
much faster than using the replace method.
Edit: unidecode has a more complete mapping of unicode codepoints to ascii.
However, unidecode.unidecode loops through the string character-by-character (in a Python loop), which is slower than using the translate method.
The following helper function uses unidecode's data files, and the translate method to attain better speed, especially for long strings.
In my tests on 1-6 MB text files, using ascii_map is about 4-6 times faster than unidecode.unidecode.
# -*- coding: utf-8 -*-
import unidecode
def ascii_map():
data={}
for num in range(256):
h=num
filename='x{num:02x}'.format(num=num)
try:
mod = __import__('unidecode.'+filename,
fromlist=True)
except ImportError:
pass
else:
for l,val in enumerate(mod.data):
i=h<<8
i+=l
if i >= 0x80:
data[i]=unicode(val)
return data
if __name__=='__main__':
s = u"éèêàùçÇ"
print(s.translate(ascii_map()))
# eeeaucC
Edit2: Rhubarb, if # -*- encoding: utf-8 -*- is causing a SyntaxError, try
# -*- encoding: cp1252 -*-. What encoding to declare depends on what encoding your text editor uses to save the file. Linux tends to use utf-8, and (it seems perhaps) Windows tends to cp1252.
A:
There is no such thing as a "high ascii character". The ASCII character set is limited to ordinal in range(128).
That aside, this is a FAQ. Here's one answer. In general, you should familiarise yourself with str.translate() and unicode.translate() -- very handy for multiple substitutions of single bytes/characters. Beware of answers that mention only the unicodedata.normalize() gimmick; that's just one part of the solution.
Update: The currently-accepted answer blows away characters that don't have a decomposition, as pointed out by Mark Tolonen. There seems to be a lack of knowledge of what unicode.translate() is capable of. It CAN translate one character into multiple characters. Here is the output from help(unicode.translate):
S.translate(table) -> unicode
Return a copy of the string S, where all characters have been mapped through the given translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.
Here's an example:
>>> u"Gau\xdf".translate({0xdf: u"ss"})
u'Gauss'
>>>
Here's a table of fix-ups from the solution that I pointed to:
CHAR_REPLACEMENT = {
# latin-1 characters that don't have a unicode decomposition
0xc6: u"AE", # LATIN CAPITAL LETTER AE
0xd0: u"D", # LATIN CAPITAL LETTER ETH
0xd8: u"OE", # LATIN CAPITAL LETTER O WITH STROKE
0xde: u"Th", # LATIN CAPITAL LETTER THORN
0xdf: u"ss", # LATIN SMALL LETTER SHARP S
0xe6: u"ae", # LATIN SMALL LETTER AE
0xf0: u"d", # LATIN SMALL LETTER ETH
0xf8: u"oe", # LATIN SMALL LETTER O WITH STROKE
0xfe: u"th", # LATIN SMALL LETTER THORN
}
This can be easily extended to cater for the fancy quotes and other non-latin-1 characters found in cp1252 and siblings.
A:
I believe that unicodedata doesn't work for fancy quotes. You could use Unidecode in this case:
import unidecode
print unidecode.unidecode(u"ß‘’“”")
# -> ss''""
A:
If unicodedata.normalize() as suggested by ~unubtu doesn't do the trick, for example if you want more control over the mapping, you should look into
str.translate()
along with str.maketrans(), a utility to produce a map table, str.translate is both efficient and convenient for this type of translation.
In Python 2.x and for unicode strings one needs to use unicode.translate() rather than str.translate() and a trick similar to the one shown in the code snippet below, in lieu of maketrans(). (thanks to John Machin for pointing this out!)
These methods are also availble in in Python 3.x see for example the Python 3.1.2 documentation (for some reason I had made a mental note that this may have changed in Python 3.x). Of course under Python 3, all strings are unicode strings, but that's other issue.
#Python 3.1
>>> intab = 'àâçêèéïîôù'
>>> outtab = 'aaceeeiiou'
>>> tmap = str.maketrans(intab, outtab)
>>> s = "à la fête de l'été, où il fait bon danser, les Français font les drôles"
>>> s
"à la fête de l'été, où il fait bon danser, les Français font les drôles"
>>> s.translate(tmap)
"a la fete de l'ete, ou il fait bon danser, les Francais font les droles"
>>>
#Python 2.6
>>> intab = u'àâçêèéïîôù'
>>> outtab = u'aaceeeiiou'
>>> s = u"à la fête de l'été, où il fait bon danser, les Français font les drôles"
>>> #note the trick to replace maketrans() since for unicode strings the translation
>>> # map expects integers (unicode ordinals) not characters.
>>> tmap = dict(zip(map(ord, intab), map(ord, outtab)))
>>> s.translate(tmap)
u"a la fete de l'ete, ou il fait bon danser, les Francais font les droles"
>>>
A:
Here's a solution that handles latin-1 characters (based on a 2003 usenet thread):
>>> accentstable = str.join("", map(chr, range(192))) + "AAAAAAACEEEEIIIIDNOOOOOxOUUUUYTsaaaaaaaceeeeiiiidnooooo/ouuuuyty"
>>> import string
>>> s = u"éèêàùçÇ"
>>> print string.translate(s.encode('latin1', 'ignore'), accentstable)
eeeaucC
Some of the mappings aren't perfect e.g. Thorn maps to T rather than Th, but it does a tolerable job.
| What's the fastest way to strip and replace a document of high unicode characters using Python? | I am looking to replace from a large document all high unicode characters, such as accented Es, left and right quotes, etc., with "normal" counterparts in the low range, such as a regular 'E', and straight quotes. I need to perform this on a very large document rather often. I see an example of this in what I think might be perl here: http://www.designmeme.com/mtplugins/lowdown.txt
Is there a fast way of doing this in Python without using s.replace(...).replace(...).replace(...)...? I've tried this on just a few characters to replace and the document stripping became really slow.
EDIT, my version of unutbu's code that doesn't seem to work:
# -*- coding: iso-8859-15 -*-
import unidecode
def ascii_map():
data={}
for num in range(256):
h=num
filename='x{num:02x}'.format(num=num)
try:
mod = __import__('unidecode.'+filename,
fromlist=True)
except ImportError:
pass
else:
for l,val in enumerate(mod.data):
i=h<<8
i+=l
if i >= 0x80:
data[i]=unicode(val)
return data
if __name__=='__main__':
s = u'“fancy“fancy2'
print(s.translate(ascii_map()))
| [
"# -*- encoding: utf-8 -*-\nimport unicodedata\n\ndef shoehorn_unicode_into_ascii(s):\n return unicodedata.normalize('NFKD', s).encode('ascii','ignore')\n\nif __name__=='__main__':\n s = u\"éèêàùçÇ\"\n print(shoehorn_unicode_into_ascii(s))\n # eeeaucC\n\nNote, as @Mark Tolonen kindly points out, the method above removes some characters like\nß‘’“”. If the above code truncates characters that you wish translated, then you may have to use the string's translate method to manually fix these problems. Another option is to use unidecode (see J.F. Sebastian's answer). \nWhen you have a large unicode string, using its translate method will be much\nmuch faster than using the replace method. \nEdit: unidecode has a more complete mapping of unicode codepoints to ascii.\nHowever, unidecode.unidecode loops through the string character-by-character (in a Python loop), which is slower than using the translate method.\nThe following helper function uses unidecode's data files, and the translate method to attain better speed, especially for long strings.\nIn my tests on 1-6 MB text files, using ascii_map is about 4-6 times faster than unidecode.unidecode.\n# -*- coding: utf-8 -*-\nimport unidecode\ndef ascii_map():\n data={}\n for num in range(256):\n h=num\n filename='x{num:02x}'.format(num=num)\n try:\n mod = __import__('unidecode.'+filename,\n fromlist=True)\n except ImportError:\n pass\n else:\n for l,val in enumerate(mod.data):\n i=h<<8\n i+=l\n if i >= 0x80:\n data[i]=unicode(val)\n return data\n\nif __name__=='__main__':\n s = u\"éèêàùçÇ\"\n print(s.translate(ascii_map()))\n # eeeaucC\n\nEdit2: Rhubarb, if # -*- encoding: utf-8 -*- is causing a SyntaxError, try \n# -*- encoding: cp1252 -*-. What encoding to declare depends on what encoding your text editor uses to save the file. Linux tends to use utf-8, and (it seems perhaps) Windows tends to cp1252.\n",
"There is no such thing as a \"high ascii character\". The ASCII character set is limited to ordinal in range(128).\nThat aside, this is a FAQ. Here's one answer. In general, you should familiarise yourself with str.translate() and unicode.translate() -- very handy for multiple substitutions of single bytes/characters. Beware of answers that mention only the unicodedata.normalize() gimmick; that's just one part of the solution.\nUpdate: The currently-accepted answer blows away characters that don't have a decomposition, as pointed out by Mark Tolonen. There seems to be a lack of knowledge of what unicode.translate() is capable of. It CAN translate one character into multiple characters. Here is the output from help(unicode.translate):\n\nS.translate(table) -> unicode\nReturn a copy of the string S, where all characters have been mapped through the given translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.\n\nHere's an example:\n>>> u\"Gau\\xdf\".translate({0xdf: u\"ss\"})\nu'Gauss'\n>>>\n\nHere's a table of fix-ups from the solution that I pointed to:\nCHAR_REPLACEMENT = {\n # latin-1 characters that don't have a unicode decomposition\n 0xc6: u\"AE\", # LATIN CAPITAL LETTER AE\n 0xd0: u\"D\", # LATIN CAPITAL LETTER ETH\n 0xd8: u\"OE\", # LATIN CAPITAL LETTER O WITH STROKE\n 0xde: u\"Th\", # LATIN CAPITAL LETTER THORN\n 0xdf: u\"ss\", # LATIN SMALL LETTER SHARP S\n 0xe6: u\"ae\", # LATIN SMALL LETTER AE\n 0xf0: u\"d\", # LATIN SMALL LETTER ETH\n 0xf8: u\"oe\", # LATIN SMALL LETTER O WITH STROKE\n 0xfe: u\"th\", # LATIN SMALL LETTER THORN\n }\n\nThis can be easily extended to cater for the fancy quotes and other non-latin-1 characters found in cp1252 and siblings.\n",
"I believe that unicodedata doesn't work for fancy quotes. You could use Unidecode in this case:\nimport unidecode\nprint unidecode.unidecode(u\"ß‘’“”\")\n# -> ss''\"\"\n\n",
"If unicodedata.normalize() as suggested by ~unubtu doesn't do the trick, for example if you want more control over the mapping, you should look into\nstr.translate()\nalong with str.maketrans(), a utility to produce a map table, str.translate is both efficient and convenient for this type of translation.\nIn Python 2.x and for unicode strings one needs to use unicode.translate() rather than str.translate() and a trick similar to the one shown in the code snippet below, in lieu of maketrans(). (thanks to John Machin for pointing this out!)\nThese methods are also availble in in Python 3.x see for example the Python 3.1.2 documentation (for some reason I had made a mental note that this may have changed in Python 3.x). Of course under Python 3, all strings are unicode strings, but that's other issue.\n#Python 3.1\n>>> intab = 'àâçêèéïîôù'\n>>> outtab = 'aaceeeiiou'\n>>> tmap = str.maketrans(intab, outtab)\n>>> s = \"à la fête de l'été, où il fait bon danser, les Français font les drôles\"\n>>> s\n\"à la fête de l'été, où il fait bon danser, les Français font les drôles\"\n>>> s.translate(tmap)\n\"a la fete de l'ete, ou il fait bon danser, les Francais font les droles\"\n>>>\n\n\n#Python 2.6\n>>> intab = u'àâçêèéïîôù'\n>>> outtab = u'aaceeeiiou'\n>>> s = u\"à la fête de l'été, où il fait bon danser, les Français font les drôles\"\n>>> #note the trick to replace maketrans() since for unicode strings the translation\n>>> # map expects integers (unicode ordinals) not characters.\n>>> tmap = dict(zip(map(ord, intab), map(ord, outtab))) \n>>> s.translate(tmap)\nu\"a la fete de l'ete, ou il fait bon danser, les Francais font les droles\"\n>>>\n\n",
"Here's a solution that handles latin-1 characters (based on a 2003 usenet thread):\n>>> accentstable = str.join(\"\", map(chr, range(192))) + \"AAAAAAACEEEEIIIIDNOOOOOxOUUUUYTsaaaaaaaceeeeiiiidnooooo/ouuuuyty\"\n>>> import string\n>>> s = u\"éèêàùçÇ\"\n>>> print string.translate(s.encode('latin1', 'ignore'), accentstable)\neeeaucC\n\nSome of the mappings aren't perfect e.g. Thorn maps to T rather than Th, but it does a tolerable job.\n"
] | [
8,
4,
3,
1,
0
] | [] | [] | [
"ascii",
"parsing",
"python",
"text_processing",
"unicode"
] | stackoverflow_0002854230_ascii_parsing_python_text_processing_unicode.txt |
Q:
Django startup problems
This is something similar to what's posted here: No Module named django.core
To reiterate, I'm getting this error on running "django-admin.py startproject mysite"(without the double quotes):
C:\Documents and Settings\fixavier\Desktop>django-admin.py startproject mysite
Traceback (most recent call last):
File "C:\Program Files\BitNami DjangoStack\apps\django\django\bin\django-admin.py", line 2, in <module>
from django.core import management
ImportError: No module named django.core
But the error still exists! Please help.
OS:Windows
Installed django using BitNami Django stack.
A:
What happens if you try to import django from the Python shell? Type python at a command prompt, then type import django at the next prompt. I'm not familiar with BitNami, but you might want to consider just installing Django the normal way. Otherwise you're going to have a hard time getting answers to issues via Google. It's not hard to install on Windows. You can get a binary installer for Python, then install Django according to the instructions in the docs.
Bonus points (and not as complicated as it sounds): To make Python package installation fairly painless, you can then install pip (or you can install pip first and then run pip install django). In order to install pip, you'll need setuptools. Once setuptools is installed, you should be able to do easy_install pip, but that's the only time you should ever use easy_install as pip's a much better product.
A:
Make sure you add the location of your django install to your PATH settings. Instant Django might also be an option for you http://www.instantdjango.com/.
| Django startup problems | This is something similar to what's posted here: No Module named django.core
To reiterate, I'm getting this error on running "django-admin.py startproject mysite"(without the double quotes):
C:\Documents and Settings\fixavier\Desktop>django-admin.py startproject mysite
Traceback (most recent call last):
File "C:\Program Files\BitNami DjangoStack\apps\django\django\bin\django-admin.py", line 2, in <module>
from django.core import management
ImportError: No module named django.core
But the error still exists! Please help.
OS:Windows
Installed django using BitNami Django stack.
| [
"What happens if you try to import django from the Python shell? Type python at a command prompt, then type import django at the next prompt. I'm not familiar with BitNami, but you might want to consider just installing Django the normal way. Otherwise you're going to have a hard time getting answers to issues via Google. It's not hard to install on Windows. You can get a binary installer for Python, then install Django according to the instructions in the docs. \nBonus points (and not as complicated as it sounds): To make Python package installation fairly painless, you can then install pip (or you can install pip first and then run pip install django). In order to install pip, you'll need setuptools. Once setuptools is installed, you should be able to do easy_install pip, but that's the only time you should ever use easy_install as pip's a much better product.\n",
"Make sure you add the location of your django install to your PATH settings. Instant Django might also be an option for you http://www.instantdjango.com/.\n"
] | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002877071_django_python.txt |
Q:
Problems with i18n using django translation on App-Engine with Korean and Hindi
I've got a setup based on the post here, and it works perfectly. Adding more languages to the mix, it recognises them fine, except for Korean (ko) and Hindi (hi). Chinese/Japanese/Hebrew are all fine, so nothing to do with encodings/charsets I don't think.
Taking a look into the django code inside the app-engine SDK, I notice that all the languages that I'm using except for ko and hi are ones that ship with django - in the default settings.py and inside the locale folder they are missing. If I copy one of the locale folders inside the /usr/local/google_appengine/lib/django[...]/conf/locale and rename it to be 'ko', then it starts working in my app, but I won't be able to replicate this modification when I deploy to app-engine, so need a bit of help understanding what I might be doing wrong.
my settings.py is definitely being taken into account, as if I remove languages from there then they stop working (as they should). If I copied the django modules into my app, under 'lib' there say, could I use those instead of the ones app-engine tries to use, maybe?
I'm brand new to python/django/app-engine, and developing on a Mac with Leopard, if that makes any difference. I have the latest app-engine SDK as of tuesday.
A:
My guess is you are hitting the 'locale restriction' listed here: http://docs.djangoproject.com/en/dev/topics/i18n/localization/#id1 that since 0.96 didn't have translations for Django in those languages, Django is not letting you translate your app.
I think it is probably easiest to use django 1.1, which does have translations for those languages. You may need to go through other parts of your code to fix any backwards incompatibilities between 0.96 and 1.1.
To use Django 1.1 you can follow the instructions here: http://code.google.com/intl/en-US/appengine/docs/python/tools/libraries.html#Django
which are:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.1')
| Problems with i18n using django translation on App-Engine with Korean and Hindi | I've got a setup based on the post here, and it works perfectly. Adding more languages to the mix, it recognises them fine, except for Korean (ko) and Hindi (hi). Chinese/Japanese/Hebrew are all fine, so nothing to do with encodings/charsets I don't think.
Taking a look into the django code inside the app-engine SDK, I notice that all the languages that I'm using except for ko and hi are ones that ship with django - in the default settings.py and inside the locale folder they are missing. If I copy one of the locale folders inside the /usr/local/google_appengine/lib/django[...]/conf/locale and rename it to be 'ko', then it starts working in my app, but I won't be able to replicate this modification when I deploy to app-engine, so need a bit of help understanding what I might be doing wrong.
my settings.py is definitely being taken into account, as if I remove languages from there then they stop working (as they should). If I copied the django modules into my app, under 'lib' there say, could I use those instead of the ones app-engine tries to use, maybe?
I'm brand new to python/django/app-engine, and developing on a Mac with Leopard, if that makes any difference. I have the latest app-engine SDK as of tuesday.
| [
"My guess is you are hitting the 'locale restriction' listed here: http://docs.djangoproject.com/en/dev/topics/i18n/localization/#id1 that since 0.96 didn't have translations for Django in those languages, Django is not letting you translate your app.\nI think it is probably easiest to use django 1.1, which does have translations for those languages. You may need to go through other parts of your code to fix any backwards incompatibilities between 0.96 and 1.1.\nTo use Django 1.1 you can follow the instructions here: http://code.google.com/intl/en-US/appengine/docs/python/tools/libraries.html#Django\nwhich are: \nimport os\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\nfrom google.appengine.dist import use_library\nuse_library('django', '1.1')\n\n"
] | [
3
] | [] | [] | [
"django",
"google_app_engine",
"internationalization",
"python"
] | stackoverflow_0002876494_django_google_app_engine_internationalization_python.txt |
Q:
Parameters for find function
I'm using beautiful soup (in Python). I have such hidden input object:
<input type="hidden" name="form_build_id" id="form-531f740522f8c290ead9b88f3da026d2" value="form-531f740522f8c290ead9b88f3da026d2" />
I need in id/value.
Here is my code:
mainPageData = cookieOpener.open('http://page.com').read()
soupHandler = BeautifulSoup(mainPageData)
areaId = soupHandler.find('input', name='form_build_id', type='hidden')
TypeError: find() got multiple values for keyword argument 'name'
I tried to change code:
print soupHandler.find(name='form_build_id', type='hidden')
None
What's wrong?
A:
Try using the alternative attrs keyword:
areaId = soupHandler.find('input', attrs={'name':'form_build_id', 'type':'hidden'})
You can't use a keyword argument
called name because the Beautiful Soup
search methods already define a name
argument. You also can't use a Python
reserved word like for as a keyword
argument.
Beautiful Soup provides a special
argument called attrs which you can
use in these situations. attrs is a
dictionary that acts just like the
keyword arguments.
| Parameters for find function | I'm using beautiful soup (in Python). I have such hidden input object:
<input type="hidden" name="form_build_id" id="form-531f740522f8c290ead9b88f3da026d2" value="form-531f740522f8c290ead9b88f3da026d2" />
I need in id/value.
Here is my code:
mainPageData = cookieOpener.open('http://page.com').read()
soupHandler = BeautifulSoup(mainPageData)
areaId = soupHandler.find('input', name='form_build_id', type='hidden')
TypeError: find() got multiple values for keyword argument 'name'
I tried to change code:
print soupHandler.find(name='form_build_id', type='hidden')
None
What's wrong?
| [
"Try using the alternative attrs keyword:\nareaId = soupHandler.find('input', attrs={'name':'form_build_id', 'type':'hidden'})\n\n\nYou can't use a keyword argument\n called name because the Beautiful Soup\n search methods already define a name\n argument. You also can't use a Python\n reserved word like for as a keyword\n argument.\nBeautiful Soup provides a special\n argument called attrs which you can\n use in these situations. attrs is a\n dictionary that acts just like the\n keyword arguments.\n\n"
] | [
35
] | [] | [] | [
"beautifulsoup",
"find",
"python"
] | stackoverflow_0002877114_beautifulsoup_find_python.txt |
Q:
Python, store a dict in a database
What's the best way to store and retrieve a python dict in a database?
A:
If you are not specifically interested into using a traditionally SQL database, such as MySQL, you could look into unstructured document databases where documents naturally map to python dictionaries, for example MongoDB. The MongoDB python bindings allow you to just insert dicts in the DB, and query them based on the values in the dict. See for example the code below:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb=myclient["mydatabase"]
mycol = mydb["customers"]
mydict = { "name": "John", "address": "Highway 37" }
x = mycol.insert_one(mydict)
And to find the entry:
print(mycol.find_one({"name":"John"}))
A:
"Best" is debatable.
If you need a DBMS, sqlite is built in; so it might be considered an easier method than some of the other ways mentioned.
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("create table kv (key text, value integer);")
# <sqlite3.Cursor object at 0x00C62CE0>
d = {'a':1,'b':2}
c.executemany("insert into kv values (?,?);", d.iteritems())
# <sqlite3.Cursor object at 0x00C62CE0>
c.execute("select * from kv;").fetchall()
# [(u'a', 1), (u'b', 2)]
A:
Fairly vague question, depends a lot on the use cases.
Typically you'd just serialize it and insert it wherever it was needed, but if you need the dict itself to be "database-like", then you can use one of many of the available key/value stores for Python
A:
If the dict directly corresponds to a database table, then you should set up a table with a schema containing two columns - key and value. Then for each element of the dict, just insert it into the database, or update it if the key is already in place, etc.
Otherwise you could use pickle to serialize the dict to a string, and then you could just save the string to the DB. But in general I would not recommend this solution since you cannot query the serialized data.
| Python, store a dict in a database | What's the best way to store and retrieve a python dict in a database?
| [
"If you are not specifically interested into using a traditionally SQL database, such as MySQL, you could look into unstructured document databases where documents naturally map to python dictionaries, for example MongoDB. The MongoDB python bindings allow you to just insert dicts in the DB, and query them based on the values in the dict. See for example the code below:\nimport pymongo\nmyclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\nmydb=myclient[\"mydatabase\"]\nmycol = mydb[\"customers\"]\nmydict = { \"name\": \"John\", \"address\": \"Highway 37\" }\nx = mycol.insert_one(mydict)\n\nAnd to find the entry:\nprint(mycol.find_one({\"name\":\"John\"}))\n\n",
"\"Best\" is debatable.\nIf you need a DBMS, sqlite is built in; so it might be considered an easier method than some of the other ways mentioned.\nimport sqlite3\nconn = sqlite3.connect(':memory:')\nc = conn.cursor()\nc.execute(\"create table kv (key text, value integer);\")\n# <sqlite3.Cursor object at 0x00C62CE0>\nd = {'a':1,'b':2}\nc.executemany(\"insert into kv values (?,?);\", d.iteritems())\n# <sqlite3.Cursor object at 0x00C62CE0>\nc.execute(\"select * from kv;\").fetchall()\n# [(u'a', 1), (u'b', 2)]\n\n",
"Fairly vague question, depends a lot on the use cases.\nTypically you'd just serialize it and insert it wherever it was needed, but if you need the dict itself to be \"database-like\", then you can use one of many of the available key/value stores for Python\n",
"If the dict directly corresponds to a database table, then you should set up a table with a schema containing two columns - key and value. Then for each element of the dict, just insert it into the database, or update it if the key is already in place, etc.\nOtherwise you could use pickle to serialize the dict to a string, and then you could just save the string to the DB. But in general I would not recommend this solution since you cannot query the serialized data.\n"
] | [
19,
6,
4,
4
] | [] | [] | [
"dictionary",
"python",
"string"
] | stackoverflow_0002877410_dictionary_python_string.txt |
Q:
What's the best way to use python-syntax config files (in python of course)?
My config file is really just a big python dict, but I have many config files to run different experiments and I want to 'import' a different one based on a command line option. Instinctively I want to do import ConfigFileName where ConfigFileName is a string with the config file's python package name in it... but that doesn't work.
Any ideas?
A:
Use the __import__ builtin function. But like nosklo, I prefer to store it in simpler data format like JSON of INI config file.
A:
Switch to json. It's included with python and makes a better format overall for config files.
A:
You might consider ConfigParser, also included with python. It offers simple sectioned name/value items, default settings, and some substitution capabilities. If that's flexible enough for your needs, it would be a nice alternative.
| What's the best way to use python-syntax config files (in python of course)? | My config file is really just a big python dict, but I have many config files to run different experiments and I want to 'import' a different one based on a command line option. Instinctively I want to do import ConfigFileName where ConfigFileName is a string with the config file's python package name in it... but that doesn't work.
Any ideas?
| [
"Use the __import__ builtin function. But like nosklo, I prefer to store it in simpler data format like JSON of INI config file.\n",
"Switch to json. It's included with python and makes a better format overall for config files.\n",
"You might consider ConfigParser, also included with python. It offers simple sectioned name/value items, default settings, and some substitution capabilities. If that's flexible enough for your needs, it would be a nice alternative.\n"
] | [
5,
1,
1
] | [] | [] | [
"config",
"configuration",
"import",
"python"
] | stackoverflow_0002874431_config_configuration_import_python.txt |
Q:
Marquee style progressbar in wxPython
Could anyone tell me how to implement a marquee style progress bar in wxPython? As stated on MSDN:
you can animate it in a way that shows
activity but does not indicate what
proportion of the task is complete.
Thank you.
alt text http://i.msdn.microsoft.com/dynimg/IC100842.png
I tried this but it doesn't seem to work. The timer ticks but the gauge doesn't scroll. Any help?
import wx
import time
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Timer Tutorial 1",
size=(500,500))
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.update, self.timer)
self.gauProgress = wx.Gauge(panel, range=1000, pos=(30, 50), size=(440, 20))
self.toggleBtn = wx.Button(panel, wx.ID_ANY, "Start")
self.toggleBtn.Bind(wx.EVT_BUTTON, self.onToggle)
def onToggle(self, event):
btnLabel = self.toggleBtn.GetLabel()
if btnLabel == "Start":
print "starting timer..."
self.timer.Start(1000)
self.toggleBtn.SetLabel("Stop")
else:
print "timer stopped!"
self.timer.Stop()
self.toggleBtn.SetLabel("Start")
def update(self, event):
print "\nupdated: ",
print time.ctime()
self.gauProgress.Pulse()
# Run the program
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()
A:
wxGauge has a Pulse() function
gauge.Pulse()
A:
Here is an example:
def loadBallots(self):
self.dirtyBallots = Ballots()
self.dirtyBallots.exceptionQueue = Queue(1)
loadThread = Thread(target=self.dirtyBallots.loadUnknown, args=(self.filename,))
loadThread.start()
# Display a progress dialog
dlg = wx.ProgressDialog(\
"Loading ballots",
"Loading ballots from %s\nNumber of ballots: %d" %
(os.path.basename(self.filename), self.dirtyBallots.numBallots),
parent=self.frame, style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME
)
while loadThread.isAlive():
sleep(0.1)
dlg.Pulse("Loading ballots from %s\nNumber of ballots: %d" %
(os.path.basename(self.filename), self.dirtyBallots.numBallots))
dlg.Destroy()
if not self.dirtyBallots.exceptionQueue.empty():
raise RuntimeError(self.dirtyBallots.exceptionQueue.get())
This is from here.
A:
how about something like this?
class ProgressDialog(wx.Dialog):
def __init__(self, parent, title, to_add=1):
"""Defines a gauge and a timer which updates the gauge."""
wx.Dialog.__init__(self, parent, title=title, style=wx.CAPTION)
self.count = 0
self.to_add = to_add
self.timer = wx.Timer(self)
self.gauge = wx.Gauge(self, range=100, size=(180, 30))
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.gauge, 0, wx.ALL, 10)
self.SetSizer(sizer)
sizer.Fit(self)
self.SetFocus()
self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)
self.timer.Start(30) # or however often you want
def on_timer(self, event):
"""Increases the gauge's progress."""
self.count += self.to_add
if self.count > 100:
self.count = 0
self.gauge.SetValue(self.count)
| Marquee style progressbar in wxPython | Could anyone tell me how to implement a marquee style progress bar in wxPython? As stated on MSDN:
you can animate it in a way that shows
activity but does not indicate what
proportion of the task is complete.
Thank you.
alt text http://i.msdn.microsoft.com/dynimg/IC100842.png
I tried this but it doesn't seem to work. The timer ticks but the gauge doesn't scroll. Any help?
import wx
import time
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Timer Tutorial 1",
size=(500,500))
# Add a panel so it looks the correct on all platforms
panel = wx.Panel(self, wx.ID_ANY)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.update, self.timer)
self.gauProgress = wx.Gauge(panel, range=1000, pos=(30, 50), size=(440, 20))
self.toggleBtn = wx.Button(panel, wx.ID_ANY, "Start")
self.toggleBtn.Bind(wx.EVT_BUTTON, self.onToggle)
def onToggle(self, event):
btnLabel = self.toggleBtn.GetLabel()
if btnLabel == "Start":
print "starting timer..."
self.timer.Start(1000)
self.toggleBtn.SetLabel("Stop")
else:
print "timer stopped!"
self.timer.Stop()
self.toggleBtn.SetLabel("Start")
def update(self, event):
print "\nupdated: ",
print time.ctime()
self.gauProgress.Pulse()
# Run the program
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()
| [
"wxGauge has a Pulse() function\ngauge.Pulse()\n\n",
"Here is an example:\n def loadBallots(self):\n self.dirtyBallots = Ballots()\n self.dirtyBallots.exceptionQueue = Queue(1)\n loadThread = Thread(target=self.dirtyBallots.loadUnknown, args=(self.filename,))\n loadThread.start()\n\n # Display a progress dialog\n dlg = wx.ProgressDialog(\\\n \"Loading ballots\",\n \"Loading ballots from %s\\nNumber of ballots: %d\" % \n (os.path.basename(self.filename), self.dirtyBallots.numBallots),\n parent=self.frame, style = wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME\n )\n while loadThread.isAlive():\n sleep(0.1)\n dlg.Pulse(\"Loading ballots from %s\\nNumber of ballots: %d\" %\n (os.path.basename(self.filename), self.dirtyBallots.numBallots))\n dlg.Destroy()\n\n if not self.dirtyBallots.exceptionQueue.empty():\n raise RuntimeError(self.dirtyBallots.exceptionQueue.get())\n\nThis is from here.\n",
"how about something like this?\nclass ProgressDialog(wx.Dialog):\n\n def __init__(self, parent, title, to_add=1):\n \"\"\"Defines a gauge and a timer which updates the gauge.\"\"\"\n wx.Dialog.__init__(self, parent, title=title, style=wx.CAPTION)\n self.count = 0\n self.to_add = to_add\n self.timer = wx.Timer(self)\n self.gauge = wx.Gauge(self, range=100, size=(180, 30))\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(self.gauge, 0, wx.ALL, 10)\n self.SetSizer(sizer)\n sizer.Fit(self)\n self.SetFocus()\n\n self.Bind(wx.EVT_TIMER, self.on_timer, self.timer)\n self.timer.Start(30) # or however often you want\n\n\n def on_timer(self, event):\n \"\"\"Increases the gauge's progress.\"\"\"\n self.count += self.to_add\n if self.count > 100:\n self.count = 0\n self.gauge.SetValue(self.count)\n\n"
] | [
1,
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002856382_python_wxpython.txt |
Q:
Django Form inheritance problem
Why can't I do this?
from django import forms
from django.forms import widgets
class UserProfileConfig(forms.Form):
def __init__(self,*args,**kwargs):
super (UserProfileConfig,self).__init__(*args,**kwargs)
self.tester = 'asdf'
username = forms.CharField(label='Username',max_length=100,initial=self.tester)
More specifically, why cant the forms.CharField grab the variable tester that I set during construction?
I feel like I am missing something about the way Python handles this sort of thing...
edit :
What I am actually trying to do is this:
class UserProfileConfig(forms.Form):
def __init__(self,request,*args,**kwargs):
super (UserProfileConfig,self).__init__(*args,**kwargs)
self.tester = request.session['some_var']
username = forms.CharField(label='Username',max_length=100,initial=self.tester)
In other words, I need to grab a session variable and then set it to an initial value...
Is there any way to handle this through the __init__ or otherwise?
A:
What you've got doesn't work because your CharField gets created, and pointed to by UserProfileConfig.username when the class is created, not when the instance is created. self.tester doesn't exist until you call __init__ at instance creation time.
A:
You can just do it this way
from django import forms
from django.forms import widgets
class UserProfileConfig(forms.Form):
username = forms.CharField(label='Username',max_length=100,initial=self.tester)
tester = 'asdf'
A:
You could do this:-
class UserProfileConfig(forms.Form):
username = forms.CharField(label='Username',max_length=100)
def view(request):
user_form = UserProfileConfig(initial={'username': request.session['username',})
Which is the generally accepted method, but you can also do this:-
class UserProfileConfig(forms.Form):
def __init__(self,request,*args,**kwargs):
super (UserProfileConfig,self).__init__(*args,**kwargs)
self.fields['username'] = request.session['some_var']
username = forms.CharField(label='Username',max_length=100)
def view(request):
user_form = UserProfileConfig(request=request)
| Django Form inheritance problem | Why can't I do this?
from django import forms
from django.forms import widgets
class UserProfileConfig(forms.Form):
def __init__(self,*args,**kwargs):
super (UserProfileConfig,self).__init__(*args,**kwargs)
self.tester = 'asdf'
username = forms.CharField(label='Username',max_length=100,initial=self.tester)
More specifically, why cant the forms.CharField grab the variable tester that I set during construction?
I feel like I am missing something about the way Python handles this sort of thing...
edit :
What I am actually trying to do is this:
class UserProfileConfig(forms.Form):
def __init__(self,request,*args,**kwargs):
super (UserProfileConfig,self).__init__(*args,**kwargs)
self.tester = request.session['some_var']
username = forms.CharField(label='Username',max_length=100,initial=self.tester)
In other words, I need to grab a session variable and then set it to an initial value...
Is there any way to handle this through the __init__ or otherwise?
| [
"What you've got doesn't work because your CharField gets created, and pointed to by UserProfileConfig.username when the class is created, not when the instance is created. self.tester doesn't exist until you call __init__ at instance creation time.\n",
"You can just do it this way\nfrom django import forms\nfrom django.forms import widgets\nclass UserProfileConfig(forms.Form):\n username = forms.CharField(label='Username',max_length=100,initial=self.tester)\n tester = 'asdf'\n\n",
"You could do this:-\nclass UserProfileConfig(forms.Form):\n\n username = forms.CharField(label='Username',max_length=100)\n\n\ndef view(request):\n user_form = UserProfileConfig(initial={'username': request.session['username',})\n\nWhich is the generally accepted method, but you can also do this:-\nclass UserProfileConfig(forms.Form):\n\n def __init__(self,request,*args,**kwargs):\n super (UserProfileConfig,self).__init__(*args,**kwargs)\n self.fields['username'] = request.session['some_var']\n\n\n username = forms.CharField(label='Username',max_length=100)\n\n\ndef view(request):\n user_form = UserProfileConfig(request=request)\n\n"
] | [
2,
1,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0002373348_django_django_forms_python.txt |
Q:
wxpython Prevent Ctrl+Enter from changing the focus
I have two wxListCtrl and want to process the Ctrl+Enter keyboard event without letting wx change the focus to the other ListCtrl.
I have event handlers for wx.EVT_KEY_DOWN, wx.EVT_KEY_UP, wx.EVT_CHAR and KillFocus, but KillFocus is always called first, then the focus changes and the the keyboard handlers are called for the wrong ListCtrl.
Is there a way to prevent wx from changing the focus, when Ctrl+Enter is pressed ?
A:
No idea if this will work, but who knows!
ac = [(wx.ACCEL_CTRL, wx.WXK_RETURN, wx.NewId())]
tbl = wx.AcceleratorTable(ac)
list.SetAcceleratorTable(tbl) # should overwrite its bindings?
or also try EVT_CHAR_HOOK
| wxpython Prevent Ctrl+Enter from changing the focus | I have two wxListCtrl and want to process the Ctrl+Enter keyboard event without letting wx change the focus to the other ListCtrl.
I have event handlers for wx.EVT_KEY_DOWN, wx.EVT_KEY_UP, wx.EVT_CHAR and KillFocus, but KillFocus is always called first, then the focus changes and the the keyboard handlers are called for the wrong ListCtrl.
Is there a way to prevent wx from changing the focus, when Ctrl+Enter is pressed ?
| [
"No idea if this will work, but who knows! \n ac = [(wx.ACCEL_CTRL, wx.WXK_RETURN, wx.NewId())]\n tbl = wx.AcceleratorTable(ac)\n list.SetAcceleratorTable(tbl) # should overwrite its bindings?\n\nor also try EVT_CHAR_HOOK\n"
] | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0002783397_python_wxpython.txt |
Q:
Referring to objects inside a list without using references or indices
I'm using python for my shopping cart class which has a list of items. When a customer wants to edit an item, I need to pass the JavaScript front-end some way to refer to the item so that it can call AJAX methods to manipulate it.
Basically, I need a simple way to point to a particular item that isn't its index, and isn't a reference to the object itself.
I can't use an index, because another item in the list might be added or removed while the identifier is "held" by the front end. If I were to pass the index forward, if an item got deleted from the list then that index wouldn't point to the right object.
One solution seems to be to use UUIDs, but that seems particularly heavyweight for a very small list. What's the simplest/best way to do this?
A:
Instead of using a list, why not use a dictionary and use small integers as the keys? Adding and removing items from the dictionary will not change the indices into the dictionary. You will want to keep one value in the dictionary that lets you know what the next assigned index will be.
A:
A UUID seems perfect for this. Why don't you want to do that?
Do the items have any sort of product_id? Can the shopping cart have more than one of the same product_id, or does it store a quantity? What I'm getting at is: If product_id's in the cart are unique, you can just use that.
| Referring to objects inside a list without using references or indices | I'm using python for my shopping cart class which has a list of items. When a customer wants to edit an item, I need to pass the JavaScript front-end some way to refer to the item so that it can call AJAX methods to manipulate it.
Basically, I need a simple way to point to a particular item that isn't its index, and isn't a reference to the object itself.
I can't use an index, because another item in the list might be added or removed while the identifier is "held" by the front end. If I were to pass the index forward, if an item got deleted from the list then that index wouldn't point to the right object.
One solution seems to be to use UUIDs, but that seems particularly heavyweight for a very small list. What's the simplest/best way to do this?
| [
"Instead of using a list, why not use a dictionary and use small integers as the keys? Adding and removing items from the dictionary will not change the indices into the dictionary. You will want to keep one value in the dictionary that lets you know what the next assigned index will be.\n",
"A UUID seems perfect for this. Why don't you want to do that?\nDo the items have any sort of product_id? Can the shopping cart have more than one of the same product_id, or does it store a quantity? What I'm getting at is: If product_id's in the cart are unique, you can just use that.\n"
] | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0002877617_python.txt |
Q:
New to PyDev, question about auto completion
I installed Eclipse and PyDev and I'm wondering if I have to setup anything else?
The reason I'm asking is that I'm finding the auto complete isn't working in certain cases. For example, if I have a variable a_string, I'd like to see a list of available methods once I type "a_string." or if I have an array I'd like to see what methods it has. But neither one works atm.
Right now I can see methods from imported packages though.
A:
It should work out of the box (given you configured your python interpreter path properly).
However, keep in mind that since Python is duck-typed you will not necessarily get the full auto-complete set you would expect from strongly-typed languages such as Java. Having said that, PyDev does do a good job with detecting easy scenarios to auto-complete, such as:
list = [1,2,3]
list. # auto-complete will recognize list is a list
Additionally, check out this question for some more info.
| New to PyDev, question about auto completion | I installed Eclipse and PyDev and I'm wondering if I have to setup anything else?
The reason I'm asking is that I'm finding the auto complete isn't working in certain cases. For example, if I have a variable a_string, I'd like to see a list of available methods once I type "a_string." or if I have an array I'd like to see what methods it has. But neither one works atm.
Right now I can see methods from imported packages though.
| [
"It should work out of the box (given you configured your python interpreter path properly).\nHowever, keep in mind that since Python is duck-typed you will not necessarily get the full auto-complete set you would expect from strongly-typed languages such as Java. Having said that, PyDev does do a good job with detecting easy scenarios to auto-complete, such as:\nlist = [1,2,3]\nlist. # auto-complete will recognize list is a list\n\nAdditionally, check out this question for some more info.\n"
] | [
2
] | [] | [] | [
"code_completion",
"pydev",
"python"
] | stackoverflow_0002877872_code_completion_pydev_python.txt |
Q:
Is there a better way to write this URL Manipulation in Python?
I'm curious if there's a simpler way to remove a particular parameter from a url. What I came up with is the following. This seems a bit verbose. Libraries to use or a more pythonic version appreciated.
parsed = urlparse(url)
if parsed.query != "":
params = dict([s.split("=") for s in parsed.query.split("&")])
if params.get("page"):
del params["page"]
url = urlunparse((parsed.scheme,
None,
parsed.path,
None,
urlencode(params.items()),
parsed.fragment,))
parsed = urlparse(url)
A:
Use urlparse.parse_qsl() to crack the query string. You can filter this in one go:
params = [(k,v) for (k,v) in parse_qsl(parsed.query) if k != 'page']
A:
I've created a small helper class to represent a url in a structured way:
import cgi, urllib, urlparse
class Url(object):
def __init__(self, url):
"""Construct from a string."""
self.scheme, self.netloc, self.path, self.params, self.query, self.fragment = urlparse.urlparse(url)
self.args = dict(cgi.parse_qsl(self.query))
def __str__(self):
"""Turn back into a URL."""
self.query = urllib.urlencode(self.args)
return urlparse.urlunparse((self.scheme, self.netloc, self.path, self.params, self.query, self.fragment))
Then you can do:
u = Url(url)
del u.args['page']
url = str(u)
More about this: Web development peeve.
| Is there a better way to write this URL Manipulation in Python? | I'm curious if there's a simpler way to remove a particular parameter from a url. What I came up with is the following. This seems a bit verbose. Libraries to use or a more pythonic version appreciated.
parsed = urlparse(url)
if parsed.query != "":
params = dict([s.split("=") for s in parsed.query.split("&")])
if params.get("page"):
del params["page"]
url = urlunparse((parsed.scheme,
None,
parsed.path,
None,
urlencode(params.items()),
parsed.fragment,))
parsed = urlparse(url)
| [
"Use urlparse.parse_qsl() to crack the query string. You can filter this in one go:\nparams = [(k,v) for (k,v) in parse_qsl(parsed.query) if k != 'page']\n\n",
"I've created a small helper class to represent a url in a structured way:\nimport cgi, urllib, urlparse\n\nclass Url(object):\n def __init__(self, url):\n \"\"\"Construct from a string.\"\"\"\n self.scheme, self.netloc, self.path, self.params, self.query, self.fragment = urlparse.urlparse(url)\n self.args = dict(cgi.parse_qsl(self.query))\n\n def __str__(self):\n \"\"\"Turn back into a URL.\"\"\"\n self.query = urllib.urlencode(self.args)\n return urlparse.urlunparse((self.scheme, self.netloc, self.path, self.params, self.query, self.fragment))\n\nThen you can do:\nu = Url(url)\ndel u.args['page']\nurl = str(u)\n\nMore about this: Web development peeve.\n"
] | [
11,
9
] | [] | [] | [
"parsing",
"python",
"url"
] | stackoverflow_0002873438_parsing_python_url.txt |
Q:
Sort a list of dicts by dict values
I have a list of dictionaries:
[{'title':'New York Times', 'title_url':'New_York_Times','id':4},
{'title':'USA Today','title_url':'USA_Today','id':6},
{'title':'Apple News','title_url':'Apple_News','id':2}]
I'd like to sort it by the title, so elements with A go before Z:
[{'title':'Apple News','title_url':'Apple_News','id':2},
{'title':'New York Times', 'title_url':'New_York_Times','id':4},
{'title':'USA Today','title_url':'USA_Today','id':6}]
What's the best way to do this?
Also, is there a way to ensure the order of each dictionary key stays constant, e.g., always title, title_url, then id?
A:
l.sort(key=lambda x:x['title'])
To sort with multiple keys, assuming all in ascending order:
l.sort(key=lambda x:(x['title'], x['title_url'], x['id']))
A:
The hypoallergenic alternative for those who sneeze when approached by lambdas:
import operator
L.sort(key=operator.itemgetter('title','title_url','id'))
A:
Call .sort(fn) on the list, where fn is a function which compares the title values and returns the result of the comparison.
mylist.sort(lambda x,y: cmp(x['title'], y['title']))
In later versions of Python, though (2.4+), it's much better to just use a sort key:
mylist.sort(key=lambda x:x['title'])
Also, dictionaries are guaranteed to keep their order, were you to iterate through keys/values, as long as there are no more additions/removals. If you add or remove items, though, all bets are off, there's no guarantee for that.
| Sort a list of dicts by dict values | I have a list of dictionaries:
[{'title':'New York Times', 'title_url':'New_York_Times','id':4},
{'title':'USA Today','title_url':'USA_Today','id':6},
{'title':'Apple News','title_url':'Apple_News','id':2}]
I'd like to sort it by the title, so elements with A go before Z:
[{'title':'Apple News','title_url':'Apple_News','id':2},
{'title':'New York Times', 'title_url':'New_York_Times','id':4},
{'title':'USA Today','title_url':'USA_Today','id':6}]
What's the best way to do this?
Also, is there a way to ensure the order of each dictionary key stays constant, e.g., always title, title_url, then id?
| [
"l.sort(key=lambda x:x['title'])\n\nTo sort with multiple keys, assuming all in ascending order:\nl.sort(key=lambda x:(x['title'], x['title_url'], x['id']))\n\n",
"The hypoallergenic alternative for those who sneeze when approached by lambdas:\nimport operator\nL.sort(key=operator.itemgetter('title','title_url','id'))\n\n",
"Call .sort(fn) on the list, where fn is a function which compares the title values and returns the result of the comparison.\nmylist.sort(lambda x,y: cmp(x['title'], y['title']))\n\nIn later versions of Python, though (2.4+), it's much better to just use a sort key:\nmylist.sort(key=lambda x:x['title'])\n\nAlso, dictionaries are guaranteed to keep their order, were you to iterate through keys/values, as long as there are no more additions/removals. If you add or remove items, though, all bets are off, there's no guarantee for that.\n"
] | [
20,
19,
2
] | [
"originalList.sort(lambda d1, d2: cmp(d1['title'], d2['title']))\n\nThough this only sorts on title and order after that is undefined. Doing multiple levels would be painful this way.\n"
] | [
-1
] | [
"dictionary",
"python",
"sorting"
] | stackoverflow_0002878084_dictionary_python_sorting.txt |
Q:
Making REST calls only available to local applications?
Suppose I have a url like:
http://example.com/get-users
which returns a JSON object of all users. But, I don't want anyone (or any bots) to be able to go to this url to fetch this information. I want it to only respond to calls from other local modules in the same website.
How would I go about implementing someting like this?
A:
Compare the REMOTE_ADDR against a white list of approved IPs. If it's not in that list, simply return nothing, close the socket, or return an HTTP error.
| Making REST calls only available to local applications? | Suppose I have a url like:
http://example.com/get-users
which returns a JSON object of all users. But, I don't want anyone (or any bots) to be able to go to this url to fetch this information. I want it to only respond to calls from other local modules in the same website.
How would I go about implementing someting like this?
| [
"Compare the REMOTE_ADDR against a white list of approved IPs. If it's not in that list, simply return nothing, close the socket, or return an HTTP error.\n"
] | [
1
] | [
"Are you using Spring? Have considered adding a filter bean inside your context to only allow HTTP requests from your site?\n"
] | [
-1
] | [
"django",
"django_piston",
"python",
"rest"
] | stackoverflow_0002878245_django_django_piston_python_rest.txt |
Q:
Python timezone issue?
im having troubles with parsing a feed and getting the time. i am using dateutil.parser
from dateutil.parser import parse
print updated, parse(updated ), parse( updated ).utcoffset()
this should be a time in cali, output
2010-05-20T11:00:00.000-07:00 2010-05-20 11:00:00.000000-07:00 -1 day, 17:00:00
why is the offset -1 day 17 hours?
this is causing me issues when i try to do things with it
A:
"Minus 7 hours" is equal to "minus 1 day, plus 17 hours". So probably the time zone offset is correct and just displayed in a weird way.
| Python timezone issue? | im having troubles with parsing a feed and getting the time. i am using dateutil.parser
from dateutil.parser import parse
print updated, parse(updated ), parse( updated ).utcoffset()
this should be a time in cali, output
2010-05-20T11:00:00.000-07:00 2010-05-20 11:00:00.000000-07:00 -1 day, 17:00:00
why is the offset -1 day 17 hours?
this is causing me issues when i try to do things with it
| [
"\"Minus 7 hours\" is equal to \"minus 1 day, plus 17 hours\". So probably the time zone offset is correct and just displayed in a weird way.\n"
] | [
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0002878400_datetime_python.txt |
Q:
ungetc in Python
Some file read (readlines()) functions in Python
copy the file contents to memory (as a list)
I need to process a file that's too large to
be copied in memory and as such need to use
a file pointer (to access the file one byte
at a time) -- as in C getc().
The additional requirement I have is that
I'd like to rewind the file pointer to previous
bytes like in C ungetc().
Is there a way to do this in Python?
Also, in Python, I can read one line at a
time with readline()
Is there a way to read the previous line
going backward?
A:
You do not need file pointers, which Python does not have or want.
To go through a file line by line without reading the whole thing into memory, just iterate over the file object itself, i.e.
with open(filename, "r") as f:
for line in f:
...
Using readlines is generally to be avoided.
Going back a line isn't something you can do super-easily. If you never need to go back more than one line, check out the pairwise recipe in the itertools documentation.
A:
OK, here's what I came up with. Thanks Brenda for the idea of building a class.
Thanks Josh for the idea to use C like functions seek() and read()
#!/bin/python
# Usage: BufRead.py inputfile
import sys, os, string
from inspect import currentframe
# Debug function usage
#
# if DEBUG:
# debugLogMsg(currentframe().f_lineno,currentframe().f_code.co_filename)
# print ...
def debugLogMsg(line,file,msg=""):
print "%s:%s %s" % (file,line,msg)
# Set DEBUG off.
DEBUG = 0
class BufRead:
def __init__(self,filename):
self.__filename = filename
self.__file = open(self.__filename,'rb')
self.__fileposition = self.__file.tell()
self.__file.seek(0, os.SEEK_END)
self.__filesize = self.__file.tell()
self.__file.seek(self.__fileposition, os.SEEK_SET)
def close(self):
if self.__file is not None:
self.__file.close()
self.__file = None
def seekstart(self):
if self.__file == None:
self.__file.seek(0, os.SEEK_SET)
self.__fileposition = self.__file.tell()
def seekend(self):
if self.__file == None:
self.__file.seek(-1, os.SEEK_END)
self.__fileposition = self.__file.tell()
def getc(self):
if self.__file == None:
return None
self.__fileposition = self.__file.tell()
if self.__fileposition < self.__filesize:
byte = self.__file.read(1)
self.__fileposition = self.__file.tell()
return byte
else:
return None
def ungetc(self):
if self.__file == None:
return None
self.__fileposition = self.__file.tell()
if self.__fileposition > 0:
self.__fileposition = self.__fileposition - 1
self.__file.seek(self.__fileposition, os.SEEK_SET)
byte = self.__file.read(1)
self.__file.seek(self.__fileposition, os.SEEK_SET)
return byte
else:
return None
# uses getc() and ungetc()
def getline(self):
if self.__file == None:
return None
self.__fileposition = self.__file.tell()
if self.__fileposition < self.__filesize:
startOfLine = False
line = ""
while True:
if self.__fileposition == 0:
startOfLine = True
break
else:
c = self.ungetc()
if c == '\n':
c = self.getc()
startOfLine = True
break
if startOfLine:
c = self.getc()
if c == '\n':
return '\n'
else:
self.ungetc()
while True:
c = self.getc()
if c == '\n':
line += c
c = self.getc()
if c == None:
return line
if c == '\n':
self.ungetc()
return line
elif c == None:
return line
else:
line += c
else:
return None
# uses getc() and ungetc()
def ungetline(self):
if self.__file == None:
return None
self.__fileposition = self.__file.tell()
if self.__fileposition > 0:
endOfLine = False
line = ""
while True:
if self.__fileposition == self.__filesize:
endOfLine = True
break
else:
c = self.getc()
if c == '\n':
c = self.ungetc()
endOfLine = True
break
if endOfLine:
c = self.ungetc()
if c == '\n':
return '\n'
else:
self.getc()
while True:
c = self.ungetc()
if c == None:
return line
if c == '\n':
line += c
c = self.ungetc()
if c == None:
return line
if c == '\n':
self.getc()
return line
elif c == None:
return line
else:
line = c + line
else:
return None
def main():
if len(sys.argv) == 2:
print sys.argv[1]
b = BufRead(sys.argv[1])
sys.stdout.write(
'----------------------------------\n' \
'- TESTING GETC \n' \
'----------------------------------\n')
while True:
c = b.getc()
if c == None:
sys.stdout.write('\n')
break
else:
sys.stdout.write(c)
sys.stdout.write(
'----------------------------------\n' \
'- TESTING UNGETC \n' \
'----------------------------------\n')
while True:
c = b.ungetc()
if c == None:
sys.stdout.write('\n')
break
else:
sys.stdout.write(c)
sys.stdout.write(
'----------------------------------\n' \
'- TESTING GETLINE \n' \
'----------------------------------\n')
b.seekstart()
while True:
line = b.getline()
if line == None:
sys.stdout.write('\n')
break
else:
sys.stdout.write(line)
sys.stdout.write(
'----------------------------------\n' \
'- TESTING UNGETLINE \n' \
'----------------------------------\n')
b.seekend()
while True:
line = b.ungetline()
if line == None:
sys.stdout.write('\n')
break
else:
sys.stdout.write(line)
b.close()
if __name__=="__main__": main()
A:
If you do want to use a file pointer directly (I think Mike Graham's suggestion is better though), you can use the file object's seek() method which lets you set the internal pointer, combined with the read() method, which support an option argument specifying how many bytes you'd like to read.
A:
Write a class the reads and buffers input for you, and implement ungetc on it -- something like this perhaps (warning: untested, written while compiling):
class BufRead:
def __init__(self,filename):
self.filename = filename
self.fn = open(filename,'rb')
self.buffer = []
self.bufsize = 256
self.ready = True
def close(self):
if self.fn is not None:
self.fn.close()
self.fn = None
self.ready = False
def read(self,size=1):
l = len(self.buffer)
if not self.ready: return None
if l <= size:
s = self.buffer[:size]
self.buffer = self.buffer[size:]
return s
s = self.buffer
size = size - l
self.buffer = self.fn.read(min(self.bufsize,size))
if self.buffer is None or len(self.buffer) == 0:
self.ready = False
return s
return s + self.read(size)
def ungetc(self,ch):
if self.buffer is None:
self.buffer = [ch]
else:
self.buffer.append(ch)
self.ready = True
A:
I don't want to do billions of unbuffered single char file reads plus I wanted a way
to debug the position of the file pointer. Hence, I resolved to return the file position
in addition to a char or line and to use mmap to map the file to memory. (and let mmap
handle paging) I think this will be a bit of a problem if the file is really, really big.
(as in larger than the amount of physical memory) That's when mmap would start going into
the virtual memory and things could get really slow. For now, it processes a 50 MB file in about 4 min.
import sys, os, string, re, time
from mmap import mmap
class StreamReaderDb:
def __init__(self,stream):
self.__stream = mmap(stream.fileno(), os.path.getsize(stream.name))
self.__streamPosition = self.__stream.tell()
self.__stream.seek(0 , os.SEEK_END)
self.__streamSize = self.__stream.tell()
self.__stream.seek(self.__streamPosition, os.SEEK_SET)
def setStreamPositionDb(self,streamPosition):
if self.__stream == None:
return None
self.__streamPosition = streamPosition
self.__stream.seek(self.__streamPosition, os.SEEK_SET)
def streamPositionDb(self):
if self.__stream == None:
return None
return self.__streamPosition
def streamSize(self):
if self.__stream == None:
return None
return self.__streamSize
def close(self):
if self.__stream is not None:
self.__stream.close()
self.__stream = None
def seekStart(self):
if self.__stream == None:
return None
self.setStreamPositionDb(0)
def seekEnd(self):
if self.__stream == None:
return None
self.__stream.seek(-1, os.SEEK_END)
self.setStreamPositionDb(self.__stream.tell())
def getcDb(self):
if self.__stream == None:
return None,None
self.setStreamPositionDb(self.__stream.tell())
if self.streamPositionDb() < self.streamSize():
byte = self.__stream.read(1)
self.setStreamPositionDb(self.__stream.tell())
return byte,self.streamPositionDb()
else:
return None,self.streamPositionDb()
def unGetcDb(self):
if self.__stream == None:
return None,None
self.setStreamPositionDb(self.__stream.tell())
if self.streamPositionDb() > 0:
self.setStreamPositionDb(self.streamPositionDb() - 1)
byte = self.__stream.read(1)
self.__stream.seek(self.streamPositionDb(), os.SEEK_SET)
return byte,self.streamPositionDb()
else:
return None,self.streamPositionDb()
def seekLineStartDb(self):
if self.__stream == None:
return None
self.setStreamPositionDb(self.__stream.tell())
if self.streamPositionDb() < self.streamSize():
# Back up to the start of the line
while True:
if self.streamPositionDb() == 0:
return self.streamPositionDb()
else:
c,fp = self.unGetcDb()
if c == '\n':
c,fp = self.getcDb()
return fp
else:
return None
def seekPrevLineEndDb(self):
if self.__stream == None:
return None
self.setStreamPositionDb(self.__stream.tell())
if self.streamPositionDb() < self.streamSize():
# Back up to the start of the line
while True:
if self.streamPositionDb() == 0:
return self.streamPositionDb()
else:
c,fp = self.unGetcDb()
if c == '\n':
return fp
else:
return None
def seekPrevLineStartDb(self):
if self.__stream == None:
return None
self.setStreamPositionDb(self.__stream.tell())
if self.streamPositionDb() < self.streamSize():
# Back up to the start of the line
while True:
if self.streamPositionDb() == 0:
return self.streamPositionDb()
else:
c,fp = self.unGetcDb()
if c == '\n':
return self.seekLineStartDb()
else:
return None
def seekLineEndDb(self):
if self.__stream == None:
return None
self.setStreamPositionDb(self.__stream.tell())
if self.streamPositionDb() > 0:
while True:
if self.streamPositionDb() == self.streamSize():
return self.streamPositionDb()
else:
c,fp = self.getcDb()
if c == '\n':
c,fp = self.unGetcDb()
return fp
else:
return None
def seekNextLineEndDb(self):
if self.__stream == None:
return None
self.setStreamPositionDb(self.__stream.tell())
if self.streamPositionDb() > 0:
while True:
if self.streamPositionDb() == self.streamSize():
return self.streamPositionDb()
else:
c,fp = self.getcDb()
if c == '\n':
return fp
else:
return None
def seekNextLineStartDb(self):
if self.__stream == None:
return None
self.setStreamPositionDb(self.__stream.tell())
if self.streamPositionDb() > 0:
while True:
if self.streamPositionDb() == self.streamSize():
return self.streamPositionDb()
else:
c,fp = self.getcDb()
if c == '\n':
return self.seekLineStartDb()
else:
return None
# uses getc() and ungetc()
def getLineDb(self):
if self.__stream == None:
return None,None
self.setStreamPositionDb(self.__stream.tell())
line = ""
if self.seekLineStartDb() != None:
c,fp = self.getcDb()
if c == '\n':
return c,self.streamPositionDb()
else:
self.unGetcDb()
while True:
c,fp = self.getcDb()
if c == '\n':
line += c
c,fp = self.getcDb()
if c == None:
return line,self.streamPositionDb()
self.unGetcDb()
return line,self.streamPositionDb()
elif c == None:
return line,self.streamPositionDb()
else:
line += c
else:
return None,self.streamPositionDb()
# uses getc() and ungetc()
def unGetLineDb(self):
if self.__stream == None:
return None,None
self.setStreamPositionDb(self.__stream.tell())
line = ""
if self.seekLineEndDb() != None:
c,fp = self.unGetcDb()
if c == '\n':
return c,self.streamPositionDb()
else:
self.getcDb()
while True:
c,fp = self.unGetcDb()
if c == None:
return line,self.streamPositionDb()
if c == '\n':
line += c
c,fp = self.unGetcDb()
if c == None:
return line,self.streamPositionDb()
self.getcDb()
return line,self.streamPositionDb()
elif c == None:
return line,self.streamPositionDb()
else:
line = c + line
else:
return None,self.streamPositionDb()
A:
The question was initially prompted by my need to build a lexical analyzer.
getc() and ungetc() are useful at first (to get the read bugs out the way and
to build the state machine) After the state machine is done,
getc() and ungetc() become a liability as they take too long to read
directly from storage.
When the state machine was complete (debugged any IO problems,
finalized the states), I optimized the lexical analyzer.
Reading the source file in chunks (or pages) into memory and running
the state machine on each page yields the best time result.
I found that considerable time is saved if getc() and ungetc() are not used
to read from the file directly.
| ungetc in Python | Some file read (readlines()) functions in Python
copy the file contents to memory (as a list)
I need to process a file that's too large to
be copied in memory and as such need to use
a file pointer (to access the file one byte
at a time) -- as in C getc().
The additional requirement I have is that
I'd like to rewind the file pointer to previous
bytes like in C ungetc().
Is there a way to do this in Python?
Also, in Python, I can read one line at a
time with readline()
Is there a way to read the previous line
going backward?
| [
"\nYou do not need file pointers, which Python does not have or want. \nTo go through a file line by line without reading the whole thing into memory, just iterate over the file object itself, i.e.\n with open(filename, \"r\") as f:\n for line in f:\n ...\n\nUsing readlines is generally to be avoided.\nGoing back a line isn't something you can do super-easily. If you never need to go back more than one line, check out the pairwise recipe in the itertools documentation.\n\n",
"OK, here's what I came up with. Thanks Brenda for the idea of building a class.\nThanks Josh for the idea to use C like functions seek() and read()\n#!/bin/python\n\n# Usage: BufRead.py inputfile\n\nimport sys, os, string\nfrom inspect import currentframe\n\n# Debug function usage\n#\n# if DEBUG:\n# debugLogMsg(currentframe().f_lineno,currentframe().f_code.co_filename)\n# print ...\ndef debugLogMsg(line,file,msg=\"\"):\n print \"%s:%s %s\" % (file,line,msg)\n\n# Set DEBUG off.\nDEBUG = 0\n\nclass BufRead: \n def __init__(self,filename): \n self.__filename = filename \n self.__file = open(self.__filename,'rb') \n self.__fileposition = self.__file.tell()\n self.__file.seek(0, os.SEEK_END)\n self.__filesize = self.__file.tell() \n self.__file.seek(self.__fileposition, os.SEEK_SET) \n\n def close(self): \n if self.__file is not None: \n self.__file.close() \n self.__file = None \n\n def seekstart(self):\n if self.__file == None:\n self.__file.seek(0, os.SEEK_SET)\n self.__fileposition = self.__file.tell()\n\n def seekend(self):\n if self.__file == None:\n self.__file.seek(-1, os.SEEK_END)\n self.__fileposition = self.__file.tell()\n\n def getc(self):\n if self.__file == None:\n return None \n self.__fileposition = self.__file.tell()\n if self.__fileposition < self.__filesize:\n byte = self.__file.read(1)\n self.__fileposition = self.__file.tell()\n return byte\n else:\n return None\n\n def ungetc(self):\n if self.__file == None:\n return None \n self.__fileposition = self.__file.tell()\n if self.__fileposition > 0:\n self.__fileposition = self.__fileposition - 1\n self.__file.seek(self.__fileposition, os.SEEK_SET)\n byte = self.__file.read(1)\n self.__file.seek(self.__fileposition, os.SEEK_SET)\n return byte\n else:\n return None\n\n # uses getc() and ungetc()\n def getline(self):\n if self.__file == None:\n return None \n self.__fileposition = self.__file.tell()\n\n if self.__fileposition < self.__filesize:\n startOfLine = False\n line = \"\"\n\n while True:\n if self.__fileposition == 0:\n startOfLine = True\n break\n else:\n c = self.ungetc()\n if c == '\\n':\n c = self.getc()\n startOfLine = True\n break\n\n if startOfLine:\n c = self.getc()\n if c == '\\n':\n return '\\n'\n else:\n self.ungetc()\n\n while True:\n c = self.getc()\n if c == '\\n':\n line += c\n c = self.getc()\n if c == None:\n return line\n if c == '\\n':\n self.ungetc()\n return line\n elif c == None:\n return line\n else:\n line += c\n else:\n return None\n\n # uses getc() and ungetc()\n def ungetline(self):\n if self.__file == None:\n return None \n self.__fileposition = self.__file.tell()\n\n if self.__fileposition > 0:\n endOfLine = False\n line = \"\"\n\n while True:\n if self.__fileposition == self.__filesize:\n endOfLine = True\n break\n else:\n c = self.getc()\n if c == '\\n':\n c = self.ungetc()\n endOfLine = True\n break\n\n if endOfLine:\n c = self.ungetc()\n if c == '\\n':\n return '\\n'\n else:\n self.getc()\n\n while True:\n c = self.ungetc()\n if c == None:\n return line\n if c == '\\n':\n line += c\n c = self.ungetc()\n if c == None:\n return line\n if c == '\\n':\n self.getc()\n return line\n elif c == None:\n return line\n else:\n line = c + line\n else:\n return None\n\ndef main():\n if len(sys.argv) == 2:\n print sys.argv[1]\n b = BufRead(sys.argv[1])\n\n sys.stdout.write(\n '----------------------------------\\n' \\\n '- TESTING GETC \\n' \\\n '----------------------------------\\n')\n\n while True:\n c = b.getc()\n if c == None: \n sys.stdout.write('\\n')\n break\n else:\n sys.stdout.write(c)\n\n sys.stdout.write(\n '----------------------------------\\n' \\\n '- TESTING UNGETC \\n' \\\n '----------------------------------\\n')\n\n while True:\n c = b.ungetc()\n if c == None: \n sys.stdout.write('\\n')\n break\n else:\n sys.stdout.write(c)\n\n sys.stdout.write(\n '----------------------------------\\n' \\\n '- TESTING GETLINE \\n' \\\n '----------------------------------\\n')\n\n b.seekstart()\n\n while True:\n line = b.getline()\n if line == None:\n sys.stdout.write('\\n')\n break\n else:\n sys.stdout.write(line)\n\n sys.stdout.write(\n '----------------------------------\\n' \\\n '- TESTING UNGETLINE \\n' \\\n '----------------------------------\\n')\n\n b.seekend()\n\n while True:\n line = b.ungetline()\n if line == None:\n sys.stdout.write('\\n')\n break\n else:\n sys.stdout.write(line)\n\n b.close()\n\nif __name__==\"__main__\": main()\n\n",
"If you do want to use a file pointer directly (I think Mike Graham's suggestion is better though), you can use the file object's seek() method which lets you set the internal pointer, combined with the read() method, which support an option argument specifying how many bytes you'd like to read.\n",
"Write a class the reads and buffers input for you, and implement ungetc on it -- something like this perhaps (warning: untested, written while compiling):\nclass BufRead:\n def __init__(self,filename):\n self.filename = filename\n self.fn = open(filename,'rb')\n self.buffer = []\n self.bufsize = 256\n self.ready = True\n def close(self):\n if self.fn is not None:\n self.fn.close()\n self.fn = None\n self.ready = False\n def read(self,size=1):\n l = len(self.buffer)\n if not self.ready: return None\n if l <= size:\n s = self.buffer[:size]\n self.buffer = self.buffer[size:]\n return s\n s = self.buffer\n size = size - l\n self.buffer = self.fn.read(min(self.bufsize,size))\n if self.buffer is None or len(self.buffer) == 0:\n self.ready = False\n return s\n return s + self.read(size)\n def ungetc(self,ch):\n if self.buffer is None:\n self.buffer = [ch]\n else: \n self.buffer.append(ch)\n self.ready = True\n\n",
"I don't want to do billions of unbuffered single char file reads plus I wanted a way\nto debug the position of the file pointer. Hence, I resolved to return the file position\nin addition to a char or line and to use mmap to map the file to memory. (and let mmap\nhandle paging) I think this will be a bit of a problem if the file is really, really big.\n(as in larger than the amount of physical memory) That's when mmap would start going into\nthe virtual memory and things could get really slow. For now, it processes a 50 MB file in about 4 min.\nimport sys, os, string, re, time\nfrom mmap import mmap\n\nclass StreamReaderDb: \n def __init__(self,stream):\n self.__stream = mmap(stream.fileno(), os.path.getsize(stream.name)) \n self.__streamPosition = self.__stream.tell()\n self.__stream.seek(0 , os.SEEK_END)\n self.__streamSize = self.__stream.tell() \n self.__stream.seek(self.__streamPosition, os.SEEK_SET) \n\n def setStreamPositionDb(self,streamPosition):\n if self.__stream == None:\n return None \n self.__streamPosition = streamPosition\n self.__stream.seek(self.__streamPosition, os.SEEK_SET)\n\n def streamPositionDb(self):\n if self.__stream == None:\n return None \n return self.__streamPosition\n\n def streamSize(self):\n if self.__stream == None:\n return None \n return self.__streamSize\n\n def close(self): \n if self.__stream is not None: \n self.__stream.close() \n self.__stream = None \n\n def seekStart(self):\n if self.__stream == None:\n return None \n self.setStreamPositionDb(0)\n\n def seekEnd(self):\n if self.__stream == None:\n return None \n self.__stream.seek(-1, os.SEEK_END)\n self.setStreamPositionDb(self.__stream.tell())\n\n def getcDb(self):\n if self.__stream == None:\n return None,None \n self.setStreamPositionDb(self.__stream.tell())\n if self.streamPositionDb() < self.streamSize():\n byte = self.__stream.read(1)\n self.setStreamPositionDb(self.__stream.tell())\n return byte,self.streamPositionDb()\n else:\n return None,self.streamPositionDb()\n\n def unGetcDb(self):\n if self.__stream == None:\n return None,None \n self.setStreamPositionDb(self.__stream.tell())\n if self.streamPositionDb() > 0:\n self.setStreamPositionDb(self.streamPositionDb() - 1)\n byte = self.__stream.read(1)\n self.__stream.seek(self.streamPositionDb(), os.SEEK_SET)\n return byte,self.streamPositionDb()\n else:\n return None,self.streamPositionDb()\n\n def seekLineStartDb(self):\n if self.__stream == None:\n return None\n self.setStreamPositionDb(self.__stream.tell())\n\n if self.streamPositionDb() < self.streamSize():\n # Back up to the start of the line\n while True:\n if self.streamPositionDb() == 0:\n return self.streamPositionDb() \n else:\n c,fp = self.unGetcDb()\n if c == '\\n':\n c,fp = self.getcDb()\n return fp\n else:\n return None\n\n def seekPrevLineEndDb(self):\n if self.__stream == None:\n return None\n self.setStreamPositionDb(self.__stream.tell())\n\n if self.streamPositionDb() < self.streamSize():\n # Back up to the start of the line\n while True:\n if self.streamPositionDb() == 0:\n return self.streamPositionDb() \n else:\n c,fp = self.unGetcDb()\n if c == '\\n':\n return fp\n else:\n return None\n\n def seekPrevLineStartDb(self):\n if self.__stream == None:\n return None\n self.setStreamPositionDb(self.__stream.tell())\n\n if self.streamPositionDb() < self.streamSize():\n # Back up to the start of the line\n while True:\n if self.streamPositionDb() == 0:\n return self.streamPositionDb() \n else:\n c,fp = self.unGetcDb()\n if c == '\\n':\n return self.seekLineStartDb()\n else:\n return None\n\n def seekLineEndDb(self):\n if self.__stream == None:\n return None \n self.setStreamPositionDb(self.__stream.tell())\n\n if self.streamPositionDb() > 0:\n while True:\n if self.streamPositionDb() == self.streamSize():\n return self.streamPositionDb()\n else:\n c,fp = self.getcDb()\n if c == '\\n':\n c,fp = self.unGetcDb()\n return fp\n else:\n return None\n\n def seekNextLineEndDb(self):\n if self.__stream == None:\n return None \n self.setStreamPositionDb(self.__stream.tell())\n\n if self.streamPositionDb() > 0:\n while True:\n if self.streamPositionDb() == self.streamSize():\n return self.streamPositionDb()\n else:\n c,fp = self.getcDb()\n if c == '\\n':\n return fp\n else:\n return None\n\n def seekNextLineStartDb(self):\n if self.__stream == None:\n return None \n self.setStreamPositionDb(self.__stream.tell())\n\n if self.streamPositionDb() > 0:\n while True:\n if self.streamPositionDb() == self.streamSize():\n return self.streamPositionDb()\n else:\n c,fp = self.getcDb()\n if c == '\\n':\n return self.seekLineStartDb()\n else:\n return None\n\n # uses getc() and ungetc()\n def getLineDb(self):\n if self.__stream == None:\n return None,None \n self.setStreamPositionDb(self.__stream.tell())\n\n line = \"\"\n\n if self.seekLineStartDb() != None:\n c,fp = self.getcDb()\n if c == '\\n':\n return c,self.streamPositionDb()\n else:\n self.unGetcDb()\n\n while True:\n c,fp = self.getcDb()\n if c == '\\n':\n line += c\n c,fp = self.getcDb()\n if c == None:\n return line,self.streamPositionDb()\n self.unGetcDb()\n return line,self.streamPositionDb()\n elif c == None:\n return line,self.streamPositionDb()\n else:\n line += c\n else:\n return None,self.streamPositionDb()\n\n # uses getc() and ungetc()\n def unGetLineDb(self):\n if self.__stream == None:\n return None,None \n self.setStreamPositionDb(self.__stream.tell())\n\n line = \"\"\n\n if self.seekLineEndDb() != None:\n c,fp = self.unGetcDb()\n if c == '\\n':\n return c,self.streamPositionDb()\n else:\n self.getcDb()\n\n while True:\n c,fp = self.unGetcDb()\n if c == None:\n return line,self.streamPositionDb()\n if c == '\\n':\n line += c\n c,fp = self.unGetcDb()\n if c == None:\n return line,self.streamPositionDb()\n self.getcDb()\n return line,self.streamPositionDb()\n elif c == None:\n return line,self.streamPositionDb()\n else:\n line = c + line\n else:\n return None,self.streamPositionDb()\n\n",
"The question was initially prompted by my need to build a lexical analyzer.\ngetc() and ungetc() are useful at first (to get the read bugs out the way and\nto build the state machine) After the state machine is done,\ngetc() and ungetc() become a liability as they take too long to read\ndirectly from storage. \nWhen the state machine was complete (debugged any IO problems,\nfinalized the states), I optimized the lexical analyzer. \nReading the source file in chunks (or pages) into memory and running\nthe state machine on each page yields the best time result.\nI found that considerable time is saved if getc() and ungetc() are not used\nto read from the file directly. \n"
] | [
5,
3,
2,
0,
0,
0
] | [] | [] | [
"python",
"readline",
"readlines",
"ungetc"
] | stackoverflow_0002655643_python_readline_readlines_ungetc.txt |
Q:
How do I include the Django settings file?
I have a .py file in a directory , which is inside the Django project folder.
I have email settings in my settings.py, but this .py file does not import that file.
How can I specify to Django that settings.py should be used , so that I can use EmailMessage class with the settings that are in my settings.py?
A:
from django.conf import settings
should do it!
A:
Depending on how you want to call your python script you can use one of a couple ways to accomplish what you want. The first is purely inside the python file.
from django.core.management import setup_environ
from mysite import settings
setup_environ(settings)
The second way is to setup your environment before calling the script
export DJANGO_SETTINGS_MODULE=yoursite.settings
Then from inside your script call
from django.conf import settings
That should set everything up for you.
A:
you can use
from mysite.settings import VARIABLE_NAME
| How do I include the Django settings file? | I have a .py file in a directory , which is inside the Django project folder.
I have email settings in my settings.py, but this .py file does not import that file.
How can I specify to Django that settings.py should be used , so that I can use EmailMessage class with the settings that are in my settings.py?
| [
"from django.conf import settings\n\nshould do it!\n",
"Depending on how you want to call your python script you can use one of a couple ways to accomplish what you want. The first is purely inside the python file.\nfrom django.core.management import setup_environ\nfrom mysite import settings\n\nsetup_environ(settings)\n\nThe second way is to setup your environment before calling the script\nexport DJANGO_SETTINGS_MODULE=yoursite.settings\n\nThen from inside your script call\nfrom django.conf import settings\n\nThat should set everything up for you.\n",
"you can use\nfrom mysite.settings import VARIABLE_NAME\n\n"
] | [
7,
1,
0
] | [] | [] | [
"django",
"email",
"python",
"settings"
] | stackoverflow_0002869909_django_email_python_settings.txt |
Q:
Replacing backslashes in Python strings
I have some code to encrypt some strings in Python. Encrypted text is used as a parameter in some urls, but after encrypting, there comes backslashes in string and I cannot use single backslash in urllib2.urlopen.
I cannot replace single backslash with double. For example:
print cipherText
'\t3-@\xab7+\xc7\x93H\xdc\xd1\x13G\xe1\xfb'
print cipherText.replace('\\','\\\\')
'\t3-@\xab7+\xc7\x93H\xdc\xd1\x13G\xe1\xfb'
Also putting r in front of \ in replace statement did not worked.
All I want to do is calling that kind of url:
http://awebsite.me/main?param="\t3-@\xab7+\xc7\x93H\xdc\xd1\x13G\xe1\xfb"
And also this url can be successfully called:
http://awebsite.me/main?param="\\t3-@\\xab7+\\xc7\\x93H\\xdc\\xd1\\x13G\\xe1\\xfb"
A:
probably what you are seeing is not a real "backslash character", but it is the string representation of a non printable (or non-ascii) character. For example \t is Tab, not a backslash and t.
You should build your url with
"http://awebsite.me/main?%s" % (urllib.urlencode({'param': cipherText}))
| Replacing backslashes in Python strings | I have some code to encrypt some strings in Python. Encrypted text is used as a parameter in some urls, but after encrypting, there comes backslashes in string and I cannot use single backslash in urllib2.urlopen.
I cannot replace single backslash with double. For example:
print cipherText
'\t3-@\xab7+\xc7\x93H\xdc\xd1\x13G\xe1\xfb'
print cipherText.replace('\\','\\\\')
'\t3-@\xab7+\xc7\x93H\xdc\xd1\x13G\xe1\xfb'
Also putting r in front of \ in replace statement did not worked.
All I want to do is calling that kind of url:
http://awebsite.me/main?param="\t3-@\xab7+\xc7\x93H\xdc\xd1\x13G\xe1\xfb"
And also this url can be successfully called:
http://awebsite.me/main?param="\\t3-@\\xab7+\\xc7\\x93H\\xdc\\xd1\\x13G\\xe1\\xfb"
| [
"probably what you are seeing is not a real \"backslash character\", but it is the string representation of a non printable (or non-ascii) character. For example \\t is Tab, not a backslash and t.\nYou should build your url with\n\"http://awebsite.me/main?%s\" % (urllib.urlencode({'param': cipherText}))\n\n"
] | [
7
] | [] | [] | [
"backslash",
"python",
"replace",
"string"
] | stackoverflow_0002878549_backslash_python_replace_string.txt |
Q:
Python: set a function timeout without using signal or threads?
Is there a way to have a function raise an error if it takes longer than a certain amount of time to return? I want to do this without using signal (because I am not in the main thread) or by spawning more threads, which is cumbersome.
A:
If your function is looping through a lot of things, you could check the elapsed time during each iteration of the loop... but if it's blocked on something for the long period, then you need to have some other thread which can be handling the timing stuff while the thread you're timing is blocked.
| Python: set a function timeout without using signal or threads? | Is there a way to have a function raise an error if it takes longer than a certain amount of time to return? I want to do this without using signal (because I am not in the main thread) or by spawning more threads, which is cumbersome.
| [
"If your function is looping through a lot of things, you could check the elapsed time during each iteration of the loop... but if it's blocked on something for the long period, then you need to have some other thread which can be handling the timing stuff while the thread you're timing is blocked.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0002878474_python.txt |
Q:
Make OS open directory in Python
I am writing a program in Python, and want to get it to make the OS open the current working directory, making for instance Windows open explorer.exe and navigating to the wanted directory. Any ideas on how to do this?
The directory is already given by os.getcwd.
Cross platform methods preferred :)
A:
There is os.startfile, but it's only available under windows:
import os
os.startfile('C:/') # opens explorer at C:\ drive
Here someone (credits to Eric_Dexter@msn.com apparently) posted an alternative for use on unix-like systems, and someone mentions the desktop package available at pypi (but i've never used it). The suggested method:
import os
import subprocess
def startfile(filename):
try:
os.startfile(filename)
except:
subprocess.Popen(['xdg-open', filename])
So to complete the answer, use:
startfile(os.getcwd())
| Make OS open directory in Python | I am writing a program in Python, and want to get it to make the OS open the current working directory, making for instance Windows open explorer.exe and navigating to the wanted directory. Any ideas on how to do this?
The directory is already given by os.getcwd.
Cross platform methods preferred :)
| [
"There is os.startfile, but it's only available under windows:\nimport os\nos.startfile('C:/') # opens explorer at C:\\ drive\n\nHere someone (credits to Eric_Dexter@msn.com apparently) posted an alternative for use on unix-like systems, and someone mentions the desktop package available at pypi (but i've never used it). The suggested method:\nimport os\nimport subprocess\n\ndef startfile(filename):\n try:\n os.startfile(filename)\n except:\n subprocess.Popen(['xdg-open', filename])\n\nSo to complete the answer, use:\nstartfile(os.getcwd())\n\n"
] | [
11
] | [] | [] | [
"python"
] | stackoverflow_0002878712_python.txt |
Q:
In python, a good way to remove a list from a list of dicts
I have a list of dicts:
list = [{'title': u'Politics', 'id': 1L, 'title_url': u'Politics'},
{'id': 3L, 'title_url': u'Test', 'title': u'Test'}]
I'd like to remove the list item with title = 'Test'
What is the best way to do this given that the order of the key/value pairs change?
Thanks.
A:
[i for i in lst if i['title']!= u'Test']
Also, please don't use list as a variable name, it shadows built-in.
A:
mylist = [x for x in mylist if x['title'] != 'Test']
Other solutions are possible, but any solution will be O(n) since you have to search through the whole list for the right element. Given that, go with the simplest approach.
A:
L = [{'title': u'Politics', 'id': 1L, 'title_url': u'Politics'},
{'id': 3L, 'title_url': u'Test', 'title': u'Test'}]
L = [d for d in L if d['title'] != u'Test']
Tips: The items in a dict aren't ordered anyway. Using the name of a built-in function like list as a variable name is a bad idea.
A:
More verbose than the above answers but modify the list in place rather than creating a copy of it (Have no idea which would be faster - copying might be the way to go anyway!)
lst = [{'title': u'Politics', 'id': 1L, 'title_url': u'Politics'},
{'id': 3L, 'title_url': u'Test', 'title': u'Test'}]
for i in xrange(len(lst)-1,0,-1):
if lst[i].get("title")=="Test":
del lst[i]
Modifies the list in place rather than copying it, copes with removing multiple dicts which have "title":"Test" in them and copes if there's no such dict.
Note that .get("title") return None if there's no matching key whereas ["title"] raises an exception.
If you could guarantee there would be just one matching item you could also use (and wanted to modify in place rather than copy)
for i,d in enumerate(lst):
if d.get("title")=="Test":
del lst[i]
break
Probably simplest to stick with
[x for x in lst if x.get("title")!="Test"]
A:
new_lst = filter(lambda x: 'title' in x and x['title']!=u'Test', lst)
| In python, a good way to remove a list from a list of dicts | I have a list of dicts:
list = [{'title': u'Politics', 'id': 1L, 'title_url': u'Politics'},
{'id': 3L, 'title_url': u'Test', 'title': u'Test'}]
I'd like to remove the list item with title = 'Test'
What is the best way to do this given that the order of the key/value pairs change?
Thanks.
| [
"[i for i in lst if i['title']!= u'Test']\n\nAlso, please don't use list as a variable name, it shadows built-in.\n",
"mylist = [x for x in mylist if x['title'] != 'Test']\n\nOther solutions are possible, but any solution will be O(n) since you have to search through the whole list for the right element. Given that, go with the simplest approach.\n",
"L = [{'title': u'Politics', 'id': 1L, 'title_url': u'Politics'}, \n {'id': 3L, 'title_url': u'Test', 'title': u'Test'}]\nL = [d for d in L if d['title'] != u'Test']\n\nTips: The items in a dict aren't ordered anyway. Using the name of a built-in function like list as a variable name is a bad idea.\n",
"More verbose than the above answers but modify the list in place rather than creating a copy of it (Have no idea which would be faster - copying might be the way to go anyway!)\nlst = [{'title': u'Politics', 'id': 1L, 'title_url': u'Politics'}, \n {'id': 3L, 'title_url': u'Test', 'title': u'Test'}] \nfor i in xrange(len(lst)-1,0,-1): \nif lst[i].get(\"title\")==\"Test\": \n del lst[i] \n\nModifies the list in place rather than copying it, copes with removing multiple dicts which have \"title\":\"Test\" in them and copes if there's no such dict.\nNote that .get(\"title\") return None if there's no matching key whereas [\"title\"] raises an exception.\nIf you could guarantee there would be just one matching item you could also use (and wanted to modify in place rather than copy)\nfor i,d in enumerate(lst): \n if d.get(\"title\")==\"Test\": \n del lst[i] \n break \n\nProbably simplest to stick with \n[x for x in lst if x.get(\"title\")!=\"Test\"]\n\n",
"new_lst = filter(lambda x: 'title' in x and x['title']!=u'Test', lst)\n\n"
] | [
6,
4,
3,
3,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0002878230_dictionary_list_python.txt |
Q:
Scalable chat site in python
Hey guys, I have an idea that I'd like to start implementing that at the crux of it, will basically be a chat website, and will need to support multiple rooms. Quite frankly, I'm not too sure where to begin with regards to setting up a very sturdy/scalable chat system in python (or another language if you guys believe it to be a better alternative), so any suggestions that can get me pointed in the right direction will be greatly appreciated.
A:
Look into XMPP. Here's the list of Python libraries.
A:
Google AppEngine supports python provides scalable framework. Probably you'll save lots of time if you use it.
| Scalable chat site in python | Hey guys, I have an idea that I'd like to start implementing that at the crux of it, will basically be a chat website, and will need to support multiple rooms. Quite frankly, I'm not too sure where to begin with regards to setting up a very sturdy/scalable chat system in python (or another language if you guys believe it to be a better alternative), so any suggestions that can get me pointed in the right direction will be greatly appreciated.
| [
"Look into XMPP. Here's the list of Python libraries.\n",
"Google AppEngine supports python provides scalable framework. Probably you'll save lots of time if you use it.\n"
] | [
0,
0
] | [] | [] | [
"chat",
"chatroom",
"python"
] | stackoverflow_0002878081_chat_chatroom_python.txt |
Q:
What's the life-time of a thread-local value in Python?
import threading
mydata = threading.local()
def run():
# When will the garbage collector be able to destroy the object created
# here? After the thread exits from ``run()``? After ``join()`` is called?
# Or will it survive the thread in which it was created, and live until
# ``mydata`` is garbage-collected?
mydata.foo = object()
t = threading.Thread(target=run)
t.start()
t.join()
A:
Here is my answer, since I am failing to see the conclusion in the previous answers.
I started wondering the same thing and tried a test program that is similar to the ones in other answers and my conclusion was that they do get GCed sooner than the end of the program, which means, these references can be determined as garbage once the thread itself dies.
import time
import threading
import gc
data = threading.local()
class Resource(object):
def __init__(self):
self.name = threading.currentThread().name
print 'create: %s' % self.name
def __del__(self):
print 'delete: %s' % self.name
def access_thlocal():
data.key = Resource()
for i in range(0, 10):
threading.Thread(target=access_thlocal).start()
time.sleep(1)
print "Triggering GC"
gc.collect()
time.sleep(1)
The output:
create: Thread-1
create: Thread-2
delete: Thread-1
create: Thread-3
delete: Thread-2
create: Thread-4
delete: Thread-3
create: Thread-5
delete: Thread-4
create: Thread-6
delete: Thread-5
create: Thread-7
delete: Thread-6
create: Thread-8
delete: Thread-7
create: Thread-9
delete: Thread-8
create: Thread-10
delete: Thread-9
Triggering GC
delete: Thread-10
As you can see, the delete's seem to happen as soon as the thread dies.
A:
Mark had it almost right -- essentially "mydata" will hold references to all the TL variables in it, whatever thread they were created from. To wit...:
import threading
import gc
mydata = threading.local()
class x:
def __del__(self):
print "x got deleted!"
def run():
mydata.foo = x()
t = threading.Thread(target=run)
print "t created"
gc.collect()
t.start()
print "t started"
gc.collect()
del mydata
print "mydata deleted"
gc.collect()
t.join()
print "t joined"
gc.collect()
print "Done!"
Emits:
t created
t started
x got deleted!
mydata deleted
t joined
Done!
gc actually plays no role here in CPython, so you can simplify the code down to:
import threading
mydata = threading.local()
class x:
def __init__(self):
print "x got created!"
def __del__(self):
print "x got deleted!"
def run():
mydata.foo = x()
t = threading.Thread(target=run)
print "t created"
t.start()
print "t started"
del mydata
print "mydata deleted"
t.join()
print "t joined"
print "Done!"
and still see...:
t created
x got created!
t started
x got deleted!
mydata deleted
t joined
Done!
A:
Thanks! It seems that Mark's program behaves differently under CPython 2.5 and 2.6:
import threading
import gc
import platform
print "Python %s (%s)" % (platform.python_version(), " ".join(platform.python_build()))
mydata = threading.local()
class x:
def __del__(self):
print "x got deleted!"
def run():
mydata.foo = x()
t = threading.Thread(target=run)
print "t created"
gc.collect()
t.start()
print "t started"
gc.collect()
del mydata
print "mydata deleted"
gc.collect()
t.join()
print "t joined"
gc.collect()
print "Done!"
Emits (under Ubuntu 8.04 i386):
Python 2.5.2 (r252:60911 Jul 31 2008 19:40:22)
t created
t started
mydata deleted
x got deleted!
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.5/threading.py", line 486, in __bootstrap_inner
self.run()
File "/usr/lib/python2.5/threading.py", line 446, in run
self.__target(*self.__args, **self.__kwargs)
File "./x.py", line 14, in run
mydata.foo = x()
NameError: global name 'mydata' is not defined
t joined
Done!
And:
Python 2.6.2 (r262:71600 Sep 19 2009 17:24:20)
t created
t started
x got deleted!
mydata deleted
t joined
Done!
A:
By making a couple simple changes to your program and forcing a garbage collection after each step of the threading, it seems that foo cannot be collected until the program is finished - in other words, after the thread goes out of scope.
import threading
import gc
mydata = threading.local()
class x:
def __del__(self):
print "x got deleted!"
def run():
mydata.foo = x()
t = threading.Thread(target=run)
print "t created"
gc.collect()
t.start()
print "t started"
gc.collect()
t.join()
print "t joined"
gc.collect()
print "Done!"
output (using Python 2.6, Windows):
>C:\temp\py\t.py
t created
t started
t joined
Done!
x got deleted!
| What's the life-time of a thread-local value in Python? | import threading
mydata = threading.local()
def run():
# When will the garbage collector be able to destroy the object created
# here? After the thread exits from ``run()``? After ``join()`` is called?
# Or will it survive the thread in which it was created, and live until
# ``mydata`` is garbage-collected?
mydata.foo = object()
t = threading.Thread(target=run)
t.start()
t.join()
| [
"Here is my answer, since I am failing to see the conclusion in the previous answers.\nI started wondering the same thing and tried a test program that is similar to the ones in other answers and my conclusion was that they do get GCed sooner than the end of the program, which means, these references can be determined as garbage once the thread itself dies.\nimport time\nimport threading\nimport gc\n\ndata = threading.local()\n\nclass Resource(object):\n def __init__(self):\n self.name = threading.currentThread().name\n print 'create: %s' % self.name\n\n def __del__(self):\n print 'delete: %s' % self.name\n\ndef access_thlocal():\n data.key = Resource()\n\nfor i in range(0, 10):\n threading.Thread(target=access_thlocal).start()\ntime.sleep(1)\nprint \"Triggering GC\"\ngc.collect()\ntime.sleep(1)\n\nThe output:\ncreate: Thread-1\ncreate: Thread-2\ndelete: Thread-1\ncreate: Thread-3\ndelete: Thread-2\ncreate: Thread-4\ndelete: Thread-3\ncreate: Thread-5\ndelete: Thread-4\ncreate: Thread-6\ndelete: Thread-5\ncreate: Thread-7\ndelete: Thread-6\ncreate: Thread-8\ndelete: Thread-7\ncreate: Thread-9\ndelete: Thread-8\ncreate: Thread-10\ndelete: Thread-9\nTriggering GC\ndelete: Thread-10\n\nAs you can see, the delete's seem to happen as soon as the thread dies.\n",
"Mark had it almost right -- essentially \"mydata\" will hold references to all the TL variables in it, whatever thread they were created from. To wit...:\nimport threading\nimport gc\n\nmydata = threading.local()\n\nclass x:\n def __del__(self):\n print \"x got deleted!\"\n\ndef run():\n mydata.foo = x()\n\nt = threading.Thread(target=run)\nprint \"t created\"\ngc.collect()\nt.start()\nprint \"t started\"\ngc.collect()\ndel mydata\nprint \"mydata deleted\"\ngc.collect()\nt.join()\nprint \"t joined\"\ngc.collect()\nprint \"Done!\"\n\nEmits:\nt created\nt started\nx got deleted!\nmydata deleted\nt joined\nDone!\n\ngc actually plays no role here in CPython, so you can simplify the code down to:\nimport threading\n\nmydata = threading.local()\n\nclass x:\n def __init__(self):\n print \"x got created!\"\n def __del__(self):\n print \"x got deleted!\"\n\ndef run():\n mydata.foo = x()\n\nt = threading.Thread(target=run)\nprint \"t created\"\nt.start()\nprint \"t started\"\ndel mydata\nprint \"mydata deleted\"\nt.join()\nprint \"t joined\"\nprint \"Done!\"\n\nand still see...:\nt created\nx got created!\nt started\nx got deleted!\nmydata deleted\nt joined\nDone!\n\n",
"Thanks! It seems that Mark's program behaves differently under CPython 2.5 and 2.6:\nimport threading\nimport gc\nimport platform\n\nprint \"Python %s (%s)\" % (platform.python_version(), \" \".join(platform.python_build()))\n\nmydata = threading.local()\n\nclass x:\n def __del__(self):\n print \"x got deleted!\"\n\ndef run():\n mydata.foo = x()\n\nt = threading.Thread(target=run)\nprint \"t created\"\ngc.collect()\nt.start()\nprint \"t started\"\ngc.collect()\ndel mydata\nprint \"mydata deleted\"\ngc.collect()\nt.join()\nprint \"t joined\"\ngc.collect()\nprint \"Done!\"\n\nEmits (under Ubuntu 8.04 i386):\nPython 2.5.2 (r252:60911 Jul 31 2008 19:40:22)\nt created\nt started\nmydata deleted\nx got deleted!\nException in thread Thread-1:\nTraceback (most recent call last):\n File \"/usr/lib/python2.5/threading.py\", line 486, in __bootstrap_inner\n self.run()\n File \"/usr/lib/python2.5/threading.py\", line 446, in run\n self.__target(*self.__args, **self.__kwargs)\n File \"./x.py\", line 14, in run\n mydata.foo = x()\nNameError: global name 'mydata' is not defined\n\nt joined\nDone!\n\nAnd:\nPython 2.6.2 (r262:71600 Sep 19 2009 17:24:20)\nt created\nt started\nx got deleted!\nmydata deleted\nt joined\nDone!\n\n",
"By making a couple simple changes to your program and forcing a garbage collection after each step of the threading, it seems that foo cannot be collected until the program is finished - in other words, after the thread goes out of scope.\nimport threading\nimport gc\n\nmydata = threading.local()\n\nclass x:\n def __del__(self):\n print \"x got deleted!\"\n\ndef run():\n mydata.foo = x()\n\nt = threading.Thread(target=run)\nprint \"t created\"\ngc.collect()\nt.start()\nprint \"t started\"\ngc.collect()\nt.join()\nprint \"t joined\"\ngc.collect()\nprint \"Done!\"\n\noutput (using Python 2.6, Windows):\n\n>C:\\temp\\py\\t.py\nt created\nt started\nt joined\nDone!\nx got deleted!\n\n"
] | [
10,
3,
1,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0001478248_multithreading_python.txt |
Q:
Getting pixel averages of a vector sitting atop a bitmap
I'm currently involved in a hardware project where I am mapping triangular shaped LED to traditional bitmap images. I'd like to overlay a triangle vector onto an image and get the average pixel data within the bounds of that vector. However, I'm unfamiliar with the math needed to calculate this. Does anyone have an algorithm or a link that could send me in the right direction? (I tagged this as Python, which is preferred, but I'd be happy with the general algorithm!)
I've created a basic image of what I'm trying to capture here: http://imgur.com/Isjip.gif
A:
Will this work: http://www.blackpawn.com/texts/pointinpoly/default.html ?
A:
You can do line rasterization on the lineparts to determine for each pixel at each horizontal scanline lie within your triangle. Sum and divide their RGB values to get the average.
| Getting pixel averages of a vector sitting atop a bitmap | I'm currently involved in a hardware project where I am mapping triangular shaped LED to traditional bitmap images. I'd like to overlay a triangle vector onto an image and get the average pixel data within the bounds of that vector. However, I'm unfamiliar with the math needed to calculate this. Does anyone have an algorithm or a link that could send me in the right direction? (I tagged this as Python, which is preferred, but I'd be happy with the general algorithm!)
I've created a basic image of what I'm trying to capture here: http://imgur.com/Isjip.gif
| [
"Will this work: http://www.blackpawn.com/texts/pointinpoly/default.html ?\n",
"You can do line rasterization on the lineparts to determine for each pixel at each horizontal scanline lie within your triangle. Sum and divide their RGB values to get the average.\n"
] | [
0,
0
] | [] | [] | [
"image_manipulation",
"python"
] | stackoverflow_0002878928_image_manipulation_python.txt |
Q:
Django Error: NameError name 'current_datetime' is not defined
I'm working through the book "The Definitive Guide to Django" and am stuck on a piece of code.
This is the code in my settings.py:
ROOT_URLCONF = 'mysite.urls'
I have the following code in my urls.py
from django.conf.urls.defaults import *
from mysite.views import hello, my_homepage_view
urlpatterns = patterns('', ('^hello/$', hello),
)
urlpatterns = patterns('', ('^time/$', current_datetime),
)
And the following is the code in my views.py file:
from django.http import HttpResponse
import datetime
def hello(request):
return HttpResponse("Hello World")
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
Yet, I get the following error when I test the code in the development server.
NameError at /time/
name 'current_datetime' is not defined
Can someone help me out here? This really is just a copy-paste from the book. I don't see any mistyping.
A:
Change:
from mysite.views import hello, my_homepage_view
To this:
from mysite.views import current_datetime, hello, my_homepage_view
Here's some documentation: http://www.djangobook.com/en/1.0/chapter03/
| Django Error: NameError name 'current_datetime' is not defined | I'm working through the book "The Definitive Guide to Django" and am stuck on a piece of code.
This is the code in my settings.py:
ROOT_URLCONF = 'mysite.urls'
I have the following code in my urls.py
from django.conf.urls.defaults import *
from mysite.views import hello, my_homepage_view
urlpatterns = patterns('', ('^hello/$', hello),
)
urlpatterns = patterns('', ('^time/$', current_datetime),
)
And the following is the code in my views.py file:
from django.http import HttpResponse
import datetime
def hello(request):
return HttpResponse("Hello World")
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)
Yet, I get the following error when I test the code in the development server.
NameError at /time/
name 'current_datetime' is not defined
Can someone help me out here? This really is just a copy-paste from the book. I don't see any mistyping.
| [
"Change:\nfrom mysite.views import hello, my_homepage_view\n\nTo this:\nfrom mysite.views import current_datetime, hello, my_homepage_view\n\nHere's some documentation: http://www.djangobook.com/en/1.0/chapter03/ \n"
] | [
3
] | [] | [] | [
"django",
"django_urls",
"django_views",
"nameerror",
"python"
] | stackoverflow_0002879170_django_django_urls_django_views_nameerror_python.txt |
Q:
Problem with urllib
I wrote this code:
import urllib
proxies = {'http': 'http://112.65.135.54:8080/'}
opener = urllib.FancyURLopener(proxies)
r = opener.open("http://www.python.org/")
print r.read()
and when I execute it this program works fine, and send for me source code of python.org But when i use this:
import urllib
proxies = {'http': 'http://80.176.245.196:1080/'}
opener = urllib.FancyURLopener(proxies)
r = opener.open("http://www.python.org/")
print r.read()
this program does not send me the source code of python.org
What am I going to do?
A:
Presumably, the first IP address and port points to a working proxy, while the second set does not (they're on private IPs so of course nobody else can check). So, speak with whoever handles your local network, and get the exact specs for IP and port of the HTTP proxy you're supposed to use!
Edit: aargh, the question had been edited to "mask" the IPs (now they're back and they're definitely not on private networks!) -- so the answer was based on that. Anyway, no need for digging now, as the OP has already discovered that one is a socks proxy, not an http proxy, and so of course can't be treated as the latter;-).
A:
hehe :d i find the answer i must use "socks" instead of "http" :
import urllib
proxies = {'socks': 'http://80.176.245.196:1080/'}
opener = urllib.FancyURLopener(proxies)
r = opener.open("http://www.python.org/")
print r.read()
this code works fine
| Problem with urllib | I wrote this code:
import urllib
proxies = {'http': 'http://112.65.135.54:8080/'}
opener = urllib.FancyURLopener(proxies)
r = opener.open("http://www.python.org/")
print r.read()
and when I execute it this program works fine, and send for me source code of python.org But when i use this:
import urllib
proxies = {'http': 'http://80.176.245.196:1080/'}
opener = urllib.FancyURLopener(proxies)
r = opener.open("http://www.python.org/")
print r.read()
this program does not send me the source code of python.org
What am I going to do?
| [
"Presumably, the first IP address and port points to a working proxy, while the second set does not (they're on private IPs so of course nobody else can check). So, speak with whoever handles your local network, and get the exact specs for IP and port of the HTTP proxy you're supposed to use!\nEdit: aargh, the question had been edited to \"mask\" the IPs (now they're back and they're definitely not on private networks!) -- so the answer was based on that. Anyway, no need for digging now, as the OP has already discovered that one is a socks proxy, not an http proxy, and so of course can't be treated as the latter;-).\n",
"hehe :d i find the answer i must use \"socks\" instead of \"http\" :\nimport urllib\nproxies = {'socks': 'http://80.176.245.196:1080/'}\nopener = urllib.FancyURLopener(proxies)\nr = opener.open(\"http://www.python.org/\")\nprint r.read()\nthis code works fine\n"
] | [
1,
1
] | [] | [] | [
"python",
"sockets",
"urllib"
] | stackoverflow_0002879183_python_sockets_urllib.txt |
Q:
Help with Django localization--doesn't seem to be working. Nothing happens
Can someone help me with Localization? I put {% trans "..." %} in my template, I filled in my django.po after running "makemessages".
#: templates/main_content.html:136
msgid "Go to page"
msgstr "▒~C~Z▒~C▒▒~B▒▒~L~G▒~Z"
#: templates/main_content.html:138
msgid "Page"
msgstr "▒~C~Z▒~C▒▒~B▒"
#: templates/main_content.html:154
msgid "Next"
msgstr "次"
Then, I set LANGUAGES={} in my settings.py along with "gettext lambda":
gettext = lambda s: s
LANGUAGES = (
('de', gettext('German')),
('en', gettext('English')),
('ja', gettext('Japanese')),
)
Of course, I installed the LocaleMiddleware.
I also set the request.session['django_language'] = "ja"
How do I test that this is working? How do I see japanese on my site!?
A:
Set your browser (or whatever web user agent you're using to test this site) so that its Accept-Language request header value is ja.
| Help with Django localization--doesn't seem to be working. Nothing happens | Can someone help me with Localization? I put {% trans "..." %} in my template, I filled in my django.po after running "makemessages".
#: templates/main_content.html:136
msgid "Go to page"
msgstr "▒~C~Z▒~C▒▒~B▒▒~L~G▒~Z"
#: templates/main_content.html:138
msgid "Page"
msgstr "▒~C~Z▒~C▒▒~B▒"
#: templates/main_content.html:154
msgid "Next"
msgstr "次"
Then, I set LANGUAGES={} in my settings.py along with "gettext lambda":
gettext = lambda s: s
LANGUAGES = (
('de', gettext('German')),
('en', gettext('English')),
('ja', gettext('Japanese')),
)
Of course, I installed the LocaleMiddleware.
I also set the request.session['django_language'] = "ja"
How do I test that this is working? How do I see japanese on my site!?
| [
"Set your browser (or whatever web user agent you're using to test this site) so that its Accept-Language request header value is ja.\n"
] | [
0
] | [] | [] | [
"django",
"internationalization",
"localization",
"python"
] | stackoverflow_0002878935_django_internationalization_localization_python.txt |
Q:
Python base classes share attributes?
Code in test.py:
class Base(object):
def __init__(self, l=[]):
self.l = l
def add(self, num):
self.l.append(num)
def remove(self, num):
self.l.remove(num)
class Derived(Base):
def __init__(self, l=[]):
super(Derived, self).__init__(l)
Python shell session:
Python 2.6.5 (r265:79063, Apr 1 2010, 05:22:20)
[GCC 4.4.3 20100316 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> a = test.Derived()
>>> b = test.Derived()
>>> a.l
[]
>>> b.l
[]
>>> a.add(1)
>>> a.l
[1]
>>> b.l
[1]
>>> c = test.Derived()
>>> c.l
[1]
I was expecting "C++-like" behavior, in which each derived object contains its own instance of the base class. Is this still the case? Why does each object appear to share the same list instance?
A:
You're making a common Python newcomer mistake.
See my answer here:
How should I declare default values for instance variables in Python?
Briefly explained, Python interprets the class definitions only once. That means everything declared in the __init__() method is only created once. Or, in another words, your [] list default argument is only made once.
Then self.l = l assigns a reference to the same instance every time you create a new class, hence the behaviour you weren't expecting.
The Pythonic way is this (partial code):
def __init__(self, arg=None):
if arg is None:
arg = []
self.arg = arg
Also, you should consider using a better naming convention than l, which is hard to read and might be mistaken as 1 or |.
A:
This is called the mutable default argument bug that is commonly made by people new to Python. When you give a mutable as a default argument, the same object gets used across instances when the default argument is required to be used. The get a better understand check the Important warning section in http://docs.python.org/tutorial/controlflow.html#default-argument-values
In your code, the instance a used the mutable default argument (a empty list object) in it's init call and when you created the instance of b, which in turn called Base's init method, again used the very same object that a used in it's init. On simpler words a.l and b.l point to the same list object.
A very similar discussion - "Least Astonishment" and the Mutable Default Argument
| Python base classes share attributes? | Code in test.py:
class Base(object):
def __init__(self, l=[]):
self.l = l
def add(self, num):
self.l.append(num)
def remove(self, num):
self.l.remove(num)
class Derived(Base):
def __init__(self, l=[]):
super(Derived, self).__init__(l)
Python shell session:
Python 2.6.5 (r265:79063, Apr 1 2010, 05:22:20)
[GCC 4.4.3 20100316 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> a = test.Derived()
>>> b = test.Derived()
>>> a.l
[]
>>> b.l
[]
>>> a.add(1)
>>> a.l
[1]
>>> b.l
[1]
>>> c = test.Derived()
>>> c.l
[1]
I was expecting "C++-like" behavior, in which each derived object contains its own instance of the base class. Is this still the case? Why does each object appear to share the same list instance?
| [
"You're making a common Python newcomer mistake.\nSee my answer here:\nHow should I declare default values for instance variables in Python?\nBriefly explained, Python interprets the class definitions only once. That means everything declared in the __init__() method is only created once. Or, in another words, your [] list default argument is only made once.\nThen self.l = l assigns a reference to the same instance every time you create a new class, hence the behaviour you weren't expecting.\nThe Pythonic way is this (partial code):\ndef __init__(self, arg=None):\n if arg is None:\n arg = []\n self.arg = arg\n\nAlso, you should consider using a better naming convention than l, which is hard to read and might be mistaken as 1 or |.\n",
"This is called the mutable default argument bug that is commonly made by people new to Python. When you give a mutable as a default argument, the same object gets used across instances when the default argument is required to be used. The get a better understand check the Important warning section in http://docs.python.org/tutorial/controlflow.html#default-argument-values\nIn your code, the instance a used the mutable default argument (a empty list object) in it's init call and when you created the instance of b, which in turn called Base's init method, again used the very same object that a used in it's init. On simpler words a.l and b.l point to the same list object.\nA very similar discussion - \"Least Astonishment\" and the Mutable Default Argument\n"
] | [
20,
2
] | [] | [] | [
"python"
] | stackoverflow_0002879494_python.txt |
Q:
Python How to make a cross-module function?
I want to be able to call a global function from an imported class, for example
In file PetStore.py
class AnimalSound(object):
def __init__(self):
if 'makenoise' in globals():
self.makenoise = globals()['makenoise']
else:
self.makenoise = lambda: 'meow'
def __str__(self):
return self.makenoise()
Then when I test in the Python Interpreter
>>> def makenoise():
... return 'bark'
...
>>> from PetStore import AnimalSound
>>> sound = AnimalSound()
>>> sound.makenoise()
'meow'
I get a 'meow' instead of 'bark'. I have tried using the solutions provided in python-how-to-make-a-cross-module-variable with no luck.
A:
The globals() call returns the globals of the module in which the call is lexically located; there is no intrinsic "dynamic scoping" in Python -- it's lexically scoped, like just about every modern language.
The solid, proper way to obtain the effect you desire is to explicitly pass to the initializer of AnimalSound the callable it's supposed to use to "make noise": i.e., the class should be
class AnimalSound(object):
def __init__(self, makenoise=lambda: 'meow'):
self.makenoise = makenoise
def __str__(self):
return self.makenoise()
and the call should be
sound = AnimalSound(makenoise)
There are practicable but less-sound solutions, such as the caller passing its own globals() (but that needlessly constrains the name of the callable!), or even (shudder) communicating via covert channels like the other answer advocates (that would be a potential disaster if you had two instantiations of AnimalSound built according to the same principle in two separate modules, etc, etc). But, "explicit is better than implicit", and clean, safe, overt communication leads to clean, safe, robust system architectures: I earnestly recommend you choose this route.
A:
"Global" scope in Python is Module scope.
import PetStore
PetStore.makenoise = makenoise
| Python How to make a cross-module function? | I want to be able to call a global function from an imported class, for example
In file PetStore.py
class AnimalSound(object):
def __init__(self):
if 'makenoise' in globals():
self.makenoise = globals()['makenoise']
else:
self.makenoise = lambda: 'meow'
def __str__(self):
return self.makenoise()
Then when I test in the Python Interpreter
>>> def makenoise():
... return 'bark'
...
>>> from PetStore import AnimalSound
>>> sound = AnimalSound()
>>> sound.makenoise()
'meow'
I get a 'meow' instead of 'bark'. I have tried using the solutions provided in python-how-to-make-a-cross-module-variable with no luck.
| [
"The globals() call returns the globals of the module in which the call is lexically located; there is no intrinsic \"dynamic scoping\" in Python -- it's lexically scoped, like just about every modern language.\nThe solid, proper way to obtain the effect you desire is to explicitly pass to the initializer of AnimalSound the callable it's supposed to use to \"make noise\": i.e., the class should be\nclass AnimalSound(object):\n def __init__(self, makenoise=lambda: 'meow'):\n self.makenoise = makenoise\n\n def __str__(self):\n return self.makenoise()\n\nand the call should be\nsound = AnimalSound(makenoise)\n\nThere are practicable but less-sound solutions, such as the caller passing its own globals() (but that needlessly constrains the name of the callable!), or even (shudder) communicating via covert channels like the other answer advocates (that would be a potential disaster if you had two instantiations of AnimalSound built according to the same principle in two separate modules, etc, etc). But, \"explicit is better than implicit\", and clean, safe, overt communication leads to clean, safe, robust system architectures: I earnestly recommend you choose this route.\n",
"\"Global\" scope in Python is Module scope.\nimport PetStore\n\nPetStore.makenoise = makenoise\n\n"
] | [
5,
2
] | [] | [] | [
"global",
"module",
"python"
] | stackoverflow_0002879711_global_module_python.txt |
Q:
Subprocess fails to catch the standard output
I am trying to generate tree with fasta file input and Alignment with MuscleCommandline
import sys,os, subprocess
from Bio import AlignIO
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(input="c:\Python26\opuntia.fasta")
child= subprocess.Popen(str(cline),
stdout = subprocess.PIPE,
stderr=subprocess.PIPE,
shell=(sys.platform!="win32"))
align=AlignIO.read(child.stdout,"fasta")
outfile=open('c:\Python26\opuntia.phy','w')
AlignIO.write([align],outfile,'phylip')
outfile.close()
I always encounter with these problems
Traceback (most recent call last):
File "<string>", line 244, in run_nodebug
File "C:\Python26\muscleIO.py", line 11, in <module>
align=AlignIO.read(child.stdout,"fasta")
File "C:\Python26\Lib\site-packages\Bio\AlignIO\__init__.py", line 423, in read
raise ValueError("No records found in handle")
ValueError: No records found in handle
A:
A couple of things are giving problems here:
You need a child.wait() after the subprocess call so that your code will wait until the external program is done running.
Muscle does not actually write to stdout, even though the help documentation says it does, at least with v3.6 that I have here. I believe the latest is v3.8 so this may be fixed.
Biopython is telling you that the stdout you are passing it is empty, which is the error you are seeing. Try running the commandline directly:
muscle -in opuntia.fasta
and see if you see FASTA output. Here is a version that fixes the wait problem and uses an intermediate output file:
import sys,os, subprocess
from Bio import AlignIO
from Bio.Align.Applications import MuscleCommandline
out_file = "opuntia.aln"
cline = MuscleCommandline(input="opuntia.fasta", out=out_file)
child= subprocess.Popen(str(cline),
stdout = subprocess.PIPE,
stderr=subprocess.PIPE,
shell=(sys.platform!="win32"))
child.wait()
with open(out_file) as align_handle:
align=AlignIO.read(align_handle,"fasta")
outfile=open('opuntia.phy','w')
AlignIO.write([align],outfile,'phylip')
outfile.close()
os.remove(out_file)
A:
From the documentation of the subproccess library:
Warning
Use communicate() rather than
.stdin.write, .stdout.read or
.stderr.read to avoid deadlocks due to
any of the other OS pipe buffers
filling up and blocking the child
process.
so maybe you could try something like:
mydata = child.communicate()[0]
A:
You have an unprotected backslash in your output filename, that is never good.
Use 'r' to get raw strings, i.e. r'c:\Python26\opuntia.phy'.
A:
Biopython 1.54 was released today with a stable version of the Bio.Phylo module. I've updated the documentation with an example pipeline for generating trees. For simplicity, the example uses ClustalW to align sequences and generate a tree, instead of Muscle and Phylip, but most of the code is still the same or similar.
http://biopython.org/wiki/Phylo#Example_pipeline
If you've already generated a tree with Phylip (using the .phy alignment as input), you can still follow the Phylo examples in general. Phylip creates a Newick file with a name like "outttree" or "foo.tree".
(Feel free to merge this with Brad's answer; I can't write a comment in that thread yet.)
| Subprocess fails to catch the standard output | I am trying to generate tree with fasta file input and Alignment with MuscleCommandline
import sys,os, subprocess
from Bio import AlignIO
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(input="c:\Python26\opuntia.fasta")
child= subprocess.Popen(str(cline),
stdout = subprocess.PIPE,
stderr=subprocess.PIPE,
shell=(sys.platform!="win32"))
align=AlignIO.read(child.stdout,"fasta")
outfile=open('c:\Python26\opuntia.phy','w')
AlignIO.write([align],outfile,'phylip')
outfile.close()
I always encounter with these problems
Traceback (most recent call last):
File "<string>", line 244, in run_nodebug
File "C:\Python26\muscleIO.py", line 11, in <module>
align=AlignIO.read(child.stdout,"fasta")
File "C:\Python26\Lib\site-packages\Bio\AlignIO\__init__.py", line 423, in read
raise ValueError("No records found in handle")
ValueError: No records found in handle
| [
"A couple of things are giving problems here:\n\nYou need a child.wait() after the subprocess call so that your code will wait until the external program is done running.\nMuscle does not actually write to stdout, even though the help documentation says it does, at least with v3.6 that I have here. I believe the latest is v3.8 so this may be fixed.\n\nBiopython is telling you that the stdout you are passing it is empty, which is the error you are seeing. Try running the commandline directly:\nmuscle -in opuntia.fasta\nand see if you see FASTA output. Here is a version that fixes the wait problem and uses an intermediate output file:\n\nimport sys,os, subprocess\nfrom Bio import AlignIO\nfrom Bio.Align.Applications import MuscleCommandline\nout_file = \"opuntia.aln\"\ncline = MuscleCommandline(input=\"opuntia.fasta\", out=out_file)\nchild= subprocess.Popen(str(cline),\n stdout = subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=(sys.platform!=\"win32\"))\nchild.wait()\nwith open(out_file) as align_handle:\n align=AlignIO.read(align_handle,\"fasta\")\noutfile=open('opuntia.phy','w')\nAlignIO.write([align],outfile,'phylip')\noutfile.close()\nos.remove(out_file)\n\n",
"From the documentation of the subproccess library:\n\nWarning\nUse communicate() rather than\n .stdin.write, .stdout.read or\n .stderr.read to avoid deadlocks due to\n any of the other OS pipe buffers\n filling up and blocking the child\n process.\n\nso maybe you could try something like:\nmydata = child.communicate()[0]\n\n",
"You have an unprotected backslash in your output filename, that is never good.\nUse 'r' to get raw strings, i.e. r'c:\\Python26\\opuntia.phy'.\n",
"Biopython 1.54 was released today with a stable version of the Bio.Phylo module. I've updated the documentation with an example pipeline for generating trees. For simplicity, the example uses ClustalW to align sequences and generate a tree, instead of Muscle and Phylip, but most of the code is still the same or similar.\nhttp://biopython.org/wiki/Phylo#Example_pipeline\nIf you've already generated a tree with Phylip (using the .phy alignment as input), you can still follow the Phylo examples in general. Phylip creates a Newick file with a name like \"outttree\" or \"foo.tree\".\n(Feel free to merge this with Brad's answer; I can't write a comment in that thread yet.)\n"
] | [
4,
2,
1,
0
] | [] | [] | [
"biopython",
"python",
"subprocess"
] | stackoverflow_0002856697_biopython_python_subprocess.txt |
Q:
is there a twitter user login framework for gae
I want to someone to be able to login using twitter,
Is there a framework that you have used to do this?
Thanks
A:
There's a simple example here. Beyond this, there's tweetapp, but it's currently not maintained; AppEngine-OAuth-Library; and, I believe, some twitter-friendly delegated authorization framework for Django, Django-social-auth, about which, however, I don't know much beyond the name.
A:
While not exactly addressing your questions I believe these examples and code will be useful:
http://github.com/joshthecoder/tweepy
http://github.com/joshthecoder/tweepy-examples
http://github.com/wasauce/redroosterlabs
| is there a twitter user login framework for gae | I want to someone to be able to login using twitter,
Is there a framework that you have used to do this?
Thanks
| [
"There's a simple example here. Beyond this, there's tweetapp, but it's currently not maintained; AppEngine-OAuth-Library; and, I believe, some twitter-friendly delegated authorization framework for Django, Django-social-auth, about which, however, I don't know much beyond the name.\n",
"While not exactly addressing your questions I believe these examples and code will be useful:\n\nhttp://github.com/joshthecoder/tweepy\nhttp://github.com/joshthecoder/tweepy-examples\nhttp://github.com/wasauce/redroosterlabs\n\n"
] | [
1,
1
] | [] | [] | [
"frameworks",
"google_app_engine",
"oauth",
"python",
"twitter"
] | stackoverflow_0002879146_frameworks_google_app_engine_oauth_python_twitter.txt |
Q:
Get system language in ISO 639 (3-letter codes) in Python
Could someone tell me a way to get a system language in the ISO 639 (3 letter code) format in a cross platform way?
Thanks.
I found a list of three letter country codes.
A:
I'm assuming you're wanting ISO 639 2 and not ISO 639 3 here. Machine-readable data is available from the Library of Congress (I'm using the "utf-8" encoding for this answer, see also http://www.loc.gov/standards/iso639-2/ascii_8bits.html for more info.)
Here's an example of how you could load this:
import codecs
def getisocodes_dict(data_path):
# Provide a map from ISO code (both bibliographic and terminologic)
# in ISO 639-2 to a dict with the two letter ISO 639-2 codes (alpha2)
# English and french names
#
# "bibliographic" iso codes are derived from English word for the language
# "terminologic" iso codes are derived from the pronunciation in the target
# language (if different to the bibliographic code)
D = {}
f = codecs.open(data_path, 'rb', 'utf-8')
for line in f:
iD = {}
iD['bibliographic'], iD['terminologic'], iD['alpha2'], \
iD['english'], iD['french'] = line.strip().split('|')
D[iD['bibliographic']] = iD
if iD['terminologic']:
D[iD['terminologic']] = iD
if iD['alpha2']:
D[iD['alpha2']] = iD
for k in iD:
# Assign `None` when columns not available from the data
iD[k] = iD[k] or None
f.close()
return D
if __name__ == '__main__':
D = getisocodes_dict('ISO-639-2_utf-8.txt')
print D['eng']
print D['fr']
# Print my current locale
import locale
print D[locale.getdefaultlocale()[0].split('_')[0].lower()]
A:
You could also use pycountry at http://pypi.python.org/pypi/pycountry/ which seems to have the ISO 639 2 codes (just using google :-)
| Get system language in ISO 639 (3-letter codes) in Python | Could someone tell me a way to get a system language in the ISO 639 (3 letter code) format in a cross platform way?
Thanks.
I found a list of three letter country codes.
| [
"I'm assuming you're wanting ISO 639 2 and not ISO 639 3 here. Machine-readable data is available from the Library of Congress (I'm using the \"utf-8\" encoding for this answer, see also http://www.loc.gov/standards/iso639-2/ascii_8bits.html for more info.) \nHere's an example of how you could load this:\nimport codecs\n\ndef getisocodes_dict(data_path):\n # Provide a map from ISO code (both bibliographic and terminologic)\n # in ISO 639-2 to a dict with the two letter ISO 639-2 codes (alpha2)\n # English and french names\n #\n # \"bibliographic\" iso codes are derived from English word for the language\n # \"terminologic\" iso codes are derived from the pronunciation in the target \n # language (if different to the bibliographic code)\n\n D = {}\n f = codecs.open(data_path, 'rb', 'utf-8')\n for line in f:\n iD = {}\n iD['bibliographic'], iD['terminologic'], iD['alpha2'], \\\n iD['english'], iD['french'] = line.strip().split('|')\n D[iD['bibliographic']] = iD\n\n if iD['terminologic']:\n D[iD['terminologic']] = iD\n\n if iD['alpha2']:\n D[iD['alpha2']] = iD\n\n for k in iD:\n # Assign `None` when columns not available from the data\n iD[k] = iD[k] or None\n f.close()\n return D\n\nif __name__ == '__main__':\n D = getisocodes_dict('ISO-639-2_utf-8.txt')\n print D['eng']\n print D['fr']\n\n # Print my current locale\n import locale\n print D[locale.getdefaultlocale()[0].split('_')[0].lower()]\n\n",
"You could also use pycountry at http://pypi.python.org/pypi/pycountry/ which seems to have the ISO 639 2 codes (just using google :-)\n"
] | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0002879856_python.txt |
Q:
Is there a ruby equivalent of "python -i"?
ruby -n is the closest thing I found, but it repeats the whole script. Also it's not available for irb.
A:
$ cat > hello.rb
$hello = 'Hello, world!'
puts $hello
^D
$ irb
irb(main):001:0> load 'hello.rb'
Hello, world!
=> true
irb(main):002:0> $hello
=> "Hello, world!"
A bit tedious, and local variables won't carry through. May be close enough for your usage? (This is basically like Python's execfile.)
A:
irb -r hello.rb
| Is there a ruby equivalent of "python -i"? | ruby -n is the closest thing I found, but it repeats the whole script. Also it's not available for irb.
| [
"\n$ cat > hello.rb\n$hello = 'Hello, world!'\nputs $hello\n^D\n$ irb\nirb(main):001:0> load 'hello.rb'\nHello, world!\n=> true\nirb(main):002:0> $hello\n=> \"Hello, world!\"\n\nA bit tedious, and local variables won't carry through. May be close enough for your usage? (This is basically like Python's execfile.)\n",
"irb -r hello.rb\n"
] | [
1,
1
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0002437582_python_ruby.txt |
Q:
Python rounding problem
>>> num = 4.123456
>>> round(num, 3) # expecting 4.123
4.1230000000000002
I'm expecting 4.123 as a result, Am I wrong?
A:
This is not a mistake. You need to read What Every computer Scientist Should Know About Floating Point Arithmetic:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
A:
Yep, your expectations don't match the design intent of your tools.
Check out this section of the Python tutorial.
Using math.round is actually pretty rare. if you're trying to display a number as a string to a certain precision, you might want something more like
>>> num = 4.123456
>>> print "%.3f" % num
4.123
You might be interested in the documentation on string formatting.
A:
Why do you care? (That's a serious question.)
The answer that you're getting is so close to 4.123 as to make no difference. It can't be exactly 4.123, since there are only finitely many numbers (around 2**64 on a typical machine) that Python can represent exactly, and without going into detail about floating-point representations, it just so happens that 4.123 isn't one of those numbers. By the way, 4.1230000000000002 isn't one of the numbers that can be exactly represented, either; the actual number stored is 4.12300000000000022026824808563105762004852294921875, but Python truncates the decimal representation to 17 significant digits for display purposes. So:
If you're doing mathematics with the result, then the difference between 4.123 and what you're getting is so tiny as to make no real difference. Just don't worry about it.
If you just care about the output looking pretty (i.e., what you're after here is a string rather than a number) then use str, or string formatting.
In the unlikely case that the difference really does matter, e.g., because you're doing financial work and this affects the direction that something rounds later on, use the decimal module.
Final note: In Python 3.x and Python 2.7, the repr of a float has changed so that you will actually get 4.123 as you expect here.
A:
If you want to have an exact representation of your floating point number, you have to use decimal.
| Python rounding problem | >>> num = 4.123456
>>> round(num, 3) # expecting 4.123
4.1230000000000002
I'm expecting 4.123 as a result, Am I wrong?
| [
"This is not a mistake. You need to read What Every computer Scientist Should Know About Floating Point Arithmetic:\nhttp://docs.sun.com/source/806-3568/ncg_goldberg.html\n",
"Yep, your expectations don't match the design intent of your tools.\nCheck out this section of the Python tutorial.\n\nUsing math.round is actually pretty rare. if you're trying to display a number as a string to a certain precision, you might want something more like\n>>> num = 4.123456\n>>> print \"%.3f\" % num\n4.123\n\nYou might be interested in the documentation on string formatting.\n",
"Why do you care? (That's a serious question.)\nThe answer that you're getting is so close to 4.123 as to make no difference. It can't be exactly 4.123, since there are only finitely many numbers (around 2**64 on a typical machine) that Python can represent exactly, and without going into detail about floating-point representations, it just so happens that 4.123 isn't one of those numbers. By the way, 4.1230000000000002 isn't one of the numbers that can be exactly represented, either; the actual number stored is 4.12300000000000022026824808563105762004852294921875, but Python truncates the decimal representation to 17 significant digits for display purposes. So:\n\nIf you're doing mathematics with the result, then the difference between 4.123 and what you're getting is so tiny as to make no real difference. Just don't worry about it.\nIf you just care about the output looking pretty (i.e., what you're after here is a string rather than a number) then use str, or string formatting.\nIn the unlikely case that the difference really does matter, e.g., because you're doing financial work and this affects the direction that something rounds later on, use the decimal module.\n\nFinal note: In Python 3.x and Python 2.7, the repr of a float has changed so that you will actually get 4.123 as you expect here.\n",
"If you want to have an exact representation of your floating point number, you have to use decimal.\n"
] | [
7,
6,
4,
2
] | [] | [] | [
"floating_point",
"math",
"python"
] | stackoverflow_0002880547_floating_point_math_python.txt |
Q:
python VTE Terminal weirdness
i'm trying to use the terminal from python VTE binding (python-vte from debian squeeze) as a virtual terminal emulator (just for ANSI/control chars text processing)
in interactive python console, everything looks (almost) all right:
>>> import vte
>>> term = vte.Terminal()
>>> term.feed("a\nb")
>>> print repr(term.get_text(lambda *a: True).rstrip())
'a\n b'
however, launching this code (little modified) as python script, different result is yielded:
$ python vte_wiredness_1.py
''
strangely enough, pasting the code back into the (new) interactive python session also yields empty string:
>>> import vte
>>> term = vte.Terminal()
>>> term.feed("a\nb")
>>> print repr(term.get_text(lambda *a: True).rstrip())
''
>>>
first thing caming on my mind was that the only difference between the two cases is the timing - there had to be some delay before get_text. unfortunately, preluding get_text with some seconds sleep did not help
then i thought it has something to do with X window environment. but the results are the same pure linux console (with some warning on missing graphics).
i wonder what causes such an unpredictable behavior (interactive console - pasted vs typed, and it's not the delay.. ant the interactive console has nothing to do with the vte terminal object.. i guess)
can someone explain what is happening? is it possible to use the VTE Term such way?
that the "b" letter in the output is preceded by the space, is another strangeness (all consecutive lines are preceded by more spaces.. looks like I have to send carriage return before the string.)
(the lambda *a: True get_text method argument i'm using is a dummy callback, it's is some SlotSelectedCallback.. for its explanation i'd be grateful as well :) )
A:
..posting myself the solution i have found elsewhere
problem was that i was ignoring fact that vte.Terminal is an gtk applet, so gtk main loop has to be called.
example of working code:
import gtk
import vte
term = vte.Terminal()
term.feed("a\r\nb")
def get_text(term):
print repr(term.get_text(lambda *a: True).rstrip())
gtk.main_quit()
term.connect('contents-changed', get_text)
gtk.main()
thanks Juhaz@irc://freenode.net/##gnome
| python VTE Terminal weirdness | i'm trying to use the terminal from python VTE binding (python-vte from debian squeeze) as a virtual terminal emulator (just for ANSI/control chars text processing)
in interactive python console, everything looks (almost) all right:
>>> import vte
>>> term = vte.Terminal()
>>> term.feed("a\nb")
>>> print repr(term.get_text(lambda *a: True).rstrip())
'a\n b'
however, launching this code (little modified) as python script, different result is yielded:
$ python vte_wiredness_1.py
''
strangely enough, pasting the code back into the (new) interactive python session also yields empty string:
>>> import vte
>>> term = vte.Terminal()
>>> term.feed("a\nb")
>>> print repr(term.get_text(lambda *a: True).rstrip())
''
>>>
first thing caming on my mind was that the only difference between the two cases is the timing - there had to be some delay before get_text. unfortunately, preluding get_text with some seconds sleep did not help
then i thought it has something to do with X window environment. but the results are the same pure linux console (with some warning on missing graphics).
i wonder what causes such an unpredictable behavior (interactive console - pasted vs typed, and it's not the delay.. ant the interactive console has nothing to do with the vte terminal object.. i guess)
can someone explain what is happening? is it possible to use the VTE Term such way?
that the "b" letter in the output is preceded by the space, is another strangeness (all consecutive lines are preceded by more spaces.. looks like I have to send carriage return before the string.)
(the lambda *a: True get_text method argument i'm using is a dummy callback, it's is some SlotSelectedCallback.. for its explanation i'd be grateful as well :) )
| [
"..posting myself the solution i have found elsewhere\nproblem was that i was ignoring fact that vte.Terminal is an gtk applet, so gtk main loop has to be called.\nexample of working code:\nimport gtk\nimport vte\n\nterm = vte.Terminal()\n\nterm.feed(\"a\\r\\nb\")\n\ndef get_text(term):\n print repr(term.get_text(lambda *a: True).rstrip()) \n gtk.main_quit()\n\nterm.connect('contents-changed', get_text)\ngtk.main()\n\nthanks Juhaz@irc://freenode.net/##gnome\n"
] | [
3
] | [] | [] | [
"gnome",
"python",
"terminal",
"vte"
] | stackoverflow_0002868694_gnome_python_terminal_vte.txt |
Q:
Django 1.2 crash course needed
I know Python but I've never used Django.
What do I need to know about Django 1.2 to port my typical PHP CRUD web application in one weekend? (Yes I've read Joel Spolsky's Netscape article :-))
I'm reading this tutorial right now and it's excellent. I'm already playing around with inspectdb to generate my models from the existing schema.
I'm planning to use the following this weekend:
Fragment caching
Static asset versioning (for far future expires)
Schema migrations (or whatever they're called in Django)
Auto-admin (and customize it later)
The test framework
Skins
...other stuff I probably don't know about yet
I'm familiar with all these concepts in other languages/frameworks, except for the ORM which I've never used. I know SQL pretty well though.
Any links, sage bits of advice, gotchas, stuff not mentioned in the (excellent) tutorial/docs, or stuff that is mentioned but warrants repeating == very welcome. Thanks!
A:
The django docs is very good and you should find the answers to most of your questions http://docs.djangoproject.com/en/1.2/
You can google it easily but make sure that you are on the doc pages of django 1.2.
For schema migration, I recommed to look at south http://south.aeracode.org/
In my opinion south is a must-have feature for a website. It is quite easy and fast to get started. The tutorial on their website should help you. I think that it will be a big help if you plan to make some schema migration in the week-end. If not you can wait a little.
I've never used south on a db generated by inspectdb but I guess that it should work ok :)
Have a nice week-end :)
A:
My best piece of advice: learn Python.
Django is wonderful, but at it's root it's just Python. You'll be able to get a long way just following the documentation and tutorials you find around the web, but you won't really benefit as much as possible if you try and use your PHP idioms instead of Pythonic ones.
| Django 1.2 crash course needed | I know Python but I've never used Django.
What do I need to know about Django 1.2 to port my typical PHP CRUD web application in one weekend? (Yes I've read Joel Spolsky's Netscape article :-))
I'm reading this tutorial right now and it's excellent. I'm already playing around with inspectdb to generate my models from the existing schema.
I'm planning to use the following this weekend:
Fragment caching
Static asset versioning (for far future expires)
Schema migrations (or whatever they're called in Django)
Auto-admin (and customize it later)
The test framework
Skins
...other stuff I probably don't know about yet
I'm familiar with all these concepts in other languages/frameworks, except for the ORM which I've never used. I know SQL pretty well though.
Any links, sage bits of advice, gotchas, stuff not mentioned in the (excellent) tutorial/docs, or stuff that is mentioned but warrants repeating == very welcome. Thanks!
| [
"The django docs is very good and you should find the answers to most of your questions http://docs.djangoproject.com/en/1.2/\nYou can google it easily but make sure that you are on the doc pages of django 1.2.\nFor schema migration, I recommed to look at south http://south.aeracode.org/\nIn my opinion south is a must-have feature for a website. It is quite easy and fast to get started. The tutorial on their website should help you. I think that it will be a big help if you plan to make some schema migration in the week-end. If not you can wait a little.\nI've never used south on a db generated by inspectdb but I guess that it should work ok :)\nHave a nice week-end :)\n",
"My best piece of advice: learn Python.\nDjango is wonderful, but at it's root it's just Python. You'll be able to get a long way just following the documentation and tutorials you find around the web, but you won't really benefit as much as possible if you try and use your PHP idioms instead of Pythonic ones.\n"
] | [
2,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002879698_django_python.txt |
Q:
writing an api for python that can be installed using setup.py method
I am new at writing APIs in python, in any language for that matter. I was hoping to get pointers on how i can create an API that can be installed using setup.py method and used in other python projects. Something similar to the twitterapi.
I have already created and coded all the methods i want to include in the API. I just need to know how to implement the installation so other can use my code to leverage ideas they may have. Or if i need to format the code a certain way to facilitate installation.
I learn best with examples or tutorials.
Thanks so much.
A:
It's worth noting that this part of python is undergoing some changes right now. It's all a bit messy. The most current overview I know of is the Hitchhiker's Guide to Packaging: http://guide.python-distribute.org/
The current state of packaging section is important: http://guide.python-distribute.org/introduction.html#current-state-of-packaging
A:
The python packaging world is a mess (like poswald said). Here's a brief overview along with a bunch of pointers. Your basic problem (using setup.py etc.) is solved by reading the distutils guide which msw has mentioned in his comment.
Now for the dirt. The basic infrastructure of the distribution modules which is in the Python standard library is distutils referred to above. It's limited in some ways and so a series of extensions was written on top of it called setuptools. Setuptools along with actually increasing the functionality provided a command line "installer" called "easy_install".
Setuptools maintenance was not too great and so it was forked and a more active branch called "distribute" was setup and it is the preferred alternative right now. In addition to this, a replacement for easy_install named pip was created which was more modular and useful.
Now there's a huge project going which attempts to fold in all changes from distribute and stuff into a unified library that will go into the stdlib. It's tentatively called "distutils2".
| writing an api for python that can be installed using setup.py method | I am new at writing APIs in python, in any language for that matter. I was hoping to get pointers on how i can create an API that can be installed using setup.py method and used in other python projects. Something similar to the twitterapi.
I have already created and coded all the methods i want to include in the API. I just need to know how to implement the installation so other can use my code to leverage ideas they may have. Or if i need to format the code a certain way to facilitate installation.
I learn best with examples or tutorials.
Thanks so much.
| [
"It's worth noting that this part of python is undergoing some changes right now. It's all a bit messy. The most current overview I know of is the Hitchhiker's Guide to Packaging: http://guide.python-distribute.org/\nThe current state of packaging section is important: http://guide.python-distribute.org/introduction.html#current-state-of-packaging\n",
"The python packaging world is a mess (like poswald said). Here's a brief overview along with a bunch of pointers. Your basic problem (using setup.py etc.) is solved by reading the distutils guide which msw has mentioned in his comment.\nNow for the dirt. The basic infrastructure of the distribution modules which is in the Python standard library is distutils referred to above. It's limited in some ways and so a series of extensions was written on top of it called setuptools. Setuptools along with actually increasing the functionality provided a command line \"installer\" called \"easy_install\". \nSetuptools maintenance was not too great and so it was forked and a more active branch called \"distribute\" was setup and it is the preferred alternative right now. In addition to this, a replacement for easy_install named pip was created which was more modular and useful. \nNow there's a huge project going which attempts to fold in all changes from distribute and stuff into a unified library that will go into the stdlib. It's tentatively called \"distutils2\". \n"
] | [
1,
1
] | [] | [] | [
"api",
"django",
"python",
"setup.py",
"twitter"
] | stackoverflow_0002727348_api_django_python_setup.py_twitter.txt |
Q:
Python socket for receiving UDP packages from an FPGA
I am trying to read the UDP packages in python, which were sent from an FPGA. I see the packages in wireshark, and they look allright. Python, however does not receive anything when I use this simple script:
import socket
import sys
HOST, PORT = "192.168.1.1", 21844
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect((HOST,PORT))
received = sock.recv(1024)
A:
You don't connect with a UDP server (I assume the Python code is the server), you bind.
| Python socket for receiving UDP packages from an FPGA | I am trying to read the UDP packages in python, which were sent from an FPGA. I see the packages in wireshark, and they look allright. Python, however does not receive anything when I use this simple script:
import socket
import sys
HOST, PORT = "192.168.1.1", 21844
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect((HOST,PORT))
received = sock.recv(1024)
| [
"You don't connect with a UDP server (I assume the Python code is the server), you bind.\n"
] | [
1
] | [] | [] | [
"fpga",
"python",
"udp"
] | stackoverflow_0002881219_fpga_python_udp.txt |
Q:
How can I make list or set translatable using gettext?
I have some structure in Python:
> gender=( ('0','woman'), ('1','man') )
I want to translate it before I will display it in Django template. Unfortunately, below solution doesn't work:
> from django.utils.translation import
> ugettext_lazy as _
>
> gender=( ('0',_('woman')),
> ('1',_('man')) )
What shall I do to translate this? I read the docs, but I can't understand what I should do.
A:
Try like this:
gender=( ('0',_('woman')), ('1',_('man')) )
When you import gettext:
from django.utils.translation import ugettext_lazy as _
you need to wrap the string in gettext function:
_('some_string')
If underscore is confiusing you, this is same as writing:
from django.utils.translation import ugettext_lazy
ugettext_lazy('some_string')
but using _ is shorter.
After you have marked strings for translation call makemessages django command.
| How can I make list or set translatable using gettext? | I have some structure in Python:
> gender=( ('0','woman'), ('1','man') )
I want to translate it before I will display it in Django template. Unfortunately, below solution doesn't work:
> from django.utils.translation import
> ugettext_lazy as _
>
> gender=( ('0',_('woman')),
> ('1',_('man')) )
What shall I do to translate this? I read the docs, but I can't understand what I should do.
| [
"Try like this:\ngender=( ('0',_('woman')), ('1',_('man')) )\n\nWhen you import gettext:\nfrom django.utils.translation import ugettext_lazy as _\n\nyou need to wrap the string in gettext function:\n_('some_string')\n\nIf underscore is confiusing you, this is same as writing:\nfrom django.utils.translation import ugettext_lazy\nugettext_lazy('some_string')\n\nbut using _ is shorter.\nAfter you have marked strings for translation call makemessages django command.\n"
] | [
0
] | [] | [] | [
"django",
"gettext",
"python"
] | stackoverflow_0002881323_django_gettext_python.txt |
Q:
How to get the contents of the wav file into array so as to cut the required segment and convert it back to wav format using python?
How to get the contents of the wav file into array so as to cut the required segment and convert it back to wav format using python??
My prob is similar to "ROMANs" prob,i hav seen earlier in the post at this site..
Basically,i want to combine parts of different wav file into one wav file??
if there is ne other apporach thn takin the contents into an array and cuting part and combining and again converting bac? please suggest...
edited:
I prefer unpacking the contents of the wave file into an array and editing by cutting the required segment of sound from the wav file,as i am working on speech processing,and guess this way would be easy to enchance the quality of sound later...
can ne one suggest a way for this??
Plz help..
Thanks in advance.
A:
There are a few libraries you can use for handling media files in general, eg. pymedia. However if all you need is support for simple WAVs, you could probably just use the built-in wave module.
import wave
win= wave.open('sample.wav', 'rb')
wout= wave.open('segment.wav', 'wb')
t0, t1= 1.0, 2.0 # cut audio between one and two seconds
s0, s1= int(t0*win.getframerate()), int(t1*win.getframerate())
win.readframes(s0) # discard
frames= win.readframes(s1-s0)
wout.setparams(win.getparams())
wout.writeframes(frames)
win.close()
wout.close()
| How to get the contents of the wav file into array so as to cut the required segment and convert it back to wav format using python? | How to get the contents of the wav file into array so as to cut the required segment and convert it back to wav format using python??
My prob is similar to "ROMANs" prob,i hav seen earlier in the post at this site..
Basically,i want to combine parts of different wav file into one wav file??
if there is ne other apporach thn takin the contents into an array and cuting part and combining and again converting bac? please suggest...
edited:
I prefer unpacking the contents of the wave file into an array and editing by cutting the required segment of sound from the wav file,as i am working on speech processing,and guess this way would be easy to enchance the quality of sound later...
can ne one suggest a way for this??
Plz help..
Thanks in advance.
| [
"There are a few libraries you can use for handling media files in general, eg. pymedia. However if all you need is support for simple WAVs, you could probably just use the built-in wave module.\nimport wave\nwin= wave.open('sample.wav', 'rb')\nwout= wave.open('segment.wav', 'wb')\n\nt0, t1= 1.0, 2.0 # cut audio between one and two seconds\ns0, s1= int(t0*win.getframerate()), int(t1*win.getframerate())\nwin.readframes(s0) # discard\nframes= win.readframes(s1-s0)\n\nwout.setparams(win.getparams())\nwout.writeframes(frames)\n\nwin.close()\nwout.close()\n\n"
] | [
7
] | [] | [] | [
"audio",
"python",
"wav"
] | stackoverflow_0002881012_audio_python_wav.txt |
Q:
Python OOP and lists
I'm new to Python and it's OOP stuff and can't get it to work. Here's my code:
class Tree:
root = None;
data = [];
def __init__(self, equation):
self.root = equation;
def appendLeft(self, data):
self.data.insert(0, data);
def appendRight(self, data):
self.data.append(data);
def calculateLeft(self):
result = [];
for item in (self.getLeft()):
if (type(item) == type(self)):
data = item.calculateLeft();
else:
data = item;
result.append(item);
return result;
def getLeft(self):
return self.data;
def getRight(self):
data = self.data;
data.reverse();
return data;
tree2 = Tree("*");
tree2.appendRight(44);
tree2.appendLeft(20);
tree = Tree("+");
tree.appendRight(4);
tree.appendLeft(10);
tree.appendLeft(tree2);
print(tree.calculateLeft());
It looks like tree2 and tree are sharing list "data"?
At the moment I'd like it to output something like [[20,44], 10, 4], but when I
tree.appendLeft(tree2)
I get RuntimeError: maximum recursion depth exceeded, and when i even won't appendLeft(tree2) it outputs [10, 20, 44, 4] (!!!). What am I missing here? I'm using Portable Python 3.0.1.
Thank you
A:
The problem is that you've declared data as a class variable, so all instances of the class share the same list. Instead, put self.data = [] in your __init__.
Also, get rid of all those semicolons. They are unnecessary and clutter up your code.
A:
Move root and data into the definition of __init__ . As it stands, you have them defined as class attributes. That makes them shared among all instances of the Tree class. When you instantiate two Trees (tree and tree2), they both share the same list accessed with self.data. To make each instance have its own instance attribute, you must move the declaration into the __init__ function.
def __init__(self, equation):
self.root = equation
self.data = []
Also, use
if isinstance(item,Tree): # This is True if item is a subclass of Tree
instead of
if (type(item) == type(self)): # This is False if item is a subclass of Tree
and change
data = self.data
to
data = self.data[:]
in getRight. When you say data = self.data then the variable name data points at the very same list that self.data points at.
When you subsequently reverse data, you reverse self.data as well.
To reverse only data, you must copy the list. self.data[:] uses slicing notation to return a copy of the list. Note that the elements of self.data can be Trees, and self.data and self.data[:] can contain identical elements. I don't think your code requires these elements to be copied, but you'll need to recursively copy self.data if that is the case.
def getRight(self):
data = self.data[:]
data.reverse()
return data
A:
When you define attributes in the following way:
class Tree:
root = None
data = []
..that empty list object is created as Python defines the class, not when you create a new instance. It is a class attribute, not an instance attribute. Meaning, Tree.root is the same object in all instances:
class Tree:
root = None
data = []
t1 = Tree()
t2 = Tree()
print id(t1.data) == id(t2.data) # is True, they are the same object
To get the behaviour you expect, move the creation of the empty list to the __init__ function, which is only called when you create a new instance, and only alters that instance (as it assigns to self):
class Tree:
def __init__(self):
self.root = None
self.data = []
t1 = Tree()
t2 = Tree()
print id(t1.data) == id(t2.data) # False, they are different objects
This question explains why such behaviour can be useful
| Python OOP and lists | I'm new to Python and it's OOP stuff and can't get it to work. Here's my code:
class Tree:
root = None;
data = [];
def __init__(self, equation):
self.root = equation;
def appendLeft(self, data):
self.data.insert(0, data);
def appendRight(self, data):
self.data.append(data);
def calculateLeft(self):
result = [];
for item in (self.getLeft()):
if (type(item) == type(self)):
data = item.calculateLeft();
else:
data = item;
result.append(item);
return result;
def getLeft(self):
return self.data;
def getRight(self):
data = self.data;
data.reverse();
return data;
tree2 = Tree("*");
tree2.appendRight(44);
tree2.appendLeft(20);
tree = Tree("+");
tree.appendRight(4);
tree.appendLeft(10);
tree.appendLeft(tree2);
print(tree.calculateLeft());
It looks like tree2 and tree are sharing list "data"?
At the moment I'd like it to output something like [[20,44], 10, 4], but when I
tree.appendLeft(tree2)
I get RuntimeError: maximum recursion depth exceeded, and when i even won't appendLeft(tree2) it outputs [10, 20, 44, 4] (!!!). What am I missing here? I'm using Portable Python 3.0.1.
Thank you
| [
"The problem is that you've declared data as a class variable, so all instances of the class share the same list. Instead, put self.data = [] in your __init__.\nAlso, get rid of all those semicolons. They are unnecessary and clutter up your code.\n",
"Move root and data into the definition of __init__ . As it stands, you have them defined as class attributes. That makes them shared among all instances of the Tree class. When you instantiate two Trees (tree and tree2), they both share the same list accessed with self.data. To make each instance have its own instance attribute, you must move the declaration into the __init__ function.\ndef __init__(self, equation):\n self.root = equation\n self.data = []\n\nAlso, use \n if isinstance(item,Tree): # This is True if item is a subclass of Tree\n\ninstead of \n if (type(item) == type(self)): # This is False if item is a subclass of Tree\n\nand change \ndata = self.data\n\nto \ndata = self.data[:]\n\nin getRight. When you say data = self.data then the variable name data points at the very same list that self.data points at.\nWhen you subsequently reverse data, you reverse self.data as well.\nTo reverse only data, you must copy the list. self.data[:] uses slicing notation to return a copy of the list. Note that the elements of self.data can be Trees, and self.data and self.data[:] can contain identical elements. I don't think your code requires these elements to be copied, but you'll need to recursively copy self.data if that is the case.\ndef getRight(self):\n data = self.data[:]\n data.reverse()\n return data\n\n",
"When you define attributes in the following way:\nclass Tree:\n root = None\n data = []\n\n..that empty list object is created as Python defines the class, not when you create a new instance. It is a class attribute, not an instance attribute. Meaning, Tree.root is the same object in all instances:\nclass Tree:\n root = None\n data = []\n\nt1 = Tree()\nt2 = Tree()\n\nprint id(t1.data) == id(t2.data) # is True, they are the same object\n\nTo get the behaviour you expect, move the creation of the empty list to the __init__ function, which is only called when you create a new instance, and only alters that instance (as it assigns to self):\nclass Tree:\n def __init__(self):\n self.root = None\n self.data = []\n\nt1 = Tree()\nt2 = Tree()\n\nprint id(t1.data) == id(t2.data) # False, they are different objects\n\nThis question explains why such behaviour can be useful\n"
] | [
11,
4,
3
] | [] | [] | [
"class_variables",
"python"
] | stackoverflow_0002878499_class_variables_python.txt |
Q:
Pyinotify doesn't run with pygtk
I'm newbie in python and I'm trying to use pyinotify with a GUI interface using pygtk. I have two classes, my gtk class which doesn't do much, only displays stuff, and a class that handles the monitoring.
When I run them separately they do their work but when I try to load the gtk class from the other one, it only runs the gtk class, the monitor class only runs when I exit the GUI. If I comment the last line the monitor runs fine. I think the "myGTK.main" is blocking the whole process. Is there anything I can do?
pyinotify.ProcessEvent.__init__(self)
self.notifier = pyinotify.ThreadedNotifier(self.watch_manager, self)
self.watch_manager.add_watch('/test', pyinotify.IN_CREATE, rec=True)
self.notifier.start()
self.myGTK.main()
Thanks.
A:
Per the comments, the solution appears to be to add
gobject.threads_init()
near the top of the script. This, and other useful information about using threads with pygtk can be found in this faq.
| Pyinotify doesn't run with pygtk | I'm newbie in python and I'm trying to use pyinotify with a GUI interface using pygtk. I have two classes, my gtk class which doesn't do much, only displays stuff, and a class that handles the monitoring.
When I run them separately they do their work but when I try to load the gtk class from the other one, it only runs the gtk class, the monitor class only runs when I exit the GUI. If I comment the last line the monitor runs fine. I think the "myGTK.main" is blocking the whole process. Is there anything I can do?
pyinotify.ProcessEvent.__init__(self)
self.notifier = pyinotify.ThreadedNotifier(self.watch_manager, self)
self.watch_manager.add_watch('/test', pyinotify.IN_CREATE, rec=True)
self.notifier.start()
self.myGTK.main()
Thanks.
| [
"Per the comments, the solution appears to be to add \ngobject.threads_init()\n\nnear the top of the script. This, and other useful information about using threads with pygtk can be found in this faq.\n"
] | [
4
] | [] | [] | [
"pygtk",
"pyinotify",
"python"
] | stackoverflow_0002877124_pygtk_pyinotify_python.txt |
Q:
Task queue execution
I'm developing a site for a customer which regularly sends email notifications, to facilitate this I have a cron job which runs at 2am to start scheduling individual tasks to send out the notications. This is all fine and work perfectly with tasks being scheduled to execute immediately, but to assist development and testing I've written some CLI apps which use ipython and the remote_api_stub to interact with my application and datastore, when I schedule tasks on the command line like this:
task = taskqueue.Task(url='/admin/tasks/email', params={'email': email, 'type': notif.type})
task.add("email")
I get a 1 hour delay on the task execution. Why is this? and is there a way to get the task to execute immediately?
A:
There seems to be a timezone-related bug in the SDK that causes the eta for tasks created through the remote API to be scheduled one hour after they're added. If you explicitly set the countdown to 0, the task should be scheduled to run immediately.
A:
If you want it to execute immediately, just open the URL in a browser. Why muck around with Task queues?
| Task queue execution | I'm developing a site for a customer which regularly sends email notifications, to facilitate this I have a cron job which runs at 2am to start scheduling individual tasks to send out the notications. This is all fine and work perfectly with tasks being scheduled to execute immediately, but to assist development and testing I've written some CLI apps which use ipython and the remote_api_stub to interact with my application and datastore, when I schedule tasks on the command line like this:
task = taskqueue.Task(url='/admin/tasks/email', params={'email': email, 'type': notif.type})
task.add("email")
I get a 1 hour delay on the task execution. Why is this? and is there a way to get the task to execute immediately?
| [
"There seems to be a timezone-related bug in the SDK that causes the eta for tasks created through the remote API to be scheduled one hour after they're added. If you explicitly set the countdown to 0, the task should be scheduled to run immediately. \n",
"If you want it to execute immediately, just open the URL in a browser. Why muck around with Task queues?\n"
] | [
3,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002880573_google_app_engine_python.txt |
Q:
getting expat to use .dtd for entity replacement in python
I'm trying to read in an xml file which looks like this
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
<incollection>
<author>José A. Blakeley</author>
</incollection>
</dblp>
The point that creates the problem looks is the
José A. Blakeley
part: The parser calls its character handler twice, once with "Jos", once with " A. Blakeley".
Now I understand this may be the correct behaviour if it doesn't know the eacute entity. However, this is defined in the dblp.dtd, which I have. I don't seem to be able to convince expat to use this file, though. All I can say is
p = xml.parsers.expat.ParserCreate()
# tried with and without following line
p.SetParamEntityParsing(xml.parsers.expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
p.UseForeignDTD(True)
f = open(dblp_file, "r")
p.ParseFile(f)
but expat still doesn't recognize my entity. Why is there no way to tell expat which DTD to use? I've tried
putting the file into the same directory as the XML
putting the file into the program's working directory
replacing the reference in the xml file by an absolute path
What am I missing? Thx.
A:
As I understand it, if you're using pyexpat directly, then you have to provide your own ExternalEntityRefHandler to fetch the external DTD and feed it to expat.
See eg. xml.sax.expatreader for example code (method external_entity_ref, line 374 in Python 2.6).
It would probably be better to use a higher-level interface such as SAX (via expatreader) if you can.
A:
btw I can temporarily help myself by copying the relevant parts of the .dtd into the XML file itself, as in
<!DOCTYPE dblp [
<!ENTITY Agrave "À" >
]>
but that doesn't really solve the problem in a general way.
| getting expat to use .dtd for entity replacement in python | I'm trying to read in an xml file which looks like this
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
<incollection>
<author>José A. Blakeley</author>
</incollection>
</dblp>
The point that creates the problem looks is the
José A. Blakeley
part: The parser calls its character handler twice, once with "Jos", once with " A. Blakeley".
Now I understand this may be the correct behaviour if it doesn't know the eacute entity. However, this is defined in the dblp.dtd, which I have. I don't seem to be able to convince expat to use this file, though. All I can say is
p = xml.parsers.expat.ParserCreate()
# tried with and without following line
p.SetParamEntityParsing(xml.parsers.expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
p.UseForeignDTD(True)
f = open(dblp_file, "r")
p.ParseFile(f)
but expat still doesn't recognize my entity. Why is there no way to tell expat which DTD to use? I've tried
putting the file into the same directory as the XML
putting the file into the program's working directory
replacing the reference in the xml file by an absolute path
What am I missing? Thx.
| [
"As I understand it, if you're using pyexpat directly, then you have to provide your own ExternalEntityRefHandler to fetch the external DTD and feed it to expat.\nSee eg. xml.sax.expatreader for example code (method external_entity_ref, line 374 in Python 2.6).\nIt would probably be better to use a higher-level interface such as SAX (via expatreader) if you can.\n",
"btw I can temporarily help myself by copying the relevant parts of the .dtd into the XML file itself, as in \n<!DOCTYPE dblp [\n <!ENTITY Agrave \"À\" >\n]>\n\nbut that doesn't really solve the problem in a general way.\n"
] | [
1,
0
] | [] | [] | [
"dtd",
"entity",
"expat_parser",
"python",
"xml"
] | stackoverflow_0002881991_dtd_entity_expat_parser_python_xml.txt |
Q:
How to write a custom solution using a python package, modules etc
I am writing a packacge foobar which consists of the modules alice, bob, charles and david.
From my understanding of Python packages and modules, this means I will create a folder foobar, with the following subdirectories and files (please correct if I am wrong)
foobar/
__init__.py
alice/alice.py
bob/bob.py
charles/charles.py
david/david.py
The package should be executable, so that in addition to making the modules alice, bob etc available as 'libraries', I should also be able to use foobar in a script like this:
python foobar --args=someargs
Question1:
Can a package be made executable and used in a script like I described above?
Question 2
The various modules will use code that I want to refactor into a common library. Does that mean creating a new sub directory 'foobar/common' and placing common.py in that folder?
Question 3
How will the modules foo import the common module ?
Is it 'from foobar import common' or can I not use this since these modules are part of the package?
Question 4
I want to add logic for when the foobar package is being used in a script (assuming this can be done - I have only seen it done for modules)
The code used is something like:
if __name__ == "__main__":
dosomething()
where (in which file) would I put this logic ?
A:
Can a package be made executable and
used in a script like I described
above?
Q1 and Q4. Yes, place your:
if __name__ == "__main__":
dosomething()
in foobar/__init__.py
Q2 The various modules will use code that
I want to refactor into a common
library. Does that mean creating a new
sub directory 'foobar/common' and
placing common.py in that folder?
No, you have to create foobar/common.py, not foobar/common/common.py. The same is true for all of your modules. Thus the right structure is:
foobar/
__init__.py
alice.py
bob.py
charles.py
common.py
david.py
Doing what you do you're creating package foobar, subpackage alice and module alice in it, etc. That is not what you want as I understand. Furthermore it will not work at all, since a directory becomes a Python package if it contains __init__.py in it, and you haven't created them in your subdirectories.
Q3 How will the modules foo import the
common module ? Is it from foobar
import common
That's right. You can also simply use import common however it can cause a conflict if your library will be used in a project that has it's own module/package named common. So I prefer to use fully-qualified module names.
| How to write a custom solution using a python package, modules etc | I am writing a packacge foobar which consists of the modules alice, bob, charles and david.
From my understanding of Python packages and modules, this means I will create a folder foobar, with the following subdirectories and files (please correct if I am wrong)
foobar/
__init__.py
alice/alice.py
bob/bob.py
charles/charles.py
david/david.py
The package should be executable, so that in addition to making the modules alice, bob etc available as 'libraries', I should also be able to use foobar in a script like this:
python foobar --args=someargs
Question1:
Can a package be made executable and used in a script like I described above?
Question 2
The various modules will use code that I want to refactor into a common library. Does that mean creating a new sub directory 'foobar/common' and placing common.py in that folder?
Question 3
How will the modules foo import the common module ?
Is it 'from foobar import common' or can I not use this since these modules are part of the package?
Question 4
I want to add logic for when the foobar package is being used in a script (assuming this can be done - I have only seen it done for modules)
The code used is something like:
if __name__ == "__main__":
dosomething()
where (in which file) would I put this logic ?
| [
"\nCan a package be made executable and\n used in a script like I described\n above?\n\nQ1 and Q4. Yes, place your:\nif __name__ == \"__main__\":\n dosomething()\n\nin foobar/__init__.py\n\nQ2 The various modules will use code that\n I want to refactor into a common\n library. Does that mean creating a new\n sub directory 'foobar/common' and\n placing common.py in that folder?\n\nNo, you have to create foobar/common.py, not foobar/common/common.py. The same is true for all of your modules. Thus the right structure is:\nfoobar/\n __init__.py\n alice.py\n bob.py\n charles.py\n common.py\n david.py\n\nDoing what you do you're creating package foobar, subpackage alice and module alice in it, etc. That is not what you want as I understand. Furthermore it will not work at all, since a directory becomes a Python package if it contains __init__.py in it, and you haven't created them in your subdirectories.\n\nQ3 How will the modules foo import the\n common module ? Is it from foobar\n import common\n\nThat's right. You can also simply use import common however it can cause a conflict if your library will be used in a project that has it's own module/package named common. So I prefer to use fully-qualified module names.\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0002882173_python.txt |
Q:
bundles in java?
in symfony 2.0 and django there are bundles that contain everything for a feature (html, css, js, img, php/python).
so if you want to delete one feature, you basically just delete that bundle and unregister it from "main".
are there java frameworks for this too? or is it different in java cause java is a compiling language.
thanks
A:
Are osgi-bundles what you search ?
http://en.wikipedia.org/wiki/OSGi
A:
I suppose the closest thing in Javaland is the venerable Web Application Archive (war file).
A:
In Java, libraries and programs are normally packaged in JAR files. Java does not have its own package management system to install or remove features. Web applications are packaged in WAR files, which are just JAR files with a specific layout.
This has nothing to do with Java being a compiled language.
| bundles in java? | in symfony 2.0 and django there are bundles that contain everything for a feature (html, css, js, img, php/python).
so if you want to delete one feature, you basically just delete that bundle and unregister it from "main".
are there java frameworks for this too? or is it different in java cause java is a compiling language.
thanks
| [
"Are osgi-bundles what you search ?\nhttp://en.wikipedia.org/wiki/OSGi\n",
"I suppose the closest thing in Javaland is the venerable Web Application Archive (war file).\n",
"In Java, libraries and programs are normally packaged in JAR files. Java does not have its own package management system to install or remove features. Web applications are packaged in WAR files, which are just JAR files with a specific layout.\nThis has nothing to do with Java being a compiled language.\n"
] | [
1,
1,
1
] | [] | [] | [
"django",
"java",
"php",
"python",
"symfony1"
] | stackoverflow_0002881825_django_java_php_python_symfony1.txt |
Q:
httplib2, how to set more than one cookie?
As you are probably aware, more often than not, an HTTP server will send more than just a session_id cookie; however, httplib2 handles cookies with a dictionary, like this:
response, content = http.request(url, 'GET', headers=headers)
headers = {'Cookie': response['set-cookie']}
url = 'http://www.example.com/home'
response, content = http.request(url, 'GET', headers=headers)
So, how do I set the extra cookies? If handled with a dictionary, I can't have double Cookie keys :S.
Thanks for your time.
A:
Cookies are contained in a single HTTP header, separated by semicolons. Example:
cookie1=value1;cookie2=value2
So you'll need to build a string from the cookies sent by the server, and then set that as the Cookie header.
Edit: Actually, playing around a bit with httplib2 and re-reading your question, I'm not sure you actually need to do anything to get the functionality you want. The set-cookie value you get back from httplib2 is actually the raw Set-Cookie header sent from the server; you can just put that into the cookie header of the new response, and everything will work fine. Technically speaking you should remove some cookie attributes such as expiry, but I imagine most servers will handle that just fine.
A:
Yes, I just found out elsewhere about the Cookie header when making the request, but the server may send several Set-Cookie headers, with a cookie(and expiration,domain,etc attributes) per header. But with the dictionary system used in httplib2, I can't really get all the possible Set-Cookie headers sent by the server, but seemingly, just the last one.
So, any more ideas :)?
A:
Doing some extra testing, with a dummy setcookie() PHP page, I generated in 3 test, the following set of headers:
Set-Cookie: chocolate=chips
Set-Cookie: milk=shape
Set-Cookie: chocolate=chips; expires=Sun, 15-Nov-2009 18:47:08 GMT; path=/; domain=thaorius.net; secure; httponly
Set-Cookie: milk=shape
Set-Cookie: chocolate=chips; expires=Sun, 15-Nov-2009 18:46:25 GMT
Set-Cookie: milk=shape
The output actually supplied by httplib2 on the set-cookie key of the array, is, respectively for each header pair, this:
chocolate=chips, milk=shape
chocolate=chips; expires=Sun, 15-Nov-2009 18:31:00 GMT; path=/; domain=thaorius.net; secure; httponly, milk=shape
chocolate=chips; expires=Sun, 15-Nov-2009 18:38:21 GMT, milk=shape
So it seems that httplib2 does deal with the problem properly, but now I'm presented with another problem. The "," in the expires attribute. As you can see, cookies get separated by a comma, but how to distinguish from that of the expires attribute.
I could split the string by commas, and then by ";", and end up with key value pairs for each cookie, nice and easy; but with the comma in expires, I can't possibly do that.
So, I'm thinking, I could use a regular expression that basically looks for "expires=letters, num&letters nums:nums:nums arbitrarychars[,|;|$]" and replaces it for something like expires=STUB, as I do not really care about the expiration time of the cookies.
So, would anyone be so kind as to give me the regex I can feed to re.sub()? I haven't really needed regex so far, thus I haven't learned them, and I really don't want to loose a few days for a single one :).
| httplib2, how to set more than one cookie? | As you are probably aware, more often than not, an HTTP server will send more than just a session_id cookie; however, httplib2 handles cookies with a dictionary, like this:
response, content = http.request(url, 'GET', headers=headers)
headers = {'Cookie': response['set-cookie']}
url = 'http://www.example.com/home'
response, content = http.request(url, 'GET', headers=headers)
So, how do I set the extra cookies? If handled with a dictionary, I can't have double Cookie keys :S.
Thanks for your time.
| [
"Cookies are contained in a single HTTP header, separated by semicolons. Example:\ncookie1=value1;cookie2=value2\n\nSo you'll need to build a string from the cookies sent by the server, and then set that as the Cookie header.\nEdit: Actually, playing around a bit with httplib2 and re-reading your question, I'm not sure you actually need to do anything to get the functionality you want. The set-cookie value you get back from httplib2 is actually the raw Set-Cookie header sent from the server; you can just put that into the cookie header of the new response, and everything will work fine. Technically speaking you should remove some cookie attributes such as expiry, but I imagine most servers will handle that just fine.\n",
"Yes, I just found out elsewhere about the Cookie header when making the request, but the server may send several Set-Cookie headers, with a cookie(and expiration,domain,etc attributes) per header. But with the dictionary system used in httplib2, I can't really get all the possible Set-Cookie headers sent by the server, but seemingly, just the last one.\nSo, any more ideas :)?\n",
"Doing some extra testing, with a dummy setcookie() PHP page, I generated in 3 test, the following set of headers:\nSet-Cookie: chocolate=chips\nSet-Cookie: milk=shape\n\n\nSet-Cookie: chocolate=chips; expires=Sun, 15-Nov-2009 18:47:08 GMT; path=/; domain=thaorius.net; secure; httponly\nSet-Cookie: milk=shape\n\n\nSet-Cookie: chocolate=chips; expires=Sun, 15-Nov-2009 18:46:25 GMT\nSet-Cookie: milk=shape\n\nThe output actually supplied by httplib2 on the set-cookie key of the array, is, respectively for each header pair, this:\nchocolate=chips, milk=shape\n\nchocolate=chips; expires=Sun, 15-Nov-2009 18:31:00 GMT; path=/; domain=thaorius.net; secure; httponly, milk=shape\n\nchocolate=chips; expires=Sun, 15-Nov-2009 18:38:21 GMT, milk=shape\n\nSo it seems that httplib2 does deal with the problem properly, but now I'm presented with another problem. The \",\" in the expires attribute. As you can see, cookies get separated by a comma, but how to distinguish from that of the expires attribute.\nI could split the string by commas, and then by \";\", and end up with key value pairs for each cookie, nice and easy; but with the comma in expires, I can't possibly do that.\nSo, I'm thinking, I could use a regular expression that basically looks for \"expires=letters, num&letters nums:nums:nums arbitrarychars[,|;|$]\" and replaces it for something like expires=STUB, as I do not really care about the expiration time of the cookies.\nSo, would anyone be so kind as to give me the regex I can feed to re.sub()? I haven't really needed regex so far, thus I haven't learned them, and I really don't want to loose a few days for a single one :).\n"
] | [
5,
3,
2
] | [
"Try this:\npp = re.compile('(Sun|Mon|Tue|Wed|Thu|Fri|Sat),')\npp.sub('','alpha Sun, beta')\n'alpha beta'\n\n"
] | [
-2
] | [
"cookiejar",
"cookies",
"httplib2",
"python"
] | stackoverflow_0001738227_cookiejar_cookies_httplib2_python.txt |
Q:
PyArg_ParseTuple plus cast
I have a c function being called from python. Python gives the function an integer, but I would like to use it as another data type in C. I am currently using
PyArg_ParseTuple (args, "i", &value) and then manually doing a cast on value.
Is there a way to do this cast through PyArg?
A:
Which data type are you trying to cast the argument to in C?
If you want an integer type, it looks like you might be able to get it by using a different format string in PyArg_ParseType(). For example, "b" converts a non-negative Python integer into an unsigned char.
unsigned char value;
PyArg_ParseTuple (args, "b", &value)
If you want something that isn't an integer type, you may be able to change the Python object type that is passed to your function, and then use the appropriate format string to get the end result you want.
| PyArg_ParseTuple plus cast | I have a c function being called from python. Python gives the function an integer, but I would like to use it as another data type in C. I am currently using
PyArg_ParseTuple (args, "i", &value) and then manually doing a cast on value.
Is there a way to do this cast through PyArg?
| [
"Which data type are you trying to cast the argument to in C?\nIf you want an integer type, it looks like you might be able to get it by using a different format string in PyArg_ParseType(). For example, \"b\" converts a non-negative Python integer into an unsigned char.\nunsigned char value;\nPyArg_ParseTuple (args, \"b\", &value)\n\nIf you want something that isn't an integer type, you may be able to change the Python object type that is passed to your function, and then use the appropriate format string to get the end result you want.\n"
] | [
0
] | [] | [] | [
"binding",
"c",
"casting",
"python"
] | stackoverflow_0002876283_binding_c_casting_python.txt |
Q:
Identifying if a data is RSS or HTML on python
Is there a function or method I could call in Python
That would tell me if the data is RSS or HTML?
A:
You could always analyze it yourself to search for an xml tag (for RSS) or html tag (for HTML).
A:
Filetypes should generally be determined out-of-band. eg. if you are fetching the file from a web server, the place to look would be the Content-Type header of the HTTP response. If you're fetching a local file, the filesystem would have a way of determining filetype—on Windows that'd be looking at the file extension.
If none of that is available, you'd have to resort to content sniffing. This is never wholly reliable, and RSS is particularly annoying because there are multiple incompatible versions of it, but about the best you could do would probably be:
Attempt to parse the content with an XML parser. If it fails, the content isn't well-formed XML so can't be RSS.
Look at the document.documentElement.namespaceURI. If it's http://www.w3.org/1999/xhtml, you've got XHTML. If it's http://www.w3.org/1999/02/22-rdf-syntax-ns#, you've got RSS (of one flavour).
If the document.documentElement.tagName is rss, you've got RSS (of a slightly different flavour).
If the file couldn't be parsed as XML, it could well be HTML (or some tag-soup approximation of it). It's conceivable it might also be broken RSS. In that case most feed tools would reject it. If you need to still detect this case you'd be reduced to looking for strings like <html or <rss or <rdf:RSS near the start of the file. This would be even more unreliable.
| Identifying if a data is RSS or HTML on python | Is there a function or method I could call in Python
That would tell me if the data is RSS or HTML?
| [
"You could always analyze it yourself to search for an xml tag (for RSS) or html tag (for HTML).\n",
"Filetypes should generally be determined out-of-band. eg. if you are fetching the file from a web server, the place to look would be the Content-Type header of the HTTP response. If you're fetching a local file, the filesystem would have a way of determining filetype—on Windows that'd be looking at the file extension.\nIf none of that is available, you'd have to resort to content sniffing. This is never wholly reliable, and RSS is particularly annoying because there are multiple incompatible versions of it, but about the best you could do would probably be:\n\nAttempt to parse the content with an XML parser. If it fails, the content isn't well-formed XML so can't be RSS.\nLook at the document.documentElement.namespaceURI. If it's http://www.w3.org/1999/xhtml, you've got XHTML. If it's http://www.w3.org/1999/02/22-rdf-syntax-ns#, you've got RSS (of one flavour).\nIf the document.documentElement.tagName is rss, you've got RSS (of a slightly different flavour).\n\nIf the file couldn't be parsed as XML, it could well be HTML (or some tag-soup approximation of it). It's conceivable it might also be broken RSS. In that case most feed tools would reject it. If you need to still detect this case you'd be reduced to looking for strings like <html or <rss or <rdf:RSS near the start of the file. This would be even more unreliable.\n"
] | [
2,
0
] | [] | [] | [
"html",
"python",
"rss"
] | stackoverflow_0002882549_html_python_rss.txt |
Q:
Java/Python: Integration, problem with looping updating text
Basically I have a script in Python that grabs the text from an open window using getWindowText() and outputs it to the screen. The python loops so as the text in the window changes, it outputs the changes, so the output of the python will always be up to date with the window text.
I'm trying to access this text in my Java program by executing the python script as a process and reading the text it outputs using a buffered reader.
For some reason this works fine for the first block of text, but will not read any more after this, it wont read any updates to the text as the python outputs it.
Can someone shed some light on this? I'm about to try and use Jython, but I'd really like to know what the problem is here...
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec("cmd /c getText.py");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
int line;
while (true) {
line = br.read();
System.out.print((char) line);
}
} catch (Exception e) {
e.printStackTrace();
}
A:
I think I was able to reproduce your error by writing a simple python program to print random numbers and then sleep:
import random
import time
import sys
random.seed(time.time())
print 'starting random numbers'
#sys.stdout.flush()
print 'big block of text' * 2000
#sys.stdout.flush()
count = 3
while count > 0:
sleeper = random.randint(1, 5)
r = random.randint(1000, 9000)
print r, 'sleeping for', sleeper, 'seconds'
#sys.stdout.flush()
time.sleep(sleeper)
count -= 1
print 'random numbers finished, closing'
#sys.stdout.flush()
The interesting bit here is that the java code will echo the first few prints but will then wait until the program is finished before it prints the rest. The problem with this example code is that the output from the Python script is buffered in stdout so the Java app can't read it. It works correctly when you uncomment the sys.stdout.flush() commands.
I would try adding a flush() to your python program and see if that fixes the issue.
| Java/Python: Integration, problem with looping updating text | Basically I have a script in Python that grabs the text from an open window using getWindowText() and outputs it to the screen. The python loops so as the text in the window changes, it outputs the changes, so the output of the python will always be up to date with the window text.
I'm trying to access this text in my Java program by executing the python script as a process and reading the text it outputs using a buffered reader.
For some reason this works fine for the first block of text, but will not read any more after this, it wont read any updates to the text as the python outputs it.
Can someone shed some light on this? I'm about to try and use Jython, but I'd really like to know what the problem is here...
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec("cmd /c getText.py");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
int line;
while (true) {
line = br.read();
System.out.print((char) line);
}
} catch (Exception e) {
e.printStackTrace();
}
| [
"I think I was able to reproduce your error by writing a simple python program to print random numbers and then sleep:\nimport random\nimport time\nimport sys\n\nrandom.seed(time.time())\n\nprint 'starting random numbers'\n#sys.stdout.flush()\nprint 'big block of text' * 2000\n#sys.stdout.flush()\n\ncount = 3\n\nwhile count > 0:\n sleeper = random.randint(1, 5)\n r = random.randint(1000, 9000)\n print r, 'sleeping for', sleeper, 'seconds'\n #sys.stdout.flush()\n time.sleep(sleeper)\n count -= 1\n\nprint 'random numbers finished, closing'\n#sys.stdout.flush()\n\nThe interesting bit here is that the java code will echo the first few prints but will then wait until the program is finished before it prints the rest. The problem with this example code is that the output from the Python script is buffered in stdout so the Java app can't read it. It works correctly when you uncomment the sys.stdout.flush() commands.\nI would try adding a flush() to your python program and see if that fixes the issue.\n"
] | [
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0002780038_java_python.txt |
Q:
Emacs/Python: running python-shell in line buffered vs. block buffered mode
In a related question and answer here, someone hypothesized that python-shell within emacs(23.2) was block-buffered instead of line-buffered. The recommended fix was to add sys.stdout.flush() to the spot in my script where I want stdio to flush its contents to the python-shell.
Is there someway to trick python-shell (running in emacs 23.2 on Windows, not Linux) into either a) thinking it's attached to a TTY or b) using line-buffered instead of block-buffered mode? I don't see why I'd be able to do this in IDLE but not emacs.
I'd rather customize emacs than add sys.stdout.flush() throughout my scripts. Call me lazy :-).
Thanks,
Mike
A:
For those wondering, I think the relevant behavior is discussed here, in emacs "7. Subprocesses\ 7.3 Buffering in shells and subprocesses".
"In a shell buffer, stdout is a pipe handle and so is buffered in blocks. If you would like the buffering behavior of your program to behave differently, the program itself is going to have to be changed; you can use setbuf and setvbuf to manipulate the buffering semantics."
Solved by adding the following to my init.el (see this SO link here for more detail):
(setenv "PYTHONUNBUFFERED" "x")
| Emacs/Python: running python-shell in line buffered vs. block buffered mode | In a related question and answer here, someone hypothesized that python-shell within emacs(23.2) was block-buffered instead of line-buffered. The recommended fix was to add sys.stdout.flush() to the spot in my script where I want stdio to flush its contents to the python-shell.
Is there someway to trick python-shell (running in emacs 23.2 on Windows, not Linux) into either a) thinking it's attached to a TTY or b) using line-buffered instead of block-buffered mode? I don't see why I'd be able to do this in IDLE but not emacs.
I'd rather customize emacs than add sys.stdout.flush() throughout my scripts. Call me lazy :-).
Thanks,
Mike
| [
"For those wondering, I think the relevant behavior is discussed here, in emacs \"7. Subprocesses\\ 7.3 Buffering in shells and subprocesses\".\n\"In a shell buffer, stdout is a pipe handle and so is buffered in blocks. If you would like the buffering behavior of your program to behave differently, the program itself is going to have to be changed; you can use setbuf and setvbuf to manipulate the buffering semantics.\"\nSolved by adding the following to my init.el (see this SO link here for more detail):\n(setenv \"PYTHONUNBUFFERED\" \"x\")\n\n"
] | [
4
] | [] | [] | [
"emacs",
"output_buffering",
"python"
] | stackoverflow_0002881346_emacs_output_buffering_python.txt |
Q:
Interpreted vs. Compiled vs. Late-Binding
Python is compiled into an intermediate bytecode(pyc) and then executed. So, there is a compilation followed by interpretation. However, long-time Python users say that Python is a "late-binding" language and that it should`nt be referred to as an interpreted language.
How would Python be different from another interpreted language?
Could you tell me what "late-binding" means, in the Python context?
Java is another language which first has source code compiled into bytecode and then interpreted into bytecode.
Is Java an interpreted/compiled language?
How is it different from Python in terms of compilation/execution?
Java is said to not have, "late-binding". Does this have anything to do with Java programs being slighly faster than Python?
It'd be great if you could also give me links to places where people have already discussed this; i'd love to read more on this. Thank you.
A:
How would Python be different from another interpreted language?
That involves hair-splitting. Interpreted languages and "managed code" languages like C# and virtual machine languages (like Java) form a weird continuum. There are folks who will say that all languages are "interpreted" -- even machine language. After all, the electronic circuits of the CPU "interpret" machine language.
The best you can do is say that "interpreted" means there's a visible layer of software interpreting your application byte-codes. "not-interpreted" means that your software is (more-or-less) directly executed by the underlying hardware. "Managed code" people are free to continue to split this hair.
Could you tell me what "late-binding" means, in the Python context?
Variables are not declared to have a type. The variable is bound to a type as late as possible -- with the assignment of an actual object.
Is Java an interpreted/compiled language?
Yes. It's compiled to byte codes. The byte codes are interpreted. I prefer to call it interpreted.
However, people will (for really obscure reasons) disagree. The presence of any kind of "compile" step -- however minimal -- always confuses people. The translation to byte code has almost no relevance to the actual behavior of the program at run time. Some folks like to say that only languages that are totally free from any taint of pre-processing "compilation" can be interpreted. There aren't a lot of examples of this any more, since many languages are translated from human-friendly text to interpreter friendly byte codes. Even Applesoft Basic (back in the 80's) had this kind of translation pass done as you typed code in.
Some JVM's do JIT. Some don't. Some are a mixture. To say that the JVM only does JIT byte-code translation is incorrect. Some JVM's do. Some don't.
How is it different from Python in terms of compilation/execution?
Not at all. The Java VM can execute Python. [For the easily-confused, the word "python" in this context cannot possibly mean "python source". It must mean python bytecode.]
Java is said to not have, "late-binding". Does this have anything to do with Java programs being slighly faster than Python?
Perhaps. Java programs are often faster because of JIT compilers that translate Java byte code to machine code at run-time.
Static ("early") binding doesn't have the same kind of benefit for Java that it has with a truly compiled language like C or C++ where there are almost no run-time checks of any kind. Java still does things like array bounds checking, which C omits in the interest of raw speed.
There is actually little penalty for "late" binding. Python attributes and methods are resolved using simple dictionary lookups. The dictionary is a hash; performance is quite good. The hashes for names can be put into an "interned" string literal pool amortizing the cost of computing the hash.
For real fun, look PyPy and RPython. This is a Python interpreter that can do JIT compilation. You wind up with a 2-tier interpreter. Your code is interpreted by PyPy. PyPy is interpreted by RPython. http://alexgaynor.net/2010/may/15/pypy-future-python/
A:
Late binding is a very different concept to interpretation.
Strictly speaking, an interpreted language is executed directly from source. It doesn't go through a byte-code compilation stage. The confusion arises because the python program is an interpreter, but it interprets the byte-code, so it is Python's byte-code language that you would describe as "interpreted". The Python language itself is a compiled language.
Java bytecode, in contrast, is both interpreted and compiled, these days. It is compiled into native code by a JIT-compiler and then run directly on the hardware.
Late binding is a property of the type system and is present in most languages to some degree, regardless of whether they are interpreted or compiled.
A:
There's a connection between what we call the binding time and the concept of interpretation/compilation.
The binding time is the time when a symbolic expression is bound to its concrete value. That's more related to the definition of programming language, e.g. dynamic vs. static scoping of variables. Or static method vs. virtual methods or dynamic typing vs. static typing.
Then comes the implementation of the language. The more information are statically known upfront, the easier it is to write a compiler. Inversely, the more late bound the language is, the harder it is. Hence the need to rely on interpretive techniques sometimes.
The distinction between both isn't strict however. Not only can we consider that everything is ultimately interpreted (see S.Lott answer), but part of the code can be compiled, decompile, or recompile dynamically (e.g. JIT) making the distinction very fuzzy.
For instance, dynamic class loading in Java goes in the category "late binding": the set of class is not fixed once for all, and classes can be loaded dynamically. Some optimizations can be done when we know the set of classes, but will need to be invalidated once a new classes is loaded. The same happens with the ability to update a method with the debugging infrastructure: the JVM will need to de-optimize all call sites were the method had been inlined.
I don't know much about Python, but Python practitioners prefer maybe the term "late bound" to avoid such confusion.
A:
I think the common misconception that Python is interpreted while Java is compiled arises because Java has an explicit compilation step - you have to run javac to convert your .java source file into a .class bytecode file that can be run.
As you rightly point out Python similarly compiles source files into bytecode but it does it transparently - compiling and running is generally done in a single step so it is less obvious to the user.
The important difference is between early & late binding and dynamic & static typing. The compiled/interpreted distinction is meaningless and irrelevant.
A:
binding time is when names get resolved to things.
More dynamic languages tend towards late binding.
This can be separate from interpretation/compilation -- for example,
objective-C methods are resolved late and dynamically compared to C++.
Java does much of it's binding at class load time : later than C but
earlier than Python.
my favorite quote from Stan Kelly-Bootle's Computer Contradictionary:
binding time n. The moment when the hash table becomes corrupted.
==> Advances in computing can be mapped against the "lateness of binding," which has me thinking about my own so-called CS so-called career: golden past, gray present, and rosy future. This is my version of Synge's optimism: the grass is greener except at t=0. On EDSAC I, my functions (5ch paper-tape subroutines) were punched, spliced, and bound about two weeks before input. This is known aspremature binding and calls for deftness with elastic bands. FORTRAN came next with a new kind of binding: soggy decks of cards that refused to be shuffled. Then with Algol and C, I enjoyed static (compile-time) binding, until C++ brought the numbing joys of dynamic (run-time) binding. My current research aims at delaying the binding until well after execution. I call this end-time binding, as prophesied in St. Matthew's Gospel: "...and whatsoever thou shalt bind on earth shall be bound in heaven..." (Matthew 16:19 KJV).
| Interpreted vs. Compiled vs. Late-Binding | Python is compiled into an intermediate bytecode(pyc) and then executed. So, there is a compilation followed by interpretation. However, long-time Python users say that Python is a "late-binding" language and that it should`nt be referred to as an interpreted language.
How would Python be different from another interpreted language?
Could you tell me what "late-binding" means, in the Python context?
Java is another language which first has source code compiled into bytecode and then interpreted into bytecode.
Is Java an interpreted/compiled language?
How is it different from Python in terms of compilation/execution?
Java is said to not have, "late-binding". Does this have anything to do with Java programs being slighly faster than Python?
It'd be great if you could also give me links to places where people have already discussed this; i'd love to read more on this. Thank you.
| [
"\nHow would Python be different from another interpreted language?\n\nThat involves hair-splitting. Interpreted languages and \"managed code\" languages like C# and virtual machine languages (like Java) form a weird continuum. There are folks who will say that all languages are \"interpreted\" -- even machine language. After all, the electronic circuits of the CPU \"interpret\" machine language.\nThe best you can do is say that \"interpreted\" means there's a visible layer of software interpreting your application byte-codes. \"not-interpreted\" means that your software is (more-or-less) directly executed by the underlying hardware. \"Managed code\" people are free to continue to split this hair.\n\nCould you tell me what \"late-binding\" means, in the Python context?\n\nVariables are not declared to have a type. The variable is bound to a type as late as possible -- with the assignment of an actual object.\n\nIs Java an interpreted/compiled language?\n\nYes. It's compiled to byte codes. The byte codes are interpreted. I prefer to call it interpreted. \nHowever, people will (for really obscure reasons) disagree. The presence of any kind of \"compile\" step -- however minimal -- always confuses people. The translation to byte code has almost no relevance to the actual behavior of the program at run time. Some folks like to say that only languages that are totally free from any taint of pre-processing \"compilation\" can be interpreted. There aren't a lot of examples of this any more, since many languages are translated from human-friendly text to interpreter friendly byte codes. Even Applesoft Basic (back in the 80's) had this kind of translation pass done as you typed code in.\nSome JVM's do JIT. Some don't. Some are a mixture. To say that the JVM only does JIT byte-code translation is incorrect. Some JVM's do. Some don't.\n\nHow is it different from Python in terms of compilation/execution?\n\nNot at all. The Java VM can execute Python. [For the easily-confused, the word \"python\" in this context cannot possibly mean \"python source\". It must mean python bytecode.]\n\nJava is said to not have, \"late-binding\". Does this have anything to do with Java programs being slighly faster than Python?\n\nPerhaps. Java programs are often faster because of JIT compilers that translate Java byte code to machine code at run-time.\nStatic (\"early\") binding doesn't have the same kind of benefit for Java that it has with a truly compiled language like C or C++ where there are almost no run-time checks of any kind. Java still does things like array bounds checking, which C omits in the interest of raw speed.\nThere is actually little penalty for \"late\" binding. Python attributes and methods are resolved using simple dictionary lookups. The dictionary is a hash; performance is quite good. The hashes for names can be put into an \"interned\" string literal pool amortizing the cost of computing the hash.\nFor real fun, look PyPy and RPython. This is a Python interpreter that can do JIT compilation. You wind up with a 2-tier interpreter. Your code is interpreted by PyPy. PyPy is interpreted by RPython. http://alexgaynor.net/2010/may/15/pypy-future-python/\n",
"Late binding is a very different concept to interpretation.\nStrictly speaking, an interpreted language is executed directly from source. It doesn't go through a byte-code compilation stage. The confusion arises because the python program is an interpreter, but it interprets the byte-code, so it is Python's byte-code language that you would describe as \"interpreted\". The Python language itself is a compiled language.\nJava bytecode, in contrast, is both interpreted and compiled, these days. It is compiled into native code by a JIT-compiler and then run directly on the hardware.\nLate binding is a property of the type system and is present in most languages to some degree, regardless of whether they are interpreted or compiled.\n",
"There's a connection between what we call the binding time and the concept of interpretation/compilation.\nThe binding time is the time when a symbolic expression is bound to its concrete value. That's more related to the definition of programming language, e.g. dynamic vs. static scoping of variables. Or static method vs. virtual methods or dynamic typing vs. static typing.\nThen comes the implementation of the language. The more information are statically known upfront, the easier it is to write a compiler. Inversely, the more late bound the language is, the harder it is. Hence the need to rely on interpretive techniques sometimes. \nThe distinction between both isn't strict however. Not only can we consider that everything is ultimately interpreted (see S.Lott answer), but part of the code can be compiled, decompile, or recompile dynamically (e.g. JIT) making the distinction very fuzzy. \nFor instance, dynamic class loading in Java goes in the category \"late binding\": the set of class is not fixed once for all, and classes can be loaded dynamically. Some optimizations can be done when we know the set of classes, but will need to be invalidated once a new classes is loaded. The same happens with the ability to update a method with the debugging infrastructure: the JVM will need to de-optimize all call sites were the method had been inlined.\nI don't know much about Python, but Python practitioners prefer maybe the term \"late bound\" to avoid such confusion.\n",
"I think the common misconception that Python is interpreted while Java is compiled arises because Java has an explicit compilation step - you have to run javac to convert your .java source file into a .class bytecode file that can be run. \nAs you rightly point out Python similarly compiles source files into bytecode but it does it transparently - compiling and running is generally done in a single step so it is less obvious to the user.\nThe important difference is between early & late binding and dynamic & static typing. The compiled/interpreted distinction is meaningless and irrelevant.\n",
"binding time is when names get resolved to things. \nMore dynamic languages tend towards late binding. \nThis can be separate from interpretation/compilation -- for example,\nobjective-C methods are resolved late and dynamically compared to C++.\nJava does much of it's binding at class load time : later than C but\nearlier than Python. \nmy favorite quote from Stan Kelly-Bootle's Computer Contradictionary:\nbinding time n. The moment when the hash table becomes corrupted.\n==> Advances in computing can be mapped against the \"lateness of binding,\" which has me thinking about my own so-called CS so-called career: golden past, gray present, and rosy future. This is my version of Synge's optimism: the grass is greener except at t=0. On EDSAC I, my functions (5ch paper-tape subroutines) were punched, spliced, and bound about two weeks before input. This is known aspremature binding and calls for deftness with elastic bands. FORTRAN came next with a new kind of binding: soggy decks of cards that refused to be shuffled. Then with Algol and C, I enjoyed static (compile-time) binding, until C++ brought the numbing joys of dynamic (run-time) binding. My current research aims at delaying the binding until well after execution. I call this end-time binding, as prophesied in St. Matthew's Gospel: \"...and whatsoever thou shalt bind on earth shall be bound in heaven...\" (Matthew 16:19 KJV).\n"
] | [
9,
7,
3,
2,
0
] | [] | [] | [
"compiled",
"java",
"late_binding",
"python"
] | stackoverflow_0002881526_compiled_java_late_binding_python.txt |
Q:
Converting python collaborative filtering code to use Map Reduce
Using Python, I'm computing cosine similarity across items.
given event data that represents a purchase (user,item), I have a list of all items 'bought' by my users.
Given this input data
(user,item)
X,1
X,2
Y,1
Y,2
Z,2
Z,3
I build a python dictionary
{1: ['X','Y'], 2 : ['X','Y','Z'], 3 : ['Z']}
From that dictionary, I generate a bought/not bought matrix, also another dictionary(bnb).
{1 : [1,1,0], 2 : [1,1,1], 3 : [0,0,1]}
From there, I'm computing similarity between (1,2) by calculating cosine between (1,1,0) and (1,1,1), yielding 0.816496
I'm doing this by:
items=[1,2,3]
for item in items:
for sub in items:
if sub >= item: #as to not calculate similarity on the inverse
sim = coSim( bnb[item], bnb[sub] )
I think the brute force approach is killing me and it only runs slower as the data gets larger. Using my trusty laptop, this calculation runs for hours when dealing with 8500 users and 3500 items.
I'm trying to compute similarity for all items in my dict and it's taking longer than I'd like it to. I think this is a good candidate for MapReduce but I'm having trouble 'thinking' in terms of key/value pairs.
Alternatively, is the issue with my approach and not necessarily a candidate for Map Reduce?
A:
This is not actually a "MapReduce" function but it should give you some significant speedup without all of the hassle.
I would actually use numpy to "vectorize" the operation and make your life easier. From this you'll just need to loop through this dictionary and apply the vectorized function comparing this item against all others.
import numpy as np
bnb_items = bnb.values()
for num in xrange(len(bnb_items)-1):
sims = cosSim(bnb_items[num], bnb_items[num+1:]
def cosSim(User, OUsers):
""" Determinnes the cosine-similarity between 1 user and all others.
Returns an array the size of OUsers with the similarity measures
User is a single array of the items purchased by a user.
OUsers is a LIST of arrays purchased by other users.
"""
multidot = np.vectorize(np.vdot)
multidenom = np.vectorize(lambda x: np.sum(x)*np.sum(User))
#apply the dot-product between this user and all others
num = multidot(OUsers, User)
#apply the magnitude multiplication across this user and all others
denom = multidenom(OUsers)
return num/denom
I haven't tested this code so there may be some silly errors but the idea should get you 90% of the way.
This should have a SIGNIFICANT speedup. If you still need a speed up there is a wonderful blog post which implements a "Slope One" recommendation system here.
Hope that helps,
Will
| Converting python collaborative filtering code to use Map Reduce | Using Python, I'm computing cosine similarity across items.
given event data that represents a purchase (user,item), I have a list of all items 'bought' by my users.
Given this input data
(user,item)
X,1
X,2
Y,1
Y,2
Z,2
Z,3
I build a python dictionary
{1: ['X','Y'], 2 : ['X','Y','Z'], 3 : ['Z']}
From that dictionary, I generate a bought/not bought matrix, also another dictionary(bnb).
{1 : [1,1,0], 2 : [1,1,1], 3 : [0,0,1]}
From there, I'm computing similarity between (1,2) by calculating cosine between (1,1,0) and (1,1,1), yielding 0.816496
I'm doing this by:
items=[1,2,3]
for item in items:
for sub in items:
if sub >= item: #as to not calculate similarity on the inverse
sim = coSim( bnb[item], bnb[sub] )
I think the brute force approach is killing me and it only runs slower as the data gets larger. Using my trusty laptop, this calculation runs for hours when dealing with 8500 users and 3500 items.
I'm trying to compute similarity for all items in my dict and it's taking longer than I'd like it to. I think this is a good candidate for MapReduce but I'm having trouble 'thinking' in terms of key/value pairs.
Alternatively, is the issue with my approach and not necessarily a candidate for Map Reduce?
| [
"This is not actually a \"MapReduce\" function but it should give you some significant speedup without all of the hassle.\nI would actually use numpy to \"vectorize\" the operation and make your life easier. From this you'll just need to loop through this dictionary and apply the vectorized function comparing this item against all others.\nimport numpy as np\nbnb_items = bnb.values()\nfor num in xrange(len(bnb_items)-1):\n sims = cosSim(bnb_items[num], bnb_items[num+1:]\n\ndef cosSim(User, OUsers):\n\"\"\" Determinnes the cosine-similarity between 1 user and all others.\nReturns an array the size of OUsers with the similarity measures\n\nUser is a single array of the items purchased by a user.\nOUsers is a LIST of arrays purchased by other users.\n\n\"\"\"\n\n multidot = np.vectorize(np.vdot)\n multidenom = np.vectorize(lambda x: np.sum(x)*np.sum(User))\n\n #apply the dot-product between this user and all others\n num = multidot(OUsers, User)\n\n #apply the magnitude multiplication across this user and all others\n denom = multidenom(OUsers)\n\n return num/denom\n\nI haven't tested this code so there may be some silly errors but the idea should get you 90% of the way.\nThis should have a SIGNIFICANT speedup. If you still need a speed up there is a wonderful blog post which implements a \"Slope One\" recommendation system here.\nHope that helps,\nWill\n"
] | [
6
] | [] | [] | [
"collaborative_filtering",
"hadoop",
"optimization",
"python",
"similarity"
] | stackoverflow_0002881467_collaborative_filtering_hadoop_optimization_python_similarity.txt |
Q:
Running the same code for get(self) as post(self)
Its been mentioned in other answers about getting the same code running for both the def get(self) and the def post(self) for any given request. I was wondering what techniques people use, I was thinking of:
class ListSubs(webapp.RequestHandler):
def get(self):
self._run()
def post(self):
self._run()
def _run(self):
self.response.out.write("This works nicely!")
A:
I would suggest both theoretical and practical reasons why the approach you're using (refactoring out the common code to a separate method and calling it from both post and get methods) is superior to the apparently-simpler alternative of just having one of those two methods call the other.
From a theoretical viewpoint, "method A entirely delegates to method B" implies a notion of "primacy" or "asymmetry" -- a design decision that, going forwards, any change that may be applied to B will inevitably, intrinsically apply to A as well; that A may in the future be slightly customized with respect to B (adding some extra code before and/or after A's call to B) but never vice versa. When there's no reason to expect such primacy it's a bad coding decision to embed that notion in your code. By having both A and B call the common private method C, you avoid breaking symmetry.
Some people are not happy with theoretical arguments and prefer pragmatic ones: fortunately, in this case, the theoretical translates to the pragmatic pretty directly. Again, it's an issue of future evolution of the code: having both A and B call C leaves you all needed degrees of freedom to do small customizations (adding code before and/or after the call to C) to either, both, or neither of A and B. Since you don't know which parts of this flexibility you will need, and the cost of it in terms of simplicity is miniscule, taking the simple and flexible route is highly pragmatical and advisable.
One last pragmatical point (applying to either choice): any time you have a pattern like:
def amethod(self):
return cmethod(self)
you're usually (modestly) better off rewording this as
amethod = cmethod
This avoids an unneeded level of call nesting (flat is better than nested). So, your class could usefully be coded:
class ListSubs(webapp.RequestHandler):
def _run(self):
self.response.out.write("This works even better!")
get = post = _run
No big deal, and you'll have to refactor back to the original "nested" way if and when you do need to apply tweaks before or after the nested call (from get to _run, etc) or need other tweaks in debugging (e.g. set a breakpoint in your debugger on post but without having the breakpoint trigger on get, etc), but a nice little simplification for those times where it's feasible.
A:
Refactoring the code that does the work into its own function/method is the correct method.
A:
I've used this:
class ListSubs(webapp.RequestHandler):
def post(self):
self.response.out.write("This works nicely!")
def get(self):
self.post()
A:
One thing that I haven't seen in responses, which I'll throw in, is why you shouldn't do this. It is a fairly common principal that an HTTP GET changing data on the server is a bad idea. Changing the server's state should usually happen through a POST. As a result, each URL which is used for both GET and POST should have specific actions that differ based on the type of request. The w3c has a nice overview of when to use GET vs. POST as well.
I tend to think of GET and POST like a getter and a setter. POSTs change data, and GETs get data. As a result, a simple search can use GET all day long, but when you save a setting back to the server, a POST is in order.
For example, say you have a URL for a post in your blog (example.com/blog/post-vs-get/). You could then use get() to get the blog post and render it to screen with a nice comment form. In this example, my comment form will POST back to the same URL, calling the post() method, which can process the form and then return the same rendered page.
class ListSubs(webapp.RequestHandler):
def post(self):
comment = cgi.escape(self.request.get('comment'))
## Do magic with our comment.
self.get() ## Go off and return the rendered page.
def get(self):
## Get the blog post out of the data store and render a page.
self.response.out.write("""<html>
<body>
<p>My awesome blog post!</p>
<form method="post">
<h1>Comment</h1>
<textarea name="comment" rows="3" cols="60"></textarea>
<input type="submit" value="Comment">
</form>
</body>
</html>""")
This gives a clean division of labor between rendering the page, and processing the POST data. This also keeps your code from running unnecessary form validation and/or processing on a request with no data. In my opinion, this separation of duties also makes debugging and maintaining code easier.
| Running the same code for get(self) as post(self) | Its been mentioned in other answers about getting the same code running for both the def get(self) and the def post(self) for any given request. I was wondering what techniques people use, I was thinking of:
class ListSubs(webapp.RequestHandler):
def get(self):
self._run()
def post(self):
self._run()
def _run(self):
self.response.out.write("This works nicely!")
| [
"I would suggest both theoretical and practical reasons why the approach you're using (refactoring out the common code to a separate method and calling it from both post and get methods) is superior to the apparently-simpler alternative of just having one of those two methods call the other.\nFrom a theoretical viewpoint, \"method A entirely delegates to method B\" implies a notion of \"primacy\" or \"asymmetry\" -- a design decision that, going forwards, any change that may be applied to B will inevitably, intrinsically apply to A as well; that A may in the future be slightly customized with respect to B (adding some extra code before and/or after A's call to B) but never vice versa. When there's no reason to expect such primacy it's a bad coding decision to embed that notion in your code. By having both A and B call the common private method C, you avoid breaking symmetry.\nSome people are not happy with theoretical arguments and prefer pragmatic ones: fortunately, in this case, the theoretical translates to the pragmatic pretty directly. Again, it's an issue of future evolution of the code: having both A and B call C leaves you all needed degrees of freedom to do small customizations (adding code before and/or after the call to C) to either, both, or neither of A and B. Since you don't know which parts of this flexibility you will need, and the cost of it in terms of simplicity is miniscule, taking the simple and flexible route is highly pragmatical and advisable.\nOne last pragmatical point (applying to either choice): any time you have a pattern like:\ndef amethod(self):\n return cmethod(self)\n\nyou're usually (modestly) better off rewording this as\namethod = cmethod\n\nThis avoids an unneeded level of call nesting (flat is better than nested). So, your class could usefully be coded:\nclass ListSubs(webapp.RequestHandler):\n\n def _run(self):\n self.response.out.write(\"This works even better!\")\n\n get = post = _run\n\nNo big deal, and you'll have to refactor back to the original \"nested\" way if and when you do need to apply tweaks before or after the nested call (from get to _run, etc) or need other tweaks in debugging (e.g. set a breakpoint in your debugger on post but without having the breakpoint trigger on get, etc), but a nice little simplification for those times where it's feasible.\n",
"Refactoring the code that does the work into its own function/method is the correct method.\n",
"I've used this:\nclass ListSubs(webapp.RequestHandler):\n def post(self):\n self.response.out.write(\"This works nicely!\")\n def get(self):\n self.post()\n\n",
"One thing that I haven't seen in responses, which I'll throw in, is why you shouldn't do this. It is a fairly common principal that an HTTP GET changing data on the server is a bad idea. Changing the server's state should usually happen through a POST. As a result, each URL which is used for both GET and POST should have specific actions that differ based on the type of request. The w3c has a nice overview of when to use GET vs. POST as well.\nI tend to think of GET and POST like a getter and a setter. POSTs change data, and GETs get data. As a result, a simple search can use GET all day long, but when you save a setting back to the server, a POST is in order. \nFor example, say you have a URL for a post in your blog (example.com/blog/post-vs-get/). You could then use get() to get the blog post and render it to screen with a nice comment form. In this example, my comment form will POST back to the same URL, calling the post() method, which can process the form and then return the same rendered page.\nclass ListSubs(webapp.RequestHandler):\n def post(self):\n comment = cgi.escape(self.request.get('comment'))\n ## Do magic with our comment.\n self.get() ## Go off and return the rendered page.\n def get(self):\n ## Get the blog post out of the data store and render a page.\n self.response.out.write(\"\"\"<html>\n <body>\n <p>My awesome blog post!</p>\n <form method=\"post\">\n <h1>Comment</h1>\n <textarea name=\"comment\" rows=\"3\" cols=\"60\"></textarea>\n <input type=\"submit\" value=\"Comment\">\n </form>\n </body>\n </html>\"\"\")\n\nThis gives a clean division of labor between rendering the page, and processing the POST data. This also keeps your code from running unnecessary form validation and/or processing on a request with no data. In my opinion, this separation of duties also makes debugging and maintaining code easier.\n"
] | [
11,
2,
2,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002882915_google_app_engine_python.txt |
Q:
Spawning a thread in python
I have a series of 'tasks' that I would like to run in separate threads. The tasks are to be performed by separate modules. Each containing the business logic for processing their tasks.
Given a tuple of tasks, I would like to be able to spawn a new thread for each module as follows.
from foobar import alice, bob charles
data = getWorkData()
# these are enums (which I just found Python doesn't support natively) :(
tasks = (alice, bob, charles)
for task in tasks
# Ok, just found out Python doesn't have a switch - @#$%!
# yet another thing I'll need help with then ...
switch
case alice:
#spawn thread here - how ?
alice.spawnWorker(data)
No prizes for guessing I am still thinking in C++. How can I write this in a Pythonic way using Pythonic 'enums' and 'switch'es, and be able to run a module in a new thread.
Obviously, the modules will all have a class that is derived from a ABC (abstract base class) called Plugin. The spawnWorker() method will be declared on the Plugin interface and defined in the classes implemented in the various modules.
Maybe, there is a better (i.e. Pythonic) way of doing all this?. I'd be interested in knowing
[Edit]
I've just been reading a bot more and it seems Python does not implement threading in the true sense (at least, not in the sense that a C++ programmer would think). In any case thats not a show stopper for me. Each of the tasks are fairly time consuming, and I dont want to hold up starting one task until another has completed, thats why I am using threading. Time slicing does not bother me much - so long as they are all started pretty much at the same time (or shortly after each other) Python can then timeslice between the treads as much as it wants - its fine by me.
I have seen an answer to a similar question here on SO.
A user provides a simple class for threading as follows:
import threading
class Foo (threading.Thread):
def __init__(self,x):
self.__x = x
threading.Thread.__init__(self)
def run (self):
print str(self.__x)
for x in xrange(20):
Foo(x).start()
I am thinking of using this for my ABC Plugin. My question then is where do I put the code where the actual task gets done (i.e. the business logic). I assume this goes in the run() method of the Foo class (obvious question I know, but I dont want to make any assumptions).
Is my thinking on the right track or flawed (if flawed - what have I missed?)
A:
Instead of switch-case, why not use a proper polymorphism? For example, here what you can do with duck typing in Python:
In, say, alice.py:
def do_stuff(data):
print 'alice does stuff with %s' % data
In, say, bob.py:
def do_stuff(data):
print 'bob does stuff with %s' % data
Then in your client code, say, main.py:
import threading
import alice, bob
def get_work_data():
return 'data'
def main():
tasks = [alice.do_stuff, bob.do_stuff]
data = get_work_data()
for task in tasks:
t = threading.Thread(target=task, args=(data,))
t.start()
Let me know if I need to clarify.
A:
import threading
from foobar import alice, bob, charles
data = get_work_data() # names_in_pep8 are more Pythonic than camelCased
for mod in [alice, bob, charles]:
# mod is an object that represent a module
worker = getattr(mod, 'do_work')
# worker now is a reference to the function like alice.do_work
t = threading.Thread(target=worker, args=[data])
# uncomment following line if you don't want to block the program
# until thread finishes on termination
#t.daemon = True
t.start()
Put your logic in do_work functions of corresponding modules.
A:
Sequential execution:
from foobar import alice, bob, charles
for fct in (alice, bob, charles):
fct()
Parallel execution:
from threading import Thread
from foobar import alice, bob, charles
for fct in (alice, bob, charles):
Thread(target=fct).start()
A:
Python can hold functions as objects. To overcome the limitation on lacking a switch may I suggest the following:
case_alice = lambda data : alice.spawnWorker(data)
my_dict[alice] = case_alice
forming a dictionary to hold your "case" statements.
Let me take it even further:
data = getWorkData()
case_alice = lambda d : alice.spawnWorker( d )
case_bob = lambda d : bob.spawnWorker( d )
case_charles = lambda d : charles.spawnWorker( d )
switch = { alice : case_alice, bob : case_bob, charles : case_charles }
spawn = lambda person : switch[ person ]( data )
[ spawn( item ) for item in (alice, bob, charles )]
| Spawning a thread in python | I have a series of 'tasks' that I would like to run in separate threads. The tasks are to be performed by separate modules. Each containing the business logic for processing their tasks.
Given a tuple of tasks, I would like to be able to spawn a new thread for each module as follows.
from foobar import alice, bob charles
data = getWorkData()
# these are enums (which I just found Python doesn't support natively) :(
tasks = (alice, bob, charles)
for task in tasks
# Ok, just found out Python doesn't have a switch - @#$%!
# yet another thing I'll need help with then ...
switch
case alice:
#spawn thread here - how ?
alice.spawnWorker(data)
No prizes for guessing I am still thinking in C++. How can I write this in a Pythonic way using Pythonic 'enums' and 'switch'es, and be able to run a module in a new thread.
Obviously, the modules will all have a class that is derived from a ABC (abstract base class) called Plugin. The spawnWorker() method will be declared on the Plugin interface and defined in the classes implemented in the various modules.
Maybe, there is a better (i.e. Pythonic) way of doing all this?. I'd be interested in knowing
[Edit]
I've just been reading a bot more and it seems Python does not implement threading in the true sense (at least, not in the sense that a C++ programmer would think). In any case thats not a show stopper for me. Each of the tasks are fairly time consuming, and I dont want to hold up starting one task until another has completed, thats why I am using threading. Time slicing does not bother me much - so long as they are all started pretty much at the same time (or shortly after each other) Python can then timeslice between the treads as much as it wants - its fine by me.
I have seen an answer to a similar question here on SO.
A user provides a simple class for threading as follows:
import threading
class Foo (threading.Thread):
def __init__(self,x):
self.__x = x
threading.Thread.__init__(self)
def run (self):
print str(self.__x)
for x in xrange(20):
Foo(x).start()
I am thinking of using this for my ABC Plugin. My question then is where do I put the code where the actual task gets done (i.e. the business logic). I assume this goes in the run() method of the Foo class (obvious question I know, but I dont want to make any assumptions).
Is my thinking on the right track or flawed (if flawed - what have I missed?)
| [
"Instead of switch-case, why not use a proper polymorphism? For example, here what you can do with duck typing in Python:\nIn, say, alice.py:\ndef do_stuff(data):\n print 'alice does stuff with %s' % data\n\nIn, say, bob.py:\ndef do_stuff(data):\n print 'bob does stuff with %s' % data\n\nThen in your client code, say, main.py:\nimport threading\nimport alice, bob\n\ndef get_work_data():\n return 'data'\n\ndef main():\n tasks = [alice.do_stuff, bob.do_stuff]\n data = get_work_data()\n for task in tasks:\n t = threading.Thread(target=task, args=(data,))\n t.start()\n\nLet me know if I need to clarify.\n",
"import threading\nfrom foobar import alice, bob, charles\n\ndata = get_work_data() # names_in_pep8 are more Pythonic than camelCased\n\nfor mod in [alice, bob, charles]:\n # mod is an object that represent a module\n worker = getattr(mod, 'do_work')\n # worker now is a reference to the function like alice.do_work\n t = threading.Thread(target=worker, args=[data])\n # uncomment following line if you don't want to block the program\n # until thread finishes on termination\n #t.daemon = True \n t.start()\n\nPut your logic in do_work functions of corresponding modules.\n",
"Sequential execution:\nfrom foobar import alice, bob, charles\n\nfor fct in (alice, bob, charles):\n fct()\n\nParallel execution:\nfrom threading import Thread\nfrom foobar import alice, bob, charles\n\nfor fct in (alice, bob, charles):\n Thread(target=fct).start()\n\n",
"Python can hold functions as objects. To overcome the limitation on lacking a switch may I suggest the following:\ncase_alice = lambda data : alice.spawnWorker(data)\n\nmy_dict[alice] = case_alice\n\nforming a dictionary to hold your \"case\" statements.\nLet me take it even further:\ndata = getWorkData()\ncase_alice = lambda d : alice.spawnWorker( d )\ncase_bob = lambda d : bob.spawnWorker( d )\ncase_charles = lambda d : charles.spawnWorker( d )\n\nswitch = { alice : case_alice, bob : case_bob, charles : case_charles }\nspawn = lambda person : switch[ person ]( data )\n[ spawn( item ) for item in (alice, bob, charles )]\n\n"
] | [
41,
5,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0002882308_python.txt |
Q:
2 different Django modules on Google App Engine
I came across 2 different modules for porting Django to App Engine:
http://code.google.com/p/app-engine-patch/
http://code.google.com/p/google-app-engine-django/
Both seem to be compatible with Django 1.0,
The featured download of the latter is in Aug 08, whereas the former is Feb 09.
What are the relative merits?
What if I don't use the database at all, would it matter?
A:
At the moment, the App Engine Patch is outdated.
Djangoappengine and Django-Nonrel provide "Native Django on App Engine":
http://www.allbuttonspressed.com/blog/django/2010/01/Native-Django-on-App-Engine
A:
It's a bit late to answer, but the problem I've had so far with app-engine-patch is that, while it's a generally feature-complete port of Django 1.0, it discards Django models in favor of AppEngine's db.Model.
It's understandable, given the differences between the two, but it can require quite a bit of effort to port, depending on how involved your models (and usage of those models; this means you lose the Django query syntax as well).
A:
Well, I got it myself. I used python 2.6, and it seem problmatic for app-engine. Starting with python2.5 solved it.
See here:
A:
App Engine Patch is the right way to go.
| 2 different Django modules on Google App Engine | I came across 2 different modules for porting Django to App Engine:
http://code.google.com/p/app-engine-patch/
http://code.google.com/p/google-app-engine-django/
Both seem to be compatible with Django 1.0,
The featured download of the latter is in Aug 08, whereas the former is Feb 09.
What are the relative merits?
What if I don't use the database at all, would it matter?
| [
"At the moment, the App Engine Patch is outdated.\nDjangoappengine and Django-Nonrel provide \"Native Django on App Engine\": \nhttp://www.allbuttonspressed.com/blog/django/2010/01/Native-Django-on-App-Engine \n",
"It's a bit late to answer, but the problem I've had so far with app-engine-patch is that, while it's a generally feature-complete port of Django 1.0, it discards Django models in favor of AppEngine's db.Model.\nIt's understandable, given the differences between the two, but it can require quite a bit of effort to port, depending on how involved your models (and usage of those models; this means you lose the Django query syntax as well).\n",
"Well, I got it myself. I used python 2.6, and it seem problmatic for app-engine. Starting with python2.5 solved it. \nSee here:\n",
"App Engine Patch is the right way to go.\n"
] | [
6,
1,
0,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0000789902_django_google_app_engine_python.txt |
Q:
Faster Insertion of Records into a Table with SQLAlchemy
I am parsing a log and inserting it into either MySQL or SQLite using SQLAlchemy and Python. Right now I open a connection to the DB, and as I loop over each line, I insert it after it is parsed (This is just one big table right now, not very experienced with SQL). I then close the connection when the loop is done. The summarized code is:
log_table = schema.Table('log_table', metadata,
schema.Column('id', types.Integer, primary_key=True),
schema.Column('time', types.DateTime),
schema.Column('ip', types.String(length=15))
....
engine = create_engine(...)
metadata.bind = engine
connection = engine.connect()
....
for line in file_to_parse:
m = line_regex.match(line)
if m:
fields = m.groupdict()
pythonified = pythoninfy_log(fields) #Turn them into ints, datatimes, etc
if use_sql:
ins = log_table.insert(values=pythonified)
connection.execute(ins)
parsed += 1
My two questions are:
Is there a way to speed up the inserts within this basic framework? Maybe have a Queue of inserts and some insertion threads, some sort of bulk inserts, etc?
When I used MySQL, for about ~1.2 million records the insert time was 15 minutes. With SQLite, the insert time was a little over an hour. Does that time difference between the db engines seem about right, or does it mean I am doing something very wrong?
A:
The big thing you should try is putting a transaction around multiple inserts since it is the committing of the database to disk that really takes a long time. You'll need to decide the batching level, but a crude first attempt would be to wrap a transaction around the whole lot.
A:
Without knowing the table engine (MyISAM? InnoDB?), schema, and indexes, it's hard to comment on specifics between the two databases you're using there.
However, when using MySQL like this, you will likely find that it is far faster to write your data out to a temporary text file and then use the LOAD DATA INFILE syntax to load it all into your database. It looks like you can call the execute method on your connection object to run the SQL necessary to do this.
Further, if you are dead set on adding things row by row, and you're recreating the table every time, you can verify key constraints in your program and add those constraints only after all rows have been inserted, saving the DB the time of doing constraints checks on every insert.
A:
I did the following to achieve some batching:
inserts = []
insert_every = 1000
for line in file_to_parse:
m = line_regex.match(line)
if m:
fields = m.groupdict()
if use_sql: #This uses Globals, Ick :-/
inserts.append(pythonified)
if (parsed % insert_every) == 0:
connection.execute(log_table.insert(), inserts)
inserts = []
parsed += 1
if use_sql:
if len(inserts) > 0:
connection.execute(log_table.insert(), inserts)
This doesn't use transactions, but in a very lazy manner it allowed me to turn the insert/parse stage from ~13 seconds to about ~2 seconds with mysql backend using a smaller sample. I will see what the difference between mysql and sqlite is now with this change using the full sample.
I found the basic information for this here.
Results:
Engine:Non-Grouped Insert Time in Minutes: Grouped Insert Time in Minutes
Sqlite:61:8
MySql:15:2.5
I didn't flush my cache between the mysql and sqlite which would have had the source text file possibly, but I don't think that would be a relatively significant difference.
| Faster Insertion of Records into a Table with SQLAlchemy | I am parsing a log and inserting it into either MySQL or SQLite using SQLAlchemy and Python. Right now I open a connection to the DB, and as I loop over each line, I insert it after it is parsed (This is just one big table right now, not very experienced with SQL). I then close the connection when the loop is done. The summarized code is:
log_table = schema.Table('log_table', metadata,
schema.Column('id', types.Integer, primary_key=True),
schema.Column('time', types.DateTime),
schema.Column('ip', types.String(length=15))
....
engine = create_engine(...)
metadata.bind = engine
connection = engine.connect()
....
for line in file_to_parse:
m = line_regex.match(line)
if m:
fields = m.groupdict()
pythonified = pythoninfy_log(fields) #Turn them into ints, datatimes, etc
if use_sql:
ins = log_table.insert(values=pythonified)
connection.execute(ins)
parsed += 1
My two questions are:
Is there a way to speed up the inserts within this basic framework? Maybe have a Queue of inserts and some insertion threads, some sort of bulk inserts, etc?
When I used MySQL, for about ~1.2 million records the insert time was 15 minutes. With SQLite, the insert time was a little over an hour. Does that time difference between the db engines seem about right, or does it mean I am doing something very wrong?
| [
"The big thing you should try is putting a transaction around multiple inserts since it is the committing of the database to disk that really takes a long time. You'll need to decide the batching level, but a crude first attempt would be to wrap a transaction around the whole lot.\n",
"Without knowing the table engine (MyISAM? InnoDB?), schema, and indexes, it's hard to comment on specifics between the two databases you're using there.\nHowever, when using MySQL like this, you will likely find that it is far faster to write your data out to a temporary text file and then use the LOAD DATA INFILE syntax to load it all into your database. It looks like you can call the execute method on your connection object to run the SQL necessary to do this.\nFurther, if you are dead set on adding things row by row, and you're recreating the table every time, you can verify key constraints in your program and add those constraints only after all rows have been inserted, saving the DB the time of doing constraints checks on every insert.\n",
"I did the following to achieve some batching:\ninserts = []\ninsert_every = 1000\nfor line in file_to_parse:\n m = line_regex.match(line)\n if m:\n fields = m.groupdict()\n if use_sql: #This uses Globals, Ick :-/\n inserts.append(pythonified)\n if (parsed % insert_every) == 0:\n connection.execute(log_table.insert(), inserts)\n inserts = []\n parsed += 1\nif use_sql:\n if len(inserts) > 0:\n connection.execute(log_table.insert(), inserts)\n\nThis doesn't use transactions, but in a very lazy manner it allowed me to turn the insert/parse stage from ~13 seconds to about ~2 seconds with mysql backend using a smaller sample. I will see what the difference between mysql and sqlite is now with this change using the full sample.\nI found the basic information for this here.\nResults:\nEngine:Non-Grouped Insert Time in Minutes: Grouped Insert Time in Minutes\nSqlite:61:8\nMySql:15:2.5\nI didn't flush my cache between the mysql and sqlite which would have had the source text file possibly, but I don't think that would be a relatively significant difference.\n"
] | [
4,
3,
3
] | [] | [] | [
"mysql",
"python",
"sql",
"sqlalchemy",
"sqlite"
] | stackoverflow_0002881890_mysql_python_sql_sqlalchemy_sqlite.txt |
Q:
How to parse large xml files on google app engine?
I have fairly large xml file 1mb in size that i host on s3.
I need to parse that xml file into my app engine datastore entirely.
I have written a simple DOM parser that works fine locally but online it reaches the 30sec error and stops.
I tried lowering the xml parsing by downloading the xml file into a BLOB at first before the parser then parse the xml file from blob. problem is that blobs are limited to 1mb. so it fails.
I have multiple inserts to the datastore which cause it to fail on 30 sec.
i saw somewhere that they recommend using the Mapper class and save some exception where the process stopped but as i am a python n00b i cant figure out how to implement it on a DOM parser or an SAX one (please provide an example?) on how to use it.
i'm pretty much doing a bad thing right now and i parse the xml using php outside the app engine and push the data via HTTP post to the app engine using a proprietary API which works fine but is stupid and makes me maintain two codes.
can you please help me out?
A:
For uploading large volumes of data, take a look at the Uploading and Downloading Data help page.
| How to parse large xml files on google app engine? | I have fairly large xml file 1mb in size that i host on s3.
I need to parse that xml file into my app engine datastore entirely.
I have written a simple DOM parser that works fine locally but online it reaches the 30sec error and stops.
I tried lowering the xml parsing by downloading the xml file into a BLOB at first before the parser then parse the xml file from blob. problem is that blobs are limited to 1mb. so it fails.
I have multiple inserts to the datastore which cause it to fail on 30 sec.
i saw somewhere that they recommend using the Mapper class and save some exception where the process stopped but as i am a python n00b i cant figure out how to implement it on a DOM parser or an SAX one (please provide an example?) on how to use it.
i'm pretty much doing a bad thing right now and i parse the xml using php outside the app engine and push the data via HTTP post to the app engine using a proprietary API which works fine but is stupid and makes me maintain two codes.
can you please help me out?
| [
"For uploading large volumes of data, take a look at the Uploading and Downloading Data help page.\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python",
"sax",
"xml"
] | stackoverflow_0002882732_google_app_engine_python_sax_xml.txt |
Q:
pyodbc on SQL Server - How can I do an insert and get the row ID back?
I'm using pyodbc with SQL Server 2000.
I want to be able to insert a row and get the auto incremented row id value back? Any ideas?
Here's what I have so far:
cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
cnxn.commit()
A:
Sorry, I asked too soon, it's addressed in their FAQ
Use "SELECT @@IDENTITY".
| pyodbc on SQL Server - How can I do an insert and get the row ID back? | I'm using pyodbc with SQL Server 2000.
I want to be able to insert a row and get the auto incremented row id value back? Any ideas?
Here's what I have so far:
cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
cnxn.commit()
| [
"Sorry, I asked too soon, it's addressed in their FAQ\nUse \"SELECT @@IDENTITY\". \n"
] | [
10
] | [] | [] | [
"django_pyodbc",
"pyodbc",
"python",
"sql_server"
] | stackoverflow_0002883722_django_pyodbc_pyodbc_python_sql_server.txt |
Q:
How do I compile python extensions for Mac OS X 10.5, on Mac OS X 10.6?
I'm trying to compile a variety of python extensions (pycrypto, paramiko, subvertpy...) on Mac OS X 10.6, such that they will be compatible with Mac OS X 10.5 and its built-in python 2.5, for including in a product installer targetted at Mac OS X 10.5.
I'm really not sure how to go about this. I dug around on Google and found a question here on stackoverflow, which led me to setting MACOSX_DEPLOYMENT_TARGET=10.5 in my environment before building, but that just gave me the error:
distutils.errors.DistutilsPlatformError: $MACOSX_DEPLOYMENT_TARGET mismatch: now "10.5" but "10.6" during configure
I am using python2.5 on Mac OS X 10.6 to run the builds, for example:
$ python2.5 setup.py install
I also came across references to /Developer/SDKs/MacOSX10.5.sdk but I'm not really sure how to make use of it.
A:
I managed to get distutils to believe that Python was built on Leopard, by inserting the following code before the call to setup() in setup.py:
# XXXHACK: make distutils believe that Python was built on Leopard.
from distutils import sysconfig
their_parse_makefile = sysconfig.parse_makefile
def my_parse_makefile(filename, g):
their_parse_makefile(filename, g)
g['MACOSX_DEPLOYMENT_TARGET'] = '10.5'
sysconfig.parse_makefile = my_parse_makefile
Then pycrypto builds well on Snow Leopard, using python2.5, after setting MACOSX_DEPLOYMENT_TARGET to "10.5". I can't guarantee it will work well but pycrypto's bundled test suite passed with this build on my Macbook Air running Leopard, so it seems OK.
| How do I compile python extensions for Mac OS X 10.5, on Mac OS X 10.6? | I'm trying to compile a variety of python extensions (pycrypto, paramiko, subvertpy...) on Mac OS X 10.6, such that they will be compatible with Mac OS X 10.5 and its built-in python 2.5, for including in a product installer targetted at Mac OS X 10.5.
I'm really not sure how to go about this. I dug around on Google and found a question here on stackoverflow, which led me to setting MACOSX_DEPLOYMENT_TARGET=10.5 in my environment before building, but that just gave me the error:
distutils.errors.DistutilsPlatformError: $MACOSX_DEPLOYMENT_TARGET mismatch: now "10.5" but "10.6" during configure
I am using python2.5 on Mac OS X 10.6 to run the builds, for example:
$ python2.5 setup.py install
I also came across references to /Developer/SDKs/MacOSX10.5.sdk but I'm not really sure how to make use of it.
| [
"I managed to get distutils to believe that Python was built on Leopard, by inserting the following code before the call to setup() in setup.py:\n# XXXHACK: make distutils believe that Python was built on Leopard.\nfrom distutils import sysconfig\ntheir_parse_makefile = sysconfig.parse_makefile\ndef my_parse_makefile(filename, g):\n their_parse_makefile(filename, g)\n g['MACOSX_DEPLOYMENT_TARGET'] = '10.5'\nsysconfig.parse_makefile = my_parse_makefile\n\nThen pycrypto builds well on Snow Leopard, using python2.5, after setting MACOSX_DEPLOYMENT_TARGET to \"10.5\". I can't guarantee it will work well but pycrypto's bundled test suite passed with this build on my Macbook Air running Leopard, so it seems OK.\n"
] | [
2
] | [] | [] | [
"cross_compiling",
"macos",
"python"
] | stackoverflow_0002871013_cross_compiling_macos_python.txt |
Q:
Extracting and integrating data from separate lists in Python
I have this code:
cursor.execute( ''' SELECT id,DISTINCT tag
FROM userurltag ''')
tags = cursor.fetchall ()
T = [3,5,7,2,1,2,2,2,5,6,3,3,1,7,4]
I have 7 groups names 1,...,7 . Each row in "tags" list corresponds to a row in "T" list.the values of "T" say that for example the first row in "tags" list belongs to group 3, the second row in "tags" list belong to group 5 and so on. These are basically the clusters to which each tag belongs.
I want to extract them, in a way that I have each group/cluster in a separate for example dictionary data type. The important thing is that the number of clusters will change in each run. So I need a general code can work with various numbers of clusters for this problem.
I seriously need you help
Thanks.
A:
cluster_to_tag = defaultdict(list)
#May want to assert that length of tags and T is same
for tag,cluster in zip(tags, T):
cluster_to_tag[cluster].append(tag)
#cluster_to_tag now maps cluster ti list of tags
hth
| Extracting and integrating data from separate lists in Python | I have this code:
cursor.execute( ''' SELECT id,DISTINCT tag
FROM userurltag ''')
tags = cursor.fetchall ()
T = [3,5,7,2,1,2,2,2,5,6,3,3,1,7,4]
I have 7 groups names 1,...,7 . Each row in "tags" list corresponds to a row in "T" list.the values of "T" say that for example the first row in "tags" list belongs to group 3, the second row in "tags" list belong to group 5 and so on. These are basically the clusters to which each tag belongs.
I want to extract them, in a way that I have each group/cluster in a separate for example dictionary data type. The important thing is that the number of clusters will change in each run. So I need a general code can work with various numbers of clusters for this problem.
I seriously need you help
Thanks.
| [
"cluster_to_tag = defaultdict(list)\n#May want to assert that length of tags and T is same\nfor tag,cluster in zip(tags, T):\n cluster_to_tag[cluster].append(tag)\n\n#cluster_to_tag now maps cluster ti list of tags\n\nhth\n"
] | [
1
] | [] | [] | [
"cluster_analysis",
"list",
"python"
] | stackoverflow_0002883808_cluster_analysis_list_python.txt |
Q:
Why is i++++++++i valid in python?
I "accidentally" came across this weird but valid syntax
i=3
print i+++i #outputs 6
print i+++++i #outputs 6
print i+-+i #outputs 0
print i+--+i #outputs 6
(for every even no: of minus symbol, it outputs 6 else 0, why?)
Does this do anything useful?
Update (Don't take it the wrong way..I love python):
One of Python's principle says
There should be one-- and preferably only one --obvious way to do it. It seems there are infinite ways to do i+1
A:
Since Python doesn't have C-style ++ or -- operators, one is left to assume that you're negating or positivating(?) the value on the left.
E.g. what would you expect i + +5 to be?
i=3
print i + +(+i) #outputs 6
print i + +(+(+(+i))) #outputs 6
print i + -(+i) #outputs 0
print i + -(-(+i)) #outputs 6
Notably, from the Python Grammar Specification, you'll see the line:
factor: ('+'|'-'|'~') factor | power
Which means that a factor in an expression can be a factor preceded by +, -, or ~. I.e. it's recursive, so if 5 is a factor (which it is because factor->power->NUMBER), then -5 is a factor and so are --5 and --------5.
A:
The plus signs are considered unary operators to the right most i variable, as in +(-3) = -3, or +(+(+3))) = 3. Just the left most sign (plus or minus) are parsed as binary, so i+++i = i + (+(+i)), which translates to i + i = 3 + 3 = 6, in your example.
The other expressions follow the same principle.
A:
That should read
print i + (+ (+i) )
that is, the first sign is the addition operator, the other ones are infix signs
+i
and (unfortunately)
++i
are thus valid statements.
| Why is i++++++++i valid in python? | I "accidentally" came across this weird but valid syntax
i=3
print i+++i #outputs 6
print i+++++i #outputs 6
print i+-+i #outputs 0
print i+--+i #outputs 6
(for every even no: of minus symbol, it outputs 6 else 0, why?)
Does this do anything useful?
Update (Don't take it the wrong way..I love python):
One of Python's principle says
There should be one-- and preferably only one --obvious way to do it. It seems there are infinite ways to do i+1
| [
"Since Python doesn't have C-style ++ or -- operators, one is left to assume that you're negating or positivating(?) the value on the left.\nE.g. what would you expect i + +5 to be?\ni=3\nprint i + +(+i) #outputs 6\nprint i + +(+(+(+i))) #outputs 6\nprint i + -(+i) #outputs 0\nprint i + -(-(+i)) #outputs 6 \n\nNotably, from the Python Grammar Specification, you'll see the line:\nfactor: ('+'|'-'|'~') factor | power\n\nWhich means that a factor in an expression can be a factor preceded by +, -, or ~. I.e. it's recursive, so if 5 is a factor (which it is because factor->power->NUMBER), then -5 is a factor and so are --5 and --------5.\n",
"The plus signs are considered unary operators to the right most i variable, as in +(-3) = -3, or +(+(+3))) = 3. Just the left most sign (plus or minus) are parsed as binary, so i+++i = i + (+(+i)), which translates to i + i = 3 + 3 = 6, in your example.\nThe other expressions follow the same principle.\n",
"That should read\nprint i + (+ (+i) )\n\nthat is, the first sign is the addition operator, the other ones are infix signs\n+i\n\nand (unfortunately)\n++i\n\nare thus valid statements.\n"
] | [
28,
5,
5
] | [] | [] | [
"python"
] | stackoverflow_0002883920_python.txt |
Q:
get expando model properties in python for google-app-engine
How do I get all the properties from an expando model? (not just Model.properties())
I want to do something like this:
...
recs = query.fetch( 100 )
for rec in recs:
for name, value in rec.iteritem():
# figure out what, if any, expando properties are in this record
but Model.iteritem() doesn't exist
This seems like it should be pretty easy to over come, but I'm a bit stumped.
Thanks!
A:
rec.dynamic_properties() will give you a list of Expando properties
http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_dynamic_properties
| get expando model properties in python for google-app-engine | How do I get all the properties from an expando model? (not just Model.properties())
I want to do something like this:
...
recs = query.fetch( 100 )
for rec in recs:
for name, value in rec.iteritem():
# figure out what, if any, expando properties are in this record
but Model.iteritem() doesn't exist
This seems like it should be pretty easy to over come, but I'm a bit stumped.
Thanks!
| [
"rec.dynamic_properties() will give you a list of Expando properties\nhttp://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_dynamic_properties\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0002883842_google_app_engine_python.txt |
Q:
Is str.replace(..).replace(..) ad nauseam a standard idiom in Python?
For instance, say I wanted a function to escape a string for use in HTML (as in Django's escape filter):
def escape(string):
"""
Returns the given string with ampersands, quotes and angle
brackets encoded.
"""
return string.replace('&', '&').replace('<', '<').replace('>', '>').replace("'", ''').replace('"', '"')
This works, but it gets ugly quickly and appears to have poor algorithmic performance (in this example, the string is repeatedly traversed 5 times). What would be better is something like this:
def escape(string):
"""
Returns the given string with ampersands, quotes and angle
brackets encoded.
"""
# Note that ampersands must be escaped first; the rest can be escaped in
# any order.
return replace_multi(string.replace('&', '&'),
{'<': '<', '>': '>',
"'": ''', '"': '"'})
Does such a function exist, or is the standard Python idiom to use what I wrote before?
A:
Do you have an application that is running too slow and you profiled it to find that a line like this snippet is causing it to be slow? Bottlenecks occur at unexpected places.
The current snippet traverses the string 5 times, doing one thing each time. You are suggesting traversing it once, probably doing doing five things each time (or at least doing something each time). It isn't clear that this will automatically do a better job to me. Currently the algorithm used is O(n*m) (assuming the length of the string is longer than the stuff in the rules), where n is the length of the string and m is the number of substitution rules. You could, I think, reduce the algorithmic complexity to something like O(n*log(m)) and in the specific case we're in—where the original things are all only one character (but not in the case of multiple calls to replace in general)—O(n), but this doesn't matter since m is 5 but n is unbounded.
If m is held constant, then, the complexity of both solutions really goes to O(n). It is not clear to me that it is going to be a worthy task to try to turn five simple passes into one complex one, the actual time of which I cannot guess at the current moment. If there was something about it that could make it scale better, I would have thought it was much more worthwhile task.
Doing everything on one pass rather than consecutive passes also demands questions be answered about what to do about conflicting rules and how they are applied. The resolution to these questions is clear with a chain of replace.
A:
How about we just test various ways of doing this and see which comes out faster (assuming we are only caring about the fastest way to do it).
def escape1(input):
return input.replace('&', '&').replace('<', '<').replace('>', '>').replace("'", ''').replace('"', '"')
translation_table = {
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"',
}
def escape2(input):
return ''.join(translation_table.get(char, char) for char in input)
import re
_escape3_re = re.compile(r'[&<>\'"]')
def _escape3_repl(x):
s = x.group(0)
return translation_table.get(s, s)
def escape3(x):
return _escape3_re.sub(_escape3_repl, x)
def escape4(x):
return unicode(x).translate(translation_table)
test_strings = (
'Nothing in there.',
'<this is="not" a="tag" />',
'Something & Something else',
'This one is pretty long. ' * 50
)
import time
for test_i, test_string in enumerate(test_strings):
print repr(test_string)
for func in escape1, escape2, escape3, escape4:
start_time = time.time()
for i in xrange(1000):
x = func(test_string)
print '\t%s done in %.3fms' % (func.__name__, (time.time() - start_time))
print
Running this gives you:
'Nothing in there.'
escape1 done in 0.002ms
escape2 done in 0.009ms
escape3 done in 0.001ms
escape4 done in 0.005ms
'<this is="not" a="tag" />'
escape1 done in 0.002ms
escape2 done in 0.012ms
escape3 done in 0.009ms
escape4 done in 0.007ms
'Something & Something else'
escape1 done in 0.002ms
escape2 done in 0.012ms
escape3 done in 0.003ms
escape4 done in 0.007ms
'This one is pretty long. <snip>'
escape1 done in 0.008ms
escape2 done in 0.386ms
escape3 done in 0.011ms
escape4 done in 0.310ms
Looks like just replacing them one after another goes the fastest.
Edit: Running the tests again with 1000000 iterations gives the following for the first three strings (the fourth would take too long on my machine for me to wait =P):
'Nothing in there.'
escape1 done in 0.001ms
escape2 done in 0.008ms
escape3 done in 0.002ms
escape4 done in 0.005ms
'<this is="not" a="tag" />'
escape1 done in 0.002ms
escape2 done in 0.011ms
escape3 done in 0.009ms
escape4 done in 0.007ms
'Something & Something else'
escape1 done in 0.002ms
escape2 done in 0.011ms
escape3 done in 0.003ms
escape4 done in 0.007ms
The numbers are pretty much the same. In the first case they are actually even more consistent as the direct string replacement is fastest now.
A:
I prefer something clean like:
substitutions = [
('<', '<'),
('>', '>'),
...]
for search, replacement in substitutions:
string = string.replace(search, replacement)
A:
You can use reduce:
reduce(lambda s,r: s.replace(*r),
[('&', '&'),
('<', '<'),
('>', '>'),
("'", '''),
('"', '"')],
string)
A:
That's what Django does:
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return mark_safe(force_unicode(html).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", '''))
A:
In accordance with bebraw's suggestion, here is what I ended up using (in a separate module, of course):
import re
class Subs(object):
"""
A container holding strings to be searched for and replaced in
replace_multi().
Holds little relation to the sandwich.
"""
def __init__(self, needles_and_replacements):
"""
Returns a new instance of the Subs class, given a dictionary holding
the keys to be searched for and the values to be used as replacements.
"""
self.lookup = needles_and_replacements
self.regex = re.compile('|'.join(map(re.escape,
needles_and_replacements)))
def replace_multi(string, subs):
"""
Replaces given items in string efficiently in a single-pass.
"string" should be the string to be searched.
"subs" can be either:
A.) a dictionary containing as its keys the items to be
searched for and as its values the items to be replaced.
or B.) a pre-compiled instance of the Subs class from this module
(which may have slightly better performance if this is
called often).
"""
if not isinstance(subs, Subs): # Assume dictionary if not our class.
subs = Subs(subs)
lookup = subs.lookup
return subs.regex.sub(lambda match: lookup[match.group(0)], string)
Example usage:
def escape(string):
"""
Returns the given string with ampersands, quotes and angle
brackets encoded.
"""
# Note that ampersands must be escaped first; the rest can be escaped in
# any order.
escape.subs = Subs({'<': '<', '>': '>', "'": ''', '"': '"'})
return replace_multi(string.replace('&', '&'), escape.subs)
Much better :). Thanks for the help.
Edit
Nevermind, Mike Graham was right. I benchmarked it and the replacement ends up actually being much slower.
Code:
from urllib2 import urlopen
import timeit
def escape1(string):
"""
Returns the given string with ampersands, quotes and angle
brackets encoded.
"""
return string.replace('&', '&').replace('<', '<').replace('>', '>').replace("'", ''').replace('"', '"')
def escape2(string):
"""
Returns the given string with ampersands, quotes and angle
brackets encoded.
"""
# Note that ampersands must be escaped first; the rest can be escaped in
# any order.
escape2.subs = Subs({'<': '<', '>': '>', "'": ''', '"': '"'})
return replace_multi(string.replace('&', '&'), escape2.subs)
# An example test on the stackoverflow homepage.
request = urlopen('http://stackoverflow.com')
test_string = request.read()
request.close()
test1 = timeit.Timer('escape1(test_string)',
setup='from __main__ import escape1, test_string')
test2 = timeit.Timer('escape2(test_string)',
setup='from __main__ import escape2, test_string')
print 'multi-pass:', test1.timeit(2000)
print 'single-pass:', test2.timeit(2000)
Output:
multi-pass: 15.9897229671
single-pass: 66.5422530174
So much for that.
A:
Apparently it's pretty common to implement that via regex. You can find an example of this at ASPN and here.
A:
ok so i sat down and did the math. pls do not get mad at me i answer specifically discussing ΤΖΩΤΖΙΟΥ’s solution, but this would be somewhat hard to shoehorn inside a comment, so let me do it this way. i will, in fact, also air some considerations that are relevant to the OP’s question.
first up, i have been discussing with ΤΖΩΤΖΙΟΥ the elegance, correctness, and viability of his approach. turns out it looks like the proposal, while it does use an (inherently unordered) dictionary as a register to store the substitution pairs, does in fact consistently return correct results, where i had claimed it wouldn’t. this is because the call to itertools.starmap() in line 11, below, gets as its second argument an iterator over pairs of single characters/bytes (more on that later) that looks like [ ( 'h', 'h', ), ( 'e', 'e', ), ( 'l', 'l', ), ... ]. these pairs of characters/bytes is what the first argument, replacer.get, is repeatedly called with. there is not a chance to run into a situation where first '>' is transformed into '>' and then inadvertently again into '&gt;', because each character/byte is considered only once for substitution. so this part is in principle fine and algorithmically correct.
the next question is viability, and that would include a look at performance. if a vital task gets correctly completed in 0.01s using an awkward code but 1s using awesome code, then awkward might be considered preferable in practice (but only if the 1 second loss is in fact intolerable). here is the code i used for testing; it includes a number of different implementations. it is written in python 3.1 so we can use unicode greek letters for identifiers which in itself is awesome (zip in py3k returns the same as itertools.izip in py2):
import itertools #01
#02
_replacements = { #03
'&': '&', #04
'<': '<', #05
'>': '>', #06
'"': '"', #07
"'": ''', } #08
#09
def escape_ΤΖΩΤΖΙΟΥ( a_string ): #10
return ''.join( #11
itertools.starmap( #12
_replacements.get, #13
zip( a_string, a_string ) ) ) #14
#15
def escape_SIMPLE( text ): #16
return ''.join( _replacements.get( chr, chr ) for chr in text ) #17
#18
def escape_SIMPLE_optimized( text ): #19
get = _replacements.get #20
return ''.join( get( chr, chr ) for chr in text ) #21
#22
def escape_TRADITIONAL( text ): #23
return text.replace('&', '&').replace('<', '<').replace('>', '>')\ #24
.replace("'", ''').replace('"', '"') #25
these are the timing results:
escaping with SIMPLE took 5.74664253sec for 100000 items
escaping with SIMPLE_optimized took 5.11457801sec for 100000 items
escaping TRADITIONAL in-situ took 0.57543013sec for 100000 items
escaping with TRADITIONAL took 0.62347413sec for 100000 items
escaping a la ΤΖΩΤΖΙΟΥ took 2.66592320sec for 100000 items
turns out the original poster’s concern that the ‘traditional’ method gets ‘ugly quickly and appears to have poor algorithmic performance’ appears partially unwarranted when put into this context. it actually performs best; when stashed away into a function call, we do get to see a 8% performance penalty (‘calling methods is expensive’, but in general you should still do it). in comparison, ΤΖΩΤΖΙΟΥ’s implementation takes around 5 times as long as the traditional method, which, given it’s higher complexity that has to compete with python’s long-honed, optimized string methods is no surprise.
there is yet another algorithm here, the SIMPLE one. as far as i can see, this very much does exactly what ΤΖΩΤΖΙΟΥ’s method does: it iterates over the characters/bytes in the text and performs a lookup for each, then joins all the characters/bytes together and returns the resulting escaped text. you can see that where one way to do that involves a fairly lengthy and myterious formulation, the SIMPLE implementation is actually understandable at a glance.
what really trips me up here, though, is how badly the SIMPLE approach is in performance: it is around 10 times as slow as the traditional one, and also twice as slow as ΤΖΩΤΖΙΟΥ’s method. i am completely at a loss here, maybe someone can come up with an idea why this should be so. it uses only the most basic building blocks of python and works with two implicit iterations, so it avoids to build throw-away lists and everything, but it still slow, and i don’t know why.
let me conclude this code review with a remark on the merit of ΤΖΩΤΖΙΟΥ’s solution. i have made it sufficiently clear i find the code hard to read and too overblown for the task at hand. more critical than that, however, i find the way he treats characters and makes sure that for a given small range of characters they will behave in a byte-like fashion a little irritating. sure it works for the task at hand, but as soon as i iterate e.g. over the bytestring 'ΤΖΩΤΖΙΟΥ' what i do is iterate over adjacent bytes representing single characters. in most situations this is exactly what you should avoid; this is precisely the reason why in py3k ‘strings’ are now the ‘unicode objects’ of old, and the ‘strings’ of old have become ‘bytes’ and ‘bytearray’. if i was to nominate the one feature of py3k that could warrant a possibly expensive migration of code from the 2 series to the 3 series, it would be this single property of py3k. 98% of all my encoding issues have just dissolved ever since, period, and there is no clever hack that could have me seriously doubt my move. said algorithm is not ‘conceptually 8bit-clean and unicode safe’, which to me is a seriously shortcome, given this is 2010.
A:
If you work with non-Unicode strings and Python < 3.0, try an alternate translate method:
# Python < 3.0
import itertools
def escape(a_string):
replacer= dict( (chr(c),chr(c)) for c in xrange(256))
replacer.update(
{'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''}
)
return ''.join(itertools.imap(replacer.__getitem__, a_string))
if __name__ == "__main__":
print escape('''"Hello"<i> to George's friend&co.''')
$ python so2484156.py
"Hello"<i> to George's friend&co.
This is closer to a "single scan" of the input string, as per your wish.
EDIT
My intention was to create a unicode.translate equivalent that was not restricted to single-character replacements, so I came up with the answer above; I got a comment by user "flow" that was almost completely out of context, with a single correct point: the code above, as is, is intended to work with byte strings and not unicode strings. There is an obvious update (i.e. unichr() … xrange(sys.maxunicode+1)) which I strongly dislike, so I came up with another function that works on both unicode and byte strings, given that Python guarantees:
all( (chr(i)==unichr(i) and hash(chr(i))==hash(unichr(i)))
for i in xrange(128)) is True
The new function follows:
def escape(a_string):
replacer= {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
}
return ''.join(
itertools.starmap(
replacer.get, # .setdefault *might* be faster
itertools.izip(a_string, a_string)
)
)
Notice the use of starmap with a sequence of tuples: for any character not in the replacer dict, return said character.
| Is str.replace(..).replace(..) ad nauseam a standard idiom in Python? | For instance, say I wanted a function to escape a string for use in HTML (as in Django's escape filter):
def escape(string):
"""
Returns the given string with ampersands, quotes and angle
brackets encoded.
"""
return string.replace('&', '&').replace('<', '<').replace('>', '>').replace("'", ''').replace('"', '"')
This works, but it gets ugly quickly and appears to have poor algorithmic performance (in this example, the string is repeatedly traversed 5 times). What would be better is something like this:
def escape(string):
"""
Returns the given string with ampersands, quotes and angle
brackets encoded.
"""
# Note that ampersands must be escaped first; the rest can be escaped in
# any order.
return replace_multi(string.replace('&', '&'),
{'<': '<', '>': '>',
"'": ''', '"': '"'})
Does such a function exist, or is the standard Python idiom to use what I wrote before?
| [
"Do you have an application that is running too slow and you profiled it to find that a line like this snippet is causing it to be slow? Bottlenecks occur at unexpected places.\nThe current snippet traverses the string 5 times, doing one thing each time. You are suggesting traversing it once, probably doing doing five things each time (or at least doing something each time). It isn't clear that this will automatically do a better job to me. Currently the algorithm used is O(n*m) (assuming the length of the string is longer than the stuff in the rules), where n is the length of the string and m is the number of substitution rules. You could, I think, reduce the algorithmic complexity to something like O(n*log(m)) and in the specific case we're in—where the original things are all only one character (but not in the case of multiple calls to replace in general)—O(n), but this doesn't matter since m is 5 but n is unbounded.\nIf m is held constant, then, the complexity of both solutions really goes to O(n). It is not clear to me that it is going to be a worthy task to try to turn five simple passes into one complex one, the actual time of which I cannot guess at the current moment. If there was something about it that could make it scale better, I would have thought it was much more worthwhile task.\nDoing everything on one pass rather than consecutive passes also demands questions be answered about what to do about conflicting rules and how they are applied. The resolution to these questions is clear with a chain of replace.\n",
"How about we just test various ways of doing this and see which comes out faster (assuming we are only caring about the fastest way to do it).\ndef escape1(input):\n return input.replace('&', '&').replace('<', '<').replace('>', '>').replace(\"'\", ''').replace('\"', '"')\n\ntranslation_table = {\n '&': '&',\n '<': '<',\n '>': '>',\n \"'\": ''',\n '\"': '"',\n}\n\ndef escape2(input):\n return ''.join(translation_table.get(char, char) for char in input)\n\nimport re\n_escape3_re = re.compile(r'[&<>\\'\"]')\ndef _escape3_repl(x):\n s = x.group(0)\n return translation_table.get(s, s)\ndef escape3(x):\n return _escape3_re.sub(_escape3_repl, x)\n\ndef escape4(x):\n return unicode(x).translate(translation_table)\n\ntest_strings = (\n 'Nothing in there.',\n '<this is=\"not\" a=\"tag\" />',\n 'Something & Something else',\n 'This one is pretty long. ' * 50\n)\n\nimport time\n\nfor test_i, test_string in enumerate(test_strings):\n print repr(test_string)\n for func in escape1, escape2, escape3, escape4:\n start_time = time.time()\n for i in xrange(1000):\n x = func(test_string)\n print '\\t%s done in %.3fms' % (func.__name__, (time.time() - start_time))\n print\n\nRunning this gives you:\n'Nothing in there.'\n escape1 done in 0.002ms\n escape2 done in 0.009ms\n escape3 done in 0.001ms\n escape4 done in 0.005ms\n\n'<this is=\"not\" a=\"tag\" />'\n escape1 done in 0.002ms\n escape2 done in 0.012ms\n escape3 done in 0.009ms\n escape4 done in 0.007ms\n\n'Something & Something else'\n escape1 done in 0.002ms\n escape2 done in 0.012ms\n escape3 done in 0.003ms\n escape4 done in 0.007ms\n\n'This one is pretty long. <snip>'\n escape1 done in 0.008ms\n escape2 done in 0.386ms\n escape3 done in 0.011ms\n escape4 done in 0.310ms\n\nLooks like just replacing them one after another goes the fastest.\nEdit: Running the tests again with 1000000 iterations gives the following for the first three strings (the fourth would take too long on my machine for me to wait =P):\n'Nothing in there.'\n escape1 done in 0.001ms\n escape2 done in 0.008ms\n escape3 done in 0.002ms\n escape4 done in 0.005ms\n\n'<this is=\"not\" a=\"tag\" />'\n escape1 done in 0.002ms\n escape2 done in 0.011ms\n escape3 done in 0.009ms\n escape4 done in 0.007ms\n\n'Something & Something else'\n escape1 done in 0.002ms\n escape2 done in 0.011ms\n escape3 done in 0.003ms\n escape4 done in 0.007ms\n\nThe numbers are pretty much the same. In the first case they are actually even more consistent as the direct string replacement is fastest now.\n",
"I prefer something clean like:\nsubstitutions = [\n ('<', '<'),\n ('>', '>'),\n ...]\n\nfor search, replacement in substitutions:\n string = string.replace(search, replacement)\n\n",
"You can use reduce:\nreduce(lambda s,r: s.replace(*r),\n [('&', '&'),\n ('<', '<'),\n ('>', '>'),\n (\"'\", '''),\n ('\"', '"')],\n string)\n\n",
"That's what Django does:\ndef escape(html):\n \"\"\"Returns the given HTML with ampersands, quotes and carets encoded.\"\"\"\n return mark_safe(force_unicode(html).replace('&', '&').replace('<', '<').replace('>', '>').replace('\"', '"').replace(\"'\", '''))\n\n",
"In accordance with bebraw's suggestion, here is what I ended up using (in a separate module, of course):\nimport re\n\nclass Subs(object):\n \"\"\"\n A container holding strings to be searched for and replaced in\n replace_multi().\n\n Holds little relation to the sandwich.\n \"\"\"\n def __init__(self, needles_and_replacements):\n \"\"\"\n Returns a new instance of the Subs class, given a dictionary holding \n the keys to be searched for and the values to be used as replacements.\n \"\"\"\n self.lookup = needles_and_replacements\n self.regex = re.compile('|'.join(map(re.escape,\n needles_and_replacements)))\n\ndef replace_multi(string, subs):\n \"\"\"\n Replaces given items in string efficiently in a single-pass.\n\n \"string\" should be the string to be searched.\n \"subs\" can be either:\n A.) a dictionary containing as its keys the items to be\n searched for and as its values the items to be replaced.\n or B.) a pre-compiled instance of the Subs class from this module\n (which may have slightly better performance if this is\n called often).\n \"\"\"\n if not isinstance(subs, Subs): # Assume dictionary if not our class.\n subs = Subs(subs)\n lookup = subs.lookup\n return subs.regex.sub(lambda match: lookup[match.group(0)], string)\n\nExample usage:\ndef escape(string):\n \"\"\"\n Returns the given string with ampersands, quotes and angle \n brackets encoded.\n \"\"\"\n # Note that ampersands must be escaped first; the rest can be escaped in \n # any order.\n escape.subs = Subs({'<': '<', '>': '>', \"'\": ''', '\"': '"'})\n return replace_multi(string.replace('&', '&'), escape.subs)\n\nMuch better :). Thanks for the help.\nEdit\nNevermind, Mike Graham was right. I benchmarked it and the replacement ends up actually being much slower.\nCode:\nfrom urllib2 import urlopen\nimport timeit\n\ndef escape1(string):\n \"\"\"\n Returns the given string with ampersands, quotes and angle\n brackets encoded.\n \"\"\"\n return string.replace('&', '&').replace('<', '<').replace('>', '>').replace(\"'\", ''').replace('\"', '"')\n\ndef escape2(string):\n \"\"\"\n Returns the given string with ampersands, quotes and angle\n brackets encoded.\n \"\"\"\n # Note that ampersands must be escaped first; the rest can be escaped in\n # any order.\n escape2.subs = Subs({'<': '<', '>': '>', \"'\": ''', '\"': '"'})\n return replace_multi(string.replace('&', '&'), escape2.subs)\n\n# An example test on the stackoverflow homepage.\nrequest = urlopen('http://stackoverflow.com')\ntest_string = request.read()\nrequest.close()\n\ntest1 = timeit.Timer('escape1(test_string)',\n setup='from __main__ import escape1, test_string')\ntest2 = timeit.Timer('escape2(test_string)',\n setup='from __main__ import escape2, test_string')\nprint 'multi-pass:', test1.timeit(2000)\nprint 'single-pass:', test2.timeit(2000)\n\nOutput: \nmulti-pass: 15.9897229671\nsingle-pass: 66.5422530174\n\nSo much for that.\n",
"Apparently it's pretty common to implement that via regex. You can find an example of this at ASPN and here.\n",
"ok so i sat down and did the math. pls do not get mad at me i answer specifically discussing ΤΖΩΤΖΙΟΥ’s solution, but this would be somewhat hard to shoehorn inside a comment, so let me do it this way. i will, in fact, also air some considerations that are relevant to the OP’s question. \nfirst up, i have been discussing with ΤΖΩΤΖΙΟΥ the elegance, correctness, and viability of his approach. turns out it looks like the proposal, while it does use an (inherently unordered) dictionary as a register to store the substitution pairs, does in fact consistently return correct results, where i had claimed it wouldn’t. this is because the call to itertools.starmap() in line 11, below, gets as its second argument an iterator over pairs of single characters/bytes (more on that later) that looks like [ ( 'h', 'h', ), ( 'e', 'e', ), ( 'l', 'l', ), ... ]. these pairs of characters/bytes is what the first argument, replacer.get, is repeatedly called with. there is not a chance to run into a situation where first '>' is transformed into '>' and then inadvertently again into '&gt;', because each character/byte is considered only once for substitution. so this part is in principle fine and algorithmically correct.\nthe next question is viability, and that would include a look at performance. if a vital task gets correctly completed in 0.01s using an awkward code but 1s using awesome code, then awkward might be considered preferable in practice (but only if the 1 second loss is in fact intolerable). here is the code i used for testing; it includes a number of different implementations. it is written in python 3.1 so we can use unicode greek letters for identifiers which in itself is awesome (zip in py3k returns the same as itertools.izip in py2):\nimport itertools #01\n #02\n_replacements = { #03\n '&': '&', #04\n '<': '<', #05\n '>': '>', #06\n '\"': '"', #07\n \"'\": ''', } #08\n #09\ndef escape_ΤΖΩΤΖΙΟΥ( a_string ): #10\n return ''.join( #11\n itertools.starmap( #12\n _replacements.get, #13\n zip( a_string, a_string ) ) ) #14\n #15\ndef escape_SIMPLE( text ): #16\n return ''.join( _replacements.get( chr, chr ) for chr in text ) #17\n #18\ndef escape_SIMPLE_optimized( text ): #19\n get = _replacements.get #20\n return ''.join( get( chr, chr ) for chr in text ) #21\n #22\ndef escape_TRADITIONAL( text ): #23\n return text.replace('&', '&').replace('<', '<').replace('>', '>')\\ #24\n .replace(\"'\", ''').replace('\"', '"') #25\n\nthese are the timing results:\nescaping with SIMPLE took 5.74664253sec for 100000 items\nescaping with SIMPLE_optimized took 5.11457801sec for 100000 items\nescaping TRADITIONAL in-situ took 0.57543013sec for 100000 items\nescaping with TRADITIONAL took 0.62347413sec for 100000 items\nescaping a la ΤΖΩΤΖΙΟΥ took 2.66592320sec for 100000 items\n\nturns out the original poster’s concern that the ‘traditional’ method gets ‘ugly quickly and appears to have poor algorithmic performance’ appears partially unwarranted when put into this context. it actually performs best; when stashed away into a function call, we do get to see a 8% performance penalty (‘calling methods is expensive’, but in general you should still do it). in comparison, ΤΖΩΤΖΙΟΥ’s implementation takes around 5 times as long as the traditional method, which, given it’s higher complexity that has to compete with python’s long-honed, optimized string methods is no surprise. \nthere is yet another algorithm here, the SIMPLE one. as far as i can see, this very much does exactly what ΤΖΩΤΖΙΟΥ’s method does: it iterates over the characters/bytes in the text and performs a lookup for each, then joins all the characters/bytes together and returns the resulting escaped text. you can see that where one way to do that involves a fairly lengthy and myterious formulation, the SIMPLE implementation is actually understandable at a glance. \nwhat really trips me up here, though, is how badly the SIMPLE approach is in performance: it is around 10 times as slow as the traditional one, and also twice as slow as ΤΖΩΤΖΙΟΥ’s method. i am completely at a loss here, maybe someone can come up with an idea why this should be so. it uses only the most basic building blocks of python and works with two implicit iterations, so it avoids to build throw-away lists and everything, but it still slow, and i don’t know why.\nlet me conclude this code review with a remark on the merit of ΤΖΩΤΖΙΟΥ’s solution. i have made it sufficiently clear i find the code hard to read and too overblown for the task at hand. more critical than that, however, i find the way he treats characters and makes sure that for a given small range of characters they will behave in a byte-like fashion a little irritating. sure it works for the task at hand, but as soon as i iterate e.g. over the bytestring 'ΤΖΩΤΖΙΟΥ' what i do is iterate over adjacent bytes representing single characters. in most situations this is exactly what you should avoid; this is precisely the reason why in py3k ‘strings’ are now the ‘unicode objects’ of old, and the ‘strings’ of old have become ‘bytes’ and ‘bytearray’. if i was to nominate the one feature of py3k that could warrant a possibly expensive migration of code from the 2 series to the 3 series, it would be this single property of py3k. 98% of all my encoding issues have just dissolved ever since, period, and there is no clever hack that could have me seriously doubt my move. said algorithm is not ‘conceptually 8bit-clean and unicode safe’, which to me is a seriously shortcome, given this is 2010.\n",
"If you work with non-Unicode strings and Python < 3.0, try an alternate translate method:\n# Python < 3.0\nimport itertools\n\ndef escape(a_string):\n replacer= dict( (chr(c),chr(c)) for c in xrange(256))\n replacer.update(\n {'&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''}\n )\n return ''.join(itertools.imap(replacer.__getitem__, a_string))\n\nif __name__ == \"__main__\":\n print escape('''\"Hello\"<i> to George's friend&co.''')\n\n$ python so2484156.py \n"Hello"<i> to George's friend&co.\n\nThis is closer to a \"single scan\" of the input string, as per your wish.\nEDIT\nMy intention was to create a unicode.translate equivalent that was not restricted to single-character replacements, so I came up with the answer above; I got a comment by user \"flow\" that was almost completely out of context, with a single correct point: the code above, as is, is intended to work with byte strings and not unicode strings. There is an obvious update (i.e. unichr() … xrange(sys.maxunicode+1)) which I strongly dislike, so I came up with another function that works on both unicode and byte strings, given that Python guarantees:\nall( (chr(i)==unichr(i) and hash(chr(i))==hash(unichr(i)))\n for i in xrange(128)) is True\n\nThe new function follows:\ndef escape(a_string):\n replacer= {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n }\n return ''.join(\n itertools.starmap(\n replacer.get, # .setdefault *might* be faster\n itertools.izip(a_string, a_string)\n )\n )\n\nNotice the use of starmap with a sequence of tuples: for any character not in the replacer dict, return said character.\n"
] | [
24,
20,
13,
9,
7,
5,
3,
2,
1
] | [] | [] | [
"idioms",
"performance",
"python",
"replace"
] | stackoverflow_0002484156_idioms_performance_python_replace.txt |
Q:
pdb is not working in django doctests
So I created the following file (testlib.py) to automatically load all doctests (throughout my nested project directories) into the __tests__ dictionary of tests.py:
# ./testlib.py
import os, imp, re, inspect
from django.contrib.admin import site
def get_module_list(start):
all_files = os.walk(start)
file_list = [(i[0], (i[1], i[2])) for i in all_files]
file_dict = dict(file_list)
curr = start
modules = []
pathlist = []
pathstack = [[start]]
while pathstack is not None:
current_level = pathstack[len(pathstack)-1]
if len(current_level) == 0:
pathstack.pop()
if len(pathlist) == 0:
break
pathlist.pop()
continue
pathlist.append(current_level.pop())
curr = os.sep.join(pathlist)
local_files = []
for f in file_dict[curr][1]:
if f.endswith(".py") and os.path.basename(f) not in ('tests.py', 'models.py'):
local_file = re.sub('\.py$', '', f)
local_files.append(local_file)
for f in local_files:
# This is necessary because some of the imports are repopulating the registry, causing errors to be raised
site._registry.clear()
module = imp.load_module(f, *imp.find_module(f, [curr]))
modules.append(module)
pathstack.append([sub_dir for sub_dir in file_dict[curr][0] if sub_dir[0] != '.'])
return modules
def get_doc_objs(module):
ret_val = []
for obj_name in dir(module):
obj = getattr(module, obj_name)
if callable(obj):
ret_val.append(obj_name)
if inspect.isclass(obj):
ret_val.append(obj_name)
return ret_val
def has_doctest(docstring):
return ">>>" in docstring
def get_test_dict(package, locals):
test_dict = {}
for module in get_module_list(os.path.dirname(package.__file__)):
for method in get_doc_objs(module):
docstring = str(getattr(module, method).__doc__)
if has_doctest(docstring):
print "Found doctests(s) " + module.__name__ + '.' + method
# import the method itself, so doctest can find it
_temp = __import__(module.__name__, globals(), locals, [method])
locals[method] = getattr(_temp, method)
# Django looks in __test__ for doctests to run. Some extra information is
# added to the dictionary key, because otherwise the info would be hidden.
test_dict[method + "@" + module.__file__] = getattr(module, method)
return test_dict
To give credit where credit is due, much of this came from here
In my tests.py file, I have the following code:
# ./project/tests.py
import testlib, project
__test__ = testlib.get_test_dict(project, locals())
All of this works quite well to load my doctests from all of my files and subdirectories. The problem is that when I import and invoke pdb.set_trace() anywhere, this is all I see:
(Pdb) l
(Pdb) args
(Pdb) n
(Pdb) n
(Pdb) l
(Pdb) cont
doctest is apparently capturing and mediating the output itself, and is using the output in assessing the tests. So, when the test run completes, I see everything that should have printed out when I was in the pdb shell within doctest's failure report. This happens regardless of whether I invoke pdb.set_trace() inside a doctest line or inside the function or method being tested.
Obviously, this is a big drag. Doctests are great, but without an interactive pdb, I cannot debug any of the failures that they are detecting in order to fix them.
My thought process is to possibly redirect pdb's output stream to something that circumvents doctest's capture of the output, but I need some help figuring out the low-level io stuff that would be required to do that. Also, I don't even know if it would be possible, and am too unfamiliar with doctest's internals to know where to start. Anyone out there have any suggestions, or better, some code that could get this done?
A:
I was able to get pdb by tweaking it. I just put the following code at the bottom of my testlib.py file:
import sys, pdb
class TestPdb(pdb.Pdb):
def __init__(self, *args, **kwargs):
self.__stdout_old = sys.stdout
sys.stdout = sys.__stdout__
pdb.Pdb.__init__(self, *args, **kwargs)
def cmdloop(self, *args, **kwargs):
sys.stdout = sys.__stdout__
retval = pdb.Pdb.cmdloop(self, *args, **kwargs)
sys.stdout = self.__stdout_old
def pdb_trace():
debugger = TestPdb()
debugger.set_trace(sys._getframe().f_back)
In order to use the debugger I just import testlib and call testlib.pdb_trace() and am dropped into a fully functional debugger.
| pdb is not working in django doctests | So I created the following file (testlib.py) to automatically load all doctests (throughout my nested project directories) into the __tests__ dictionary of tests.py:
# ./testlib.py
import os, imp, re, inspect
from django.contrib.admin import site
def get_module_list(start):
all_files = os.walk(start)
file_list = [(i[0], (i[1], i[2])) for i in all_files]
file_dict = dict(file_list)
curr = start
modules = []
pathlist = []
pathstack = [[start]]
while pathstack is not None:
current_level = pathstack[len(pathstack)-1]
if len(current_level) == 0:
pathstack.pop()
if len(pathlist) == 0:
break
pathlist.pop()
continue
pathlist.append(current_level.pop())
curr = os.sep.join(pathlist)
local_files = []
for f in file_dict[curr][1]:
if f.endswith(".py") and os.path.basename(f) not in ('tests.py', 'models.py'):
local_file = re.sub('\.py$', '', f)
local_files.append(local_file)
for f in local_files:
# This is necessary because some of the imports are repopulating the registry, causing errors to be raised
site._registry.clear()
module = imp.load_module(f, *imp.find_module(f, [curr]))
modules.append(module)
pathstack.append([sub_dir for sub_dir in file_dict[curr][0] if sub_dir[0] != '.'])
return modules
def get_doc_objs(module):
ret_val = []
for obj_name in dir(module):
obj = getattr(module, obj_name)
if callable(obj):
ret_val.append(obj_name)
if inspect.isclass(obj):
ret_val.append(obj_name)
return ret_val
def has_doctest(docstring):
return ">>>" in docstring
def get_test_dict(package, locals):
test_dict = {}
for module in get_module_list(os.path.dirname(package.__file__)):
for method in get_doc_objs(module):
docstring = str(getattr(module, method).__doc__)
if has_doctest(docstring):
print "Found doctests(s) " + module.__name__ + '.' + method
# import the method itself, so doctest can find it
_temp = __import__(module.__name__, globals(), locals, [method])
locals[method] = getattr(_temp, method)
# Django looks in __test__ for doctests to run. Some extra information is
# added to the dictionary key, because otherwise the info would be hidden.
test_dict[method + "@" + module.__file__] = getattr(module, method)
return test_dict
To give credit where credit is due, much of this came from here
In my tests.py file, I have the following code:
# ./project/tests.py
import testlib, project
__test__ = testlib.get_test_dict(project, locals())
All of this works quite well to load my doctests from all of my files and subdirectories. The problem is that when I import and invoke pdb.set_trace() anywhere, this is all I see:
(Pdb) l
(Pdb) args
(Pdb) n
(Pdb) n
(Pdb) l
(Pdb) cont
doctest is apparently capturing and mediating the output itself, and is using the output in assessing the tests. So, when the test run completes, I see everything that should have printed out when I was in the pdb shell within doctest's failure report. This happens regardless of whether I invoke pdb.set_trace() inside a doctest line or inside the function or method being tested.
Obviously, this is a big drag. Doctests are great, but without an interactive pdb, I cannot debug any of the failures that they are detecting in order to fix them.
My thought process is to possibly redirect pdb's output stream to something that circumvents doctest's capture of the output, but I need some help figuring out the low-level io stuff that would be required to do that. Also, I don't even know if it would be possible, and am too unfamiliar with doctest's internals to know where to start. Anyone out there have any suggestions, or better, some code that could get this done?
| [
"I was able to get pdb by tweaking it. I just put the following code at the bottom of my testlib.py file:\nimport sys, pdb\nclass TestPdb(pdb.Pdb):\n def __init__(self, *args, **kwargs):\n self.__stdout_old = sys.stdout\n sys.stdout = sys.__stdout__\n pdb.Pdb.__init__(self, *args, **kwargs)\n\n def cmdloop(self, *args, **kwargs):\n sys.stdout = sys.__stdout__\n retval = pdb.Pdb.cmdloop(self, *args, **kwargs)\n sys.stdout = self.__stdout_old\n\ndef pdb_trace():\n debugger = TestPdb()\n debugger.set_trace(sys._getframe().f_back)\n\nIn order to use the debugger I just import testlib and call testlib.pdb_trace() and am dropped into a fully functional debugger.\n"
] | [
4
] | [] | [] | [
"django",
"doctest",
"pdb",
"python"
] | stackoverflow_0002882885_django_doctest_pdb_python.txt |
Q:
tkinter integration with glib mainloop
Is it possible to integrate tkinter with glib mainloop ?
A:
Here is one way of doing it:
app=TkinterApp()
def refreshApp():
app.update()
return True
gobject.idle_add(refreshApp)
loop = gobject.MainLoop()
loop.run()
| tkinter integration with glib mainloop | Is it possible to integrate tkinter with glib mainloop ?
| [
"Here is one way of doing it:\napp=TkinterApp()\n\ndef refreshApp():\n app.update()\n return True\n\ngobject.idle_add(refreshApp)\nloop = gobject.MainLoop()\nloop.run()\n\n"
] | [
2
] | [] | [] | [
"glib",
"python",
"tkinter"
] | stackoverflow_0002884528_glib_python_tkinter.txt |
Q:
Conditional operator in Mako using Pylons
In PHP, I often use the conditional operator to add an attribute to an html element if it applies to the element in question. For example:
<select name="blah">
<option value="1"<?= $blah == 1 ? ' selected="selected"' : '' ?>>
One
</option>
<option value="2"<?= $blah == 2 ? ' selected="selected"' : '' ?>>
Two
</option>
</select>
I'm starting a project with Pylons using Mako for the templating. How can I achieve something similar? Right now, I see two possibilities that are not ideal.
Solution 1:
<select name="blah">
% if blah == 1:
<option value="1" selected="selected">One</option>
% else:
<option value="1">One</option>
% endif
% if blah == 2:
<option value="2" selected="selected">Two</option>
% else:
<option value="2">Two</option>
% endif
</select>
Solution 2:
<select name="blah">
<option value="1"
% if blah == 1:
selected="selected"
% endif
>One</option>
<option value="2"
% if blah == 2:
selected="selected"
% endif
>Two</option>
</select>
In this particular case, the value is equal to the variable tested (value="1" => blah == 1), but I use the same pattern in other situations, like <?= isset($variable) ? ' value="$variable" : '' ?>.
I am looking for a clean way to achieve this using Mako.
A:
If it's running Python, the "ternary operator" is
# condition ? trueValue : falseValue
trueValue if condition else falseValue
| Conditional operator in Mako using Pylons | In PHP, I often use the conditional operator to add an attribute to an html element if it applies to the element in question. For example:
<select name="blah">
<option value="1"<?= $blah == 1 ? ' selected="selected"' : '' ?>>
One
</option>
<option value="2"<?= $blah == 2 ? ' selected="selected"' : '' ?>>
Two
</option>
</select>
I'm starting a project with Pylons using Mako for the templating. How can I achieve something similar? Right now, I see two possibilities that are not ideal.
Solution 1:
<select name="blah">
% if blah == 1:
<option value="1" selected="selected">One</option>
% else:
<option value="1">One</option>
% endif
% if blah == 2:
<option value="2" selected="selected">Two</option>
% else:
<option value="2">Two</option>
% endif
</select>
Solution 2:
<select name="blah">
<option value="1"
% if blah == 1:
selected="selected"
% endif
>One</option>
<option value="2"
% if blah == 2:
selected="selected"
% endif
>Two</option>
</select>
In this particular case, the value is equal to the variable tested (value="1" => blah == 1), but I use the same pattern in other situations, like <?= isset($variable) ? ' value="$variable" : '' ?>.
I am looking for a clean way to achieve this using Mako.
| [
"If it's running Python, the \"ternary operator\" is\n# condition ? trueValue : falseValue\ntrueValue if condition else falseValue\n\n"
] | [
5
] | [] | [] | [
"conditional_operator",
"mako",
"php",
"pylons",
"python"
] | stackoverflow_0002884696_conditional_operator_mako_php_pylons_python.txt |
Q:
Writing XML from Python : Python equivalent of .NET XmlTextWriter?
I have some IronPython code which makes use of XmlTextWriter which allows me to write code like
self.writer = System.Xml.XmlTextWriter(filename, None)
self.writer.Formatting = Formatting.Indented
self.writer.WriteStartElement(name)
self.writer.WriteString(str(text))
self.writer.WriteEndElement()
...
self.writer.Close()
I would like to make my code portable across Python implementations (CPython, IronPython and Jython). Is there a streaming Python XML writer I can use for this without needing to use either print statements, or to construct a whole DOM tree before writing it out to file?
A:
I wrote a module named loxun to do just that: http://pypi.python.org/pypi/loxun/. It runs with CPython 2.5 and Jython 2.5, but I never tried it with IronPython.
Example usage:
with open("...", "wb") as out:
xml = XmlWriter(out)
xml.addNamespace("xhtml", "http://www.w3.org/1999/xhtml")
xml.startTag("xhtml:html")
xml.startTag("xhtml:body")
xml.text("Hello world!")
xml.tag("xhtml:img", {"src": "smile.png", "alt": ":-)"})
xml.endTag()
xml.endTag()
xml.close()
And the result:
<?xml version="1.0" encoding="utf-8"?>
<xhtml:html xlmns:xhtml="http://www.w3.org/1999/xhtml">
<xhtml:body>
Hello world!
<xhtml:img alt=":-)" src="smile.png" />
</xhtml:body>
</xhtml:html>
Among other features, it detects missalligned tags while you write, uses a streaming API with a small memory footprint, supports Unicode and allows to disable pretty printing.
A:
I've never used the .NET implementation you're talking about, but it sounds like the closest you're going to get is Python's SAX parser (specifically, the XMLGenerator class -- some sample code here).
A:
I wrote a tool to facilitate XML generation from Python (code and tutorial)
| Writing XML from Python : Python equivalent of .NET XmlTextWriter? | I have some IronPython code which makes use of XmlTextWriter which allows me to write code like
self.writer = System.Xml.XmlTextWriter(filename, None)
self.writer.Formatting = Formatting.Indented
self.writer.WriteStartElement(name)
self.writer.WriteString(str(text))
self.writer.WriteEndElement()
...
self.writer.Close()
I would like to make my code portable across Python implementations (CPython, IronPython and Jython). Is there a streaming Python XML writer I can use for this without needing to use either print statements, or to construct a whole DOM tree before writing it out to file?
| [
"I wrote a module named loxun to do just that: http://pypi.python.org/pypi/loxun/. It runs with CPython 2.5 and Jython 2.5, but I never tried it with IronPython.\nExample usage:\nwith open(\"...\", \"wb\") as out:\n xml = XmlWriter(out)\n xml.addNamespace(\"xhtml\", \"http://www.w3.org/1999/xhtml\")\n xml.startTag(\"xhtml:html\")\n xml.startTag(\"xhtml:body\")\n xml.text(\"Hello world!\")\n xml.tag(\"xhtml:img\", {\"src\": \"smile.png\", \"alt\": \":-)\"})\n xml.endTag()\n xml.endTag()\n xml.close()\n\nAnd the result:\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xhtml:html xlmns:xhtml=\"http://www.w3.org/1999/xhtml\">\n <xhtml:body>\n Hello world!\n <xhtml:img alt=\":-)\" src=\"smile.png\" />\n </xhtml:body>\n</xhtml:html>\n\nAmong other features, it detects missalligned tags while you write, uses a streaming API with a small memory footprint, supports Unicode and allows to disable pretty printing.\n",
"I've never used the .NET implementation you're talking about, but it sounds like the closest you're going to get is Python's SAX parser (specifically, the XMLGenerator class -- some sample code here).\n",
"I wrote a tool to facilitate XML generation from Python (code and tutorial)\n"
] | [
3,
2,
2
] | [] | [] | [
"ironpython",
"jython",
"python",
"xml"
] | stackoverflow_0001022429_ironpython_jython_python_xml.txt |
Q:
Check to see if system volume is muted?
I am working on a project that plays audio for part of the program. I would like to be able to display a message if the user's system volume is muted. I am using Python on Windows.
A:
Use the Windows Mixer API. I've found this article for you, and attached the relevant code:
(From MS KB 181550: "Monitor Audio Volume Levels")
This is in C, but it can be "translated" to Python as well.
I hope that helps.
#include <windows.h>
#include <mmsystem.h>
MMRESULT rc; // Return code.
HMIXER hMixer; // Mixer handle used in mixer API calls.
MIXERCONTROL mxc; // Holds the mixer control data.
MIXERLINE mxl; // Holds the mixer line data.
MIXERLINECONTROLS mxlc; // Obtains the mixer control.
// Open the mixer. This opens the mixer with a deviceID of 0. If you
// have a single sound card/mixer, then this will open it. If you have
// multiple sound cards/mixers, the deviceIDs will be 0, 1, 2, and
// so on.
rc = mixerOpen(&hMixer, 0,0,0,0);
if (MMSYSERR_NOERROR != rc) {
// Couldn't open the mixer.
}
// Initialize MIXERLINE structure.
ZeroMemory(&mxl,sizeof(mxl));
mxl.cbStruct = sizeof(mxl);
// Specify the line you want to get. You are getting the input line
// here. If you want to get the output line, you need to use
// MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT.
mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
rc = mixerGetLineInfo((HMIXEROBJ)hMixer, &mxl,
MIXER_GETLINEINFOF_COMPONENTTYPE);
if (MMSYSERR_NOERROR == rc) {
// Couldn't get the mixer line.
}
// Get the control.
ZeroMemory(&mxlc, sizeof(mxlc));
mxlc.cbStruct = sizeof(mxlc);
mxlc.dwLineID = mxl.dwLineID;
mxlc.dwControlType = MIXERCONTROL_CONTROLTYPE_PEAKMETER;
mxlc.cControls = 1;
mxlc.cbmxctrl = sizeof(mxc);
mxlc.pamxctrl = &mxc;
ZeroMemory(&mxc, sizeof(mxc));
mxc.cbStruct = sizeof(mxc);
rc = mixerGetLineControls((HMIXEROBJ)hMixer,&mxlc,
MIXER_GETLINECONTROLSF_ONEBYTYPE);
if (MMSYSERR_NOERROR != rc) {
// Couldn't get the control.
}
// After successfully getting the peakmeter control, the volume range
// will be specified by mxc.Bounds.lMinimum to mxc.Bounds.lMaximum.
MIXERCONTROLDETAILS mxcd; // Gets the control values.
MIXERCONTROLDETAILS_SIGNED volStruct; // Gets the control values.
long volume; // Holds the final volume value.
// Initialize the MIXERCONTROLDETAILS structure
ZeroMemory(&mxcd, sizeof(mxcd));
mxcd.cbStruct = sizeof(mxcd);
mxcd.cbDetails = sizeof(volStruct);
mxcd.dwControlID = mxc.dwControlID;
mxcd.paDetails = &volStruct;
mxcd.cChannels = 1;
// Get the current value of the peakmeter control. Typically, you
// would set a timer in your program to query the volume every 10th
// of a second or so.
rc = mixerGetControlDetails((HMIXEROBJ)hMixer, &mxcd,
MIXER_GETCONTROLDETAILSF_VALUE);
if (MMSYSERR_NOERROR == rc) {
// Couldn't get the current volume.
}
volume = volStruct.lValue;
// Get the absolute value of the volume.
if (volume < 0)
volume = -volume;
| Check to see if system volume is muted? | I am working on a project that plays audio for part of the program. I would like to be able to display a message if the user's system volume is muted. I am using Python on Windows.
| [
"Use the Windows Mixer API. I've found this article for you, and attached the relevant code:\n(From MS KB 181550: \"Monitor Audio Volume Levels\")\nThis is in C, but it can be \"translated\" to Python as well.\nI hope that helps. \n#include <windows.h>\n#include <mmsystem.h>\n\nMMRESULT rc; // Return code.\nHMIXER hMixer; // Mixer handle used in mixer API calls.\nMIXERCONTROL mxc; // Holds the mixer control data.\nMIXERLINE mxl; // Holds the mixer line data.\nMIXERLINECONTROLS mxlc; // Obtains the mixer control.\n\n// Open the mixer. This opens the mixer with a deviceID of 0. If you\n// have a single sound card/mixer, then this will open it. If you have\n// multiple sound cards/mixers, the deviceIDs will be 0, 1, 2, and\n// so on.\nrc = mixerOpen(&hMixer, 0,0,0,0);\nif (MMSYSERR_NOERROR != rc) {\n // Couldn't open the mixer.\n}\n\n// Initialize MIXERLINE structure.\nZeroMemory(&mxl,sizeof(mxl));\nmxl.cbStruct = sizeof(mxl);\n\n// Specify the line you want to get. You are getting the input line\n// here. If you want to get the output line, you need to use\n// MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT.\nmxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;\n\nrc = mixerGetLineInfo((HMIXEROBJ)hMixer, &mxl,\n MIXER_GETLINEINFOF_COMPONENTTYPE);\nif (MMSYSERR_NOERROR == rc) {\n // Couldn't get the mixer line.\n}\n\n// Get the control.\nZeroMemory(&mxlc, sizeof(mxlc));\nmxlc.cbStruct = sizeof(mxlc);\nmxlc.dwLineID = mxl.dwLineID;\nmxlc.dwControlType = MIXERCONTROL_CONTROLTYPE_PEAKMETER;\nmxlc.cControls = 1;\nmxlc.cbmxctrl = sizeof(mxc);\nmxlc.pamxctrl = &mxc;\nZeroMemory(&mxc, sizeof(mxc));\nmxc.cbStruct = sizeof(mxc);\nrc = mixerGetLineControls((HMIXEROBJ)hMixer,&mxlc,\n MIXER_GETLINECONTROLSF_ONEBYTYPE);\nif (MMSYSERR_NOERROR != rc) {\n // Couldn't get the control.\n}\n\n// After successfully getting the peakmeter control, the volume range\n// will be specified by mxc.Bounds.lMinimum to mxc.Bounds.lMaximum.\n\nMIXERCONTROLDETAILS mxcd; // Gets the control values.\nMIXERCONTROLDETAILS_SIGNED volStruct; // Gets the control values.\nlong volume; // Holds the final volume value.\n\n// Initialize the MIXERCONTROLDETAILS structure\nZeroMemory(&mxcd, sizeof(mxcd));\nmxcd.cbStruct = sizeof(mxcd);\nmxcd.cbDetails = sizeof(volStruct);\nmxcd.dwControlID = mxc.dwControlID;\nmxcd.paDetails = &volStruct;\nmxcd.cChannels = 1;\n\n// Get the current value of the peakmeter control. Typically, you\n// would set a timer in your program to query the volume every 10th\n// of a second or so.\nrc = mixerGetControlDetails((HMIXEROBJ)hMixer, &mxcd,\n MIXER_GETCONTROLDETAILSF_VALUE);\nif (MMSYSERR_NOERROR == rc) {\n // Couldn't get the current volume.\n}\nvolume = volStruct.lValue;\n\n// Get the absolute value of the volume.\nif (volume < 0)\n volume = -volume;\n\n"
] | [
3
] | [] | [] | [
"mute",
"python",
"volume",
"windows"
] | stackoverflow_0002864507_mute_python_volume_windows.txt |
Q:
C++ Structure within itself?
I've been trying to port this code to python, but there is something I do not quite understand in C++ (I do know a bit of C++ but this is beyond me):
typedef struct huffnode_s
{
struct huffnode_s *zero;
struct huffnode_s *one;
unsigned char val;
float freq;
} huffnode_t;
What I don't get is how huffnode_s can be within itself, I've never seen this before and don't quite understand it. What does this mean, and if someone can, what would be the python equivalent?
A:
huffnode_s isn't within itself, only pointers to huffnode_s are in there. Since a pointer is of known size, it's no problem.
A:
This.
class Huffnode(object):
def __init__(self, zero, one, val, freq):
"""zero and one are Huffnode's, val is a 'char' and freq is a float."""
self.zero = zero
self.one = one
self.val = val
self.freq = freq
You can then refactor your various C functions to be methods of this class.
Or maybe this.
from collections import namedtuple
Huffnode = namedtuple( 'Huffnode', [ 'zero', 'one', 'val', 'freq' ] )
If you want your C functions to remain functions.
That's it.
h0 = Huffnode(None, None, 'x', 0.0)
h1 = Huffnode(None, None, 'y', 1.0)
h2 = Huffnode(h0, h1, 'z', 2.0)
That's all that's required.
A:
it does not have a structure in itself. it has a pointer to that structure.
in memory struct huffnode_s would look like (32 bit machine):
|------------------ huffnode_s* zero - 4 bytes --------------|
|------------------ huffnode_s* one - 4 bytes----------------|
|unsigned char val - 1 byte + 3 bytes padding=======|
|------------------- float freq - 4 bytes -------------------------|
these sizes would vary machine to machine, and how it looks in memory is decided by compiler .
A:
To add to Carl's answer, the same thing in C++ is also possible:
class Foo {
public:
Foo() {}
Foo *anotherFoo;
};
(Note the above class is silly, but the point is you can have a pointer inside a class that is of the class type)
A:
As others have noted, the references to itself are simply pointers to other instances of that structure.
The pointers within the structure would allow one to connect instances together as a linked list.
A:
(struct huffnode_s *) declares a pointer to another structure that includes same variables as the structure that it's declared in. See this question.
A:
This is a pointer to a huffnode inside of a huffnode. What this means is that you can say:
huffnode_t *node = ...;
huffnode_t *greatgreatgreatgrandchild = node->zero->zero->zero->zero->zero;
This will compile, and it will work as long as all those huffnode descendents are actually allocated and pointed to correctly.
Pointers are much like object references in JavaScript. They don't actually contain data, they just refer to it. Rest assured that you are not looking at an infinite type.
A:
This is known as a self referential structure and it is exactly what it sounds like: a structure which contains a reference to itself. A common occurrence of this is in a structure which describes a node for a linked list. Each node needs a reference to the next node in the chain.
struct linked_list_node {
int data;
struct linked_list_node *next; // <- self reference
};
| C++ Structure within itself? | I've been trying to port this code to python, but there is something I do not quite understand in C++ (I do know a bit of C++ but this is beyond me):
typedef struct huffnode_s
{
struct huffnode_s *zero;
struct huffnode_s *one;
unsigned char val;
float freq;
} huffnode_t;
What I don't get is how huffnode_s can be within itself, I've never seen this before and don't quite understand it. What does this mean, and if someone can, what would be the python equivalent?
| [
"huffnode_s isn't within itself, only pointers to huffnode_s are in there. Since a pointer is of known size, it's no problem.\n",
"This.\nclass Huffnode(object):\n def __init__(self, zero, one, val, freq):\n \"\"\"zero and one are Huffnode's, val is a 'char' and freq is a float.\"\"\"\n self.zero = zero\n self.one = one\n self.val = val\n self.freq = freq\n\nYou can then refactor your various C functions to be methods of this class.\nOr maybe this.\nfrom collections import namedtuple\nHuffnode = namedtuple( 'Huffnode', [ 'zero', 'one', 'val', 'freq' ] )\n\nIf you want your C functions to remain functions.\nThat's it.\nh0 = Huffnode(None, None, 'x', 0.0)\nh1 = Huffnode(None, None, 'y', 1.0)\nh2 = Huffnode(h0, h1, 'z', 2.0)\n\nThat's all that's required.\n",
"it does not have a structure in itself. it has a pointer to that structure. \nin memory struct huffnode_s would look like (32 bit machine):\n\n|------------------ huffnode_s* zero - 4 bytes --------------| \n|------------------ huffnode_s* one - 4 bytes----------------| \n|unsigned char val - 1 byte + 3 bytes padding=======| \n|------------------- float freq - 4 bytes -------------------------| \n\nthese sizes would vary machine to machine, and how it looks in memory is decided by compiler .\n",
"To add to Carl's answer, the same thing in C++ is also possible:\nclass Foo {\npublic:\n Foo() {}\n\n Foo *anotherFoo;\n}; \n\n(Note the above class is silly, but the point is you can have a pointer inside a class that is of the class type)\n",
"As others have noted, the references to itself are simply pointers to other instances of that structure.\nThe pointers within the structure would allow one to connect instances together as a linked list.\n",
"(struct huffnode_s *) declares a pointer to another structure that includes same variables as the structure that it's declared in. See this question.\n",
"This is a pointer to a huffnode inside of a huffnode. What this means is that you can say:\nhuffnode_t *node = ...;\nhuffnode_t *greatgreatgreatgrandchild = node->zero->zero->zero->zero->zero;\n\nThis will compile, and it will work as long as all those huffnode descendents are actually allocated and pointed to correctly.\nPointers are much like object references in JavaScript. They don't actually contain data, they just refer to it. Rest assured that you are not looking at an infinite type.\n",
"This is known as a self referential structure and it is exactly what it sounds like: a structure which contains a reference to itself. A common occurrence of this is in a structure which describes a node for a linked list. Each node needs a reference to the next node in the chain. \nstruct linked_list_node { \n int data; \n struct linked_list_node *next; // <- self reference \n}; \n\n"
] | [
19,
11,
4,
1,
0,
0,
0,
0
] | [] | [] | [
"c",
"c++",
"huffman_code",
"python"
] | stackoverflow_0002885502_c_c++_huffman_code_python.txt |
Q:
Python csv reader acting weird
So OK if I run this wrong code:
csvReader1 = csv.reader(file('new_categories.csv', "rU"), delimiter=',')
for row1 in csvReader1:
print row1[0]
print row1[8]
category_sku = str(row[8])
if category_sku == sku:
classifications["Craft"] = row[0]
classifications["Theme"] = row[1]
I get:
Knitting
391
Traceback (most recent call last):
File "upload_all_inventory_ebay.py", line 403, in <module>
inventory_item_list = get_item_list(product)
File "upload_all_inventory_ebay.py", line 294, in get_item_list
category_sku = str(row[8])
NameError: global name 'row' is not defined
Where Knitting and 391 are exactly right, of course I need to refer to row[8] as row1[8]...k so I do this:
csvReader1 = csv.reader(file('new_categories.csv', "rU"), delimiter=',')
for row1 in csvReader1:
print row1[0]
print row1[8]
category_sku = str(row1[8])
if category_sku == sku:
classifications["Craft"] = row1[0]
classifications["Theme"] = row1[1]
And I get this:
...........
Crochet
107452
Knitting
107454
Knitting
107455
Knitting
107456
Knitting
107457
Crochet
108200
Crochet
108201
Crochet
108205
Crochet
108213
Crochet
108214
Crochet
108217
108432
Quilt
108451
108482
108488
Scrapbooking
108711
Knitting
122363
Needlework
Beading
Crafts & Decorating
Crochet
Crochet
Crochet
Traceback (most recent call last):
File "upload_all_inventory_ebay.py", line 403, in <module>
inventory_item_list = get_item_list(product)
File "upload_all_inventory_ebay.py", line 292, in get_item_list
print row1[0]
IndexError: list index out of range
Where the output you see there is every effing thing in column 0 and column 1 !!!!!!!!!! Why? And WHY is row1[0] out of range if it wasn't before. YAY Fridays!
A:
The output contains results from every row because you are printing the 1st and 9th columns for every row.
row1[0] is out of range for whatever row that is because there aren't any items on that particular line of the file. You can't access the first item in row1 if row1 doesn't have any items to access. Check row1 on each loop to see if it has anything in it.
| Python csv reader acting weird | So OK if I run this wrong code:
csvReader1 = csv.reader(file('new_categories.csv', "rU"), delimiter=',')
for row1 in csvReader1:
print row1[0]
print row1[8]
category_sku = str(row[8])
if category_sku == sku:
classifications["Craft"] = row[0]
classifications["Theme"] = row[1]
I get:
Knitting
391
Traceback (most recent call last):
File "upload_all_inventory_ebay.py", line 403, in <module>
inventory_item_list = get_item_list(product)
File "upload_all_inventory_ebay.py", line 294, in get_item_list
category_sku = str(row[8])
NameError: global name 'row' is not defined
Where Knitting and 391 are exactly right, of course I need to refer to row[8] as row1[8]...k so I do this:
csvReader1 = csv.reader(file('new_categories.csv', "rU"), delimiter=',')
for row1 in csvReader1:
print row1[0]
print row1[8]
category_sku = str(row1[8])
if category_sku == sku:
classifications["Craft"] = row1[0]
classifications["Theme"] = row1[1]
And I get this:
...........
Crochet
107452
Knitting
107454
Knitting
107455
Knitting
107456
Knitting
107457
Crochet
108200
Crochet
108201
Crochet
108205
Crochet
108213
Crochet
108214
Crochet
108217
108432
Quilt
108451
108482
108488
Scrapbooking
108711
Knitting
122363
Needlework
Beading
Crafts & Decorating
Crochet
Crochet
Crochet
Traceback (most recent call last):
File "upload_all_inventory_ebay.py", line 403, in <module>
inventory_item_list = get_item_list(product)
File "upload_all_inventory_ebay.py", line 292, in get_item_list
print row1[0]
IndexError: list index out of range
Where the output you see there is every effing thing in column 0 and column 1 !!!!!!!!!! Why? And WHY is row1[0] out of range if it wasn't before. YAY Fridays!
| [
"The output contains results from every row because you are printing the 1st and 9th columns for every row.\nrow1[0] is out of range for whatever row that is because there aren't any items on that particular line of the file. You can't access the first item in row1 if row1 doesn't have any items to access. Check row1 on each loop to see if it has anything in it.\n"
] | [
2
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0002885627_csv_python.txt |
Q:
SWIG: Throwing exceptions from Python to C++
We've got an interface we've defined in C++ (abstract class, all functions pure virtual) which will be extended in Python. To overcome the cross-language polymorphism issues we're planning on using SWIG directors. I've read how to catch exceptions thrown from C++ code in our Python code here, here, here, and even on SO.
It's fairly straight forward and I'm not expecting issues with handling our library's own exceptions. What I'd like to know and can't seem to find in the documentation is how to have our Python implementation of the extended C++ interface throw those C++ exceptions in a way that makes them visible to the C++ code.
We could make small functions within the *.i files such that each function throws our exceptions:
void throw_myException(){ throw MyException; }
but I'm wondering how it will interact with the Python code.
Anyone have any experience with throwing C++ exceptions from Python code?
A:
(C)Python is written in C. It seems that it could be bad to throw exceptions "through" the interpreter.
My feeling is that it's probably safest to return a token of some sort from your API that can create an exception via a factory.
That's basically what we do here, although we're using C# instead of Python to generate the "error code" data which then gets translated to the C++ layer and then sent off to the exception factory.
| SWIG: Throwing exceptions from Python to C++ | We've got an interface we've defined in C++ (abstract class, all functions pure virtual) which will be extended in Python. To overcome the cross-language polymorphism issues we're planning on using SWIG directors. I've read how to catch exceptions thrown from C++ code in our Python code here, here, here, and even on SO.
It's fairly straight forward and I'm not expecting issues with handling our library's own exceptions. What I'd like to know and can't seem to find in the documentation is how to have our Python implementation of the extended C++ interface throw those C++ exceptions in a way that makes them visible to the C++ code.
We could make small functions within the *.i files such that each function throws our exceptions:
void throw_myException(){ throw MyException; }
but I'm wondering how it will interact with the Python code.
Anyone have any experience with throwing C++ exceptions from Python code?
| [
"(C)Python is written in C. It seems that it could be bad to throw exceptions \"through\" the interpreter.\nMy feeling is that it's probably safest to return a token of some sort from your API that can create an exception via a factory.\nThat's basically what we do here, although we're using C# instead of Python to generate the \"error code\" data which then gets translated to the C++ layer and then sent off to the exception factory.\n"
] | [
2
] | [] | [] | [
"c++",
"exception_handling",
"python",
"swig"
] | stackoverflow_0002884797_c++_exception_handling_python_swig.txt |
Q:
Errors when compiling mod_wsgi for python2.6 on Cent OS 5.3
I am running a website on CentOS 5.3. I understand centos will break if the default python 2.4 is upgraded. I followed this site (http://www.question-defense.com/2009/12/25/how-to-install-python-2-6-on-centos-5-without-breaking-yum) and got python 2.6 installed.
Now if I run "python" it runs python2.4 and if I run "python26" it runs python2.6.
I am trying to compile mod_wsgi-3.2. When it run ./configure it takes only python 2.4 environment. I have tried using the --with-python=/usr/bin/python26. That way, "make" command does not work.
Can someone throw some light on this?
Thanks in advance
Sorry for that. The output is too long.
It ends this way.
mod_wsgi.c:14519: error: 'AuthObject' has no member named 'r' mod_wsgi.c:14523:
error: 'AuthObject' has no member named 'log' mod_wsgi.c:14526:
error: 'PyExc_AttributeError' undeclared (first use in this function) mod_wsgi.c:14528:
error: 'AuthObject' has no member named 'log' mod_wsgi.c:14541: error: expected expression before ')' token mod_wsgi.c:14548:
rror: expected ';' before 'ap_log_rerror' mod_wsgi.c:14553:
error: expected ';' before '}' token mod_wsgi.c:14558:
error: too many arguments to function 'wsgi_log_python_error' mod_wsgi.c:14563:
error: expected expression before 'module' apxs:
Error: Command failed with rc=65536 . make: *** [mod_wsgi.la] Error 1
Thank you
A:
You must install the development packages for both Apache and Python. Read the instructions for installing mod_wsgi and it tells you that. See:
http://code.google.com/p/modwsgi/wiki/QuickInstallationGuide
or the README that comes with the mod_wsgi source code.
| Errors when compiling mod_wsgi for python2.6 on Cent OS 5.3 | I am running a website on CentOS 5.3. I understand centos will break if the default python 2.4 is upgraded. I followed this site (http://www.question-defense.com/2009/12/25/how-to-install-python-2-6-on-centos-5-without-breaking-yum) and got python 2.6 installed.
Now if I run "python" it runs python2.4 and if I run "python26" it runs python2.6.
I am trying to compile mod_wsgi-3.2. When it run ./configure it takes only python 2.4 environment. I have tried using the --with-python=/usr/bin/python26. That way, "make" command does not work.
Can someone throw some light on this?
Thanks in advance
Sorry for that. The output is too long.
It ends this way.
mod_wsgi.c:14519: error: 'AuthObject' has no member named 'r' mod_wsgi.c:14523:
error: 'AuthObject' has no member named 'log' mod_wsgi.c:14526:
error: 'PyExc_AttributeError' undeclared (first use in this function) mod_wsgi.c:14528:
error: 'AuthObject' has no member named 'log' mod_wsgi.c:14541: error: expected expression before ')' token mod_wsgi.c:14548:
rror: expected ';' before 'ap_log_rerror' mod_wsgi.c:14553:
error: expected ';' before '}' token mod_wsgi.c:14558:
error: too many arguments to function 'wsgi_log_python_error' mod_wsgi.c:14563:
error: expected expression before 'module' apxs:
Error: Command failed with rc=65536 . make: *** [mod_wsgi.la] Error 1
Thank you
| [
"You must install the development packages for both Apache and Python. Read the instructions for installing mod_wsgi and it tells you that. See:\nhttp://code.google.com/p/modwsgi/wiki/QuickInstallationGuide\nor the README that comes with the mod_wsgi source code.\n"
] | [
1
] | [] | [] | [
"centos5",
"mod_wsgi",
"python"
] | stackoverflow_0002883514_centos5_mod_wsgi_python.txt |
Q:
os.walk in python not running with cmd line parameter passed as path
I needed to find the number of files in a folder on the system.
This is what i used:
file_count = sum((len(f) for _, _, f in os.walk('path')))
This works fine when we specify the path as a string in quotes, but when I enter a variable name that holds the path, type(file_count) is a generator object, and hence cannot be used as an integer.
How to solve this and why does this happen?
Ok, here's what i'm doing:
in the command line at the terminal:
python mypyProg.py arg1 arg2 arg3
in myProg.py:
arg1 = sys.argv[1]
file_count = sum((len(f) for _, _, f in os.walk(arg1)))
arg1 is passed as a string
I checked repr(arg1) and type(arg1):
repr(arg1) '/home/kartik/Downloads/yahoo_dataset/tryfolder'
type(arg1) <type 'str'>
type(file_count) <type 'generator'>
Error message:
NDCG = scipy.zeros((file_count,1),float)
TypeError: an integer is required
I don't know, it is running fine in the IDLE python IDE when i enter it using just some dummy variables.
A:
I assume you're using walk because you want to know every single file in the directory and its subdirectories. I do not understand what happens here:
file_count = sum((len(f) for _, _, f in os.walk(path)))
Assuming path contains, let's say, 'src' which is a directory in my home dir I get the number of files in the dir and its descendants, so what do you mean? Are you sure you're reading correctly the path from the command line? Can you post more?
A:
sum should return an integer, as it does in my python shell, too ...
>>> x = '/tmp'
>>> file_count = sum((len(f) for _, _, f in os.walk(x)))
>>> file_count
11
>>> type(file_count)
<type 'int'>
A:
Since I had only files in that directory, i used this instead:
file_count = len([f for f in os.listdir(loadpathTest) if os.path.isfile(os.path.join(loadpathTest, f))])
This seems to work.
@All
Thanks for your help.
| os.walk in python not running with cmd line parameter passed as path | I needed to find the number of files in a folder on the system.
This is what i used:
file_count = sum((len(f) for _, _, f in os.walk('path')))
This works fine when we specify the path as a string in quotes, but when I enter a variable name that holds the path, type(file_count) is a generator object, and hence cannot be used as an integer.
How to solve this and why does this happen?
Ok, here's what i'm doing:
in the command line at the terminal:
python mypyProg.py arg1 arg2 arg3
in myProg.py:
arg1 = sys.argv[1]
file_count = sum((len(f) for _, _, f in os.walk(arg1)))
arg1 is passed as a string
I checked repr(arg1) and type(arg1):
repr(arg1) '/home/kartik/Downloads/yahoo_dataset/tryfolder'
type(arg1) <type 'str'>
type(file_count) <type 'generator'>
Error message:
NDCG = scipy.zeros((file_count,1),float)
TypeError: an integer is required
I don't know, it is running fine in the IDLE python IDE when i enter it using just some dummy variables.
| [
"I assume you're using walk because you want to know every single file in the directory and its subdirectories. I do not understand what happens here:\nfile_count = sum((len(f) for _, _, f in os.walk(path)))\nAssuming path contains, let's say, 'src' which is a directory in my home dir I get the number of files in the dir and its descendants, so what do you mean? Are you sure you're reading correctly the path from the command line? Can you post more?\n",
"sum should return an integer, as it does in my python shell, too ...\n>>> x = '/tmp'\n>>> file_count = sum((len(f) for _, _, f in os.walk(x)))\n>>> file_count\n11\n>>> type(file_count)\n<type 'int'>\n\n",
"Since I had only files in that directory, i used this instead: \nfile_count = len([f for f in os.listdir(loadpathTest) if os.path.isfile(os.path.join(loadpathTest, f))])\n\nThis seems to work.\n@All\nThanks for your help.\n"
] | [
0,
0,
0
] | [] | [] | [
"os.walk",
"python"
] | stackoverflow_0002880604_os.walk_python.txt |
Q:
What is ODBC and how can I take advantage of it (Linux)?
I am creating a master database using SQLite. This single file contains a dozen tables. I want everybody in my group to have access to it (either through Python or through the SQLite command line) and I was thinking of simply putting the file in a group readable directory and calling it 'master.db'.
Now, the buzz word 'ODBC' comes to mind.
I remember my old Windows days (thank God they're gone), when I could "register" and Excel spreadsheet into my "data sources"; it would be made visible from within any application.
Can I take advantage of this in the Linux world? Does this make any sense?
Many thanks.
A:
If it's only small numbers of people who access you db then you should be ok. However, SQlite sucks at large numbers of concurrent accesses - I switched over from sqlite to mysql when I had lots of concurrent access because the db kept getting locked.
For many concurrent accesses, you need something in between it that takes the brunt of the requests, like a (small) webserver or even a python program that can take all those requests and can regulate the access to the sqlite db. Use an ORM like SQLAlchemy or SQLObject that can access sqlite in a threadsafe way.
As for using odbc on linux to make sqlite accessible as a data source to the linux users, while ODBC certainly works on linux, and an sqlite odbc driver exists ( http://www.ch-werner.de/sqliteodbc/ ) I don't think you can 'register' your sqlite via odbc into a central list of data sources - that's pure windows...
A:
First off, here's the wikipedia article for ODBC. It's a standard software API for interacting with a database. However, I doubt you need to use it if you want to use SQLite & Python together. Python has a built-in module called sqlite3 that should help you along the way. Good Luck.
| What is ODBC and how can I take advantage of it (Linux)? | I am creating a master database using SQLite. This single file contains a dozen tables. I want everybody in my group to have access to it (either through Python or through the SQLite command line) and I was thinking of simply putting the file in a group readable directory and calling it 'master.db'.
Now, the buzz word 'ODBC' comes to mind.
I remember my old Windows days (thank God they're gone), when I could "register" and Excel spreadsheet into my "data sources"; it would be made visible from within any application.
Can I take advantage of this in the Linux world? Does this make any sense?
Many thanks.
| [
"If it's only small numbers of people who access you db then you should be ok. However, SQlite sucks at large numbers of concurrent accesses - I switched over from sqlite to mysql when I had lots of concurrent access because the db kept getting locked.\nFor many concurrent accesses, you need something in between it that takes the brunt of the requests, like a (small) webserver or even a python program that can take all those requests and can regulate the access to the sqlite db. Use an ORM like SQLAlchemy or SQLObject that can access sqlite in a threadsafe way.\nAs for using odbc on linux to make sqlite accessible as a data source to the linux users, while ODBC certainly works on linux, and an sqlite odbc driver exists ( http://www.ch-werner.de/sqliteodbc/ ) I don't think you can 'register' your sqlite via odbc into a central list of data sources - that's pure windows...\n",
"First off, here's the wikipedia article for ODBC. It's a standard software API for interacting with a database. However, I doubt you need to use it if you want to use SQLite & Python together. Python has a built-in module called sqlite3 that should help you along the way. Good Luck.\n"
] | [
1,
0
] | [] | [] | [
"odbc",
"python"
] | stackoverflow_0002885495_odbc_python.txt |
Q:
how to re-invoke python script within itself
I am trying to find the best way of re-invoking a Python script within itself. Currently it is working like http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L285. The START_CTX is created at http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L82-86.
The code is relying on sys.argv[0] as the "caller". However, this fails in cases where it is invoked with:
python script.py ...
This case does work:
python ./script.py ...
because the code uses os.chdir before running os.execlp.
I did notice os.environ["_"], but I am not sure how reliable that would be. Another possible case is to check if sys.argv[0] is not on PATH and is not executable and use sys.executable when calling os.execlp.
Any thoughts on a better approach solving this issue?
A:
I think the real issue here is that the gunicorn/arbiter.py code wants to execute the Python script with the exact same environment every time. This is important because the Python script being invoked is an unknown and it is important for it be called exactly the same way every time.
My feeling is that the problem you are experiencing has to do with the environment having changed between invokations of the Python script by the arbiter.
In http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L85-89, we see that the python executable and the args are being stored by the arbiter into self.START_CTX.
Then in http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L303-305, we see that the execvpe is called with the sys.executable, the modified args and then os.environ.
If os.environ had changed somewhere else (i.e. the PWD variable), then your executable will fail to be called properly (because you're no longer in the correct folder). The arbiter seems to take care of that possibility by storing the cwd in START_CTX. So the question remains, why is the invokation failing for you?
I tried some test code out which I wrote as follows:
#!/usr/bin/env python
import sys
import os
def main():
"""Execute twice"""
cwd = os.getcwd()
print cwd
print sys.argv
if os.path.exists("/tmp/started.txt"):
os.unlink("/tmp/started.txt")
print "Deleted /tmp/started.txt"
print
return
args = [sys.executable] + sys.argv[:]
os.system("touch /tmp/started.txt")
print "Created /tmp/started.txt"
print
os.execvpe(sys.executable, args, os.environ)
if __name__ == '__main__':
main()
When I execute this code from the command line, it works just fine:
guest@desktop:~/Python/Test$ python selfreferential.py
/Users/guest/Python/Test
['selfreferential.py']
Created /tmp/started.txt
/Users/guest/Python/Test
['selfreferential.py']
Deleted /tmp/started.txt
guest@desktop:~/Python/Test$ python ./selfreferential.py
/Users/guest/Python/Test
['./selfreferential.py']
Created /tmp/started.txt
/Users/guest/Python/Test
['./selfreferential.py']
Deleted /tmp/started.txt
guest@desktop:~/Python/Test$ cd
guest@desktop:~$ python Python/Test/selfreferential.py
/Users/guest
['Python/Test/selfreferential.py']
Created /tmp/started.txt
/Users/guest
['Python/Test/selfreferential.py']
Deleted /tmp/started.txt
guest@desktop:~$ python /Users/guest/Python/Test/selfreferential.py
/Users/guest
['/Users/guest/Python/Test/selfreferential.py']
Created /tmp/started.txt
/Users/guest
['/Users/guest/Python/Test/selfreferential.py']
Deleted /tmp/started.txt
guest@desktop:~$
As you can see, there was no problem doing what gunicorn was doing. So, maybe your problem has something to do with the environment variable. Or maybe is has something to do with the way your operating system executes things.
A:
I would suggest a different approach. Wrapp all of the script functionality into a single function, which gets called when the script is executed, which can recursively call itself, instead of executing a new process.
| how to re-invoke python script within itself | I am trying to find the best way of re-invoking a Python script within itself. Currently it is working like http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L285. The START_CTX is created at http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L82-86.
The code is relying on sys.argv[0] as the "caller". However, this fails in cases where it is invoked with:
python script.py ...
This case does work:
python ./script.py ...
because the code uses os.chdir before running os.execlp.
I did notice os.environ["_"], but I am not sure how reliable that would be. Another possible case is to check if sys.argv[0] is not on PATH and is not executable and use sys.executable when calling os.execlp.
Any thoughts on a better approach solving this issue?
| [
"I think the real issue here is that the gunicorn/arbiter.py code wants to execute the Python script with the exact same environment every time. This is important because the Python script being invoked is an unknown and it is important for it be called exactly the same way every time.\nMy feeling is that the problem you are experiencing has to do with the environment having changed between invokations of the Python script by the arbiter.\n\nIn http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L85-89, we see that the python executable and the args are being stored by the arbiter into self.START_CTX. \nThen in http://github.com/benoitc/gunicorn/blob/master/gunicorn/arbiter.py#L303-305, we see that the execvpe is called with the sys.executable, the modified args and then os.environ.\n\nIf os.environ had changed somewhere else (i.e. the PWD variable), then your executable will fail to be called properly (because you're no longer in the correct folder). The arbiter seems to take care of that possibility by storing the cwd in START_CTX. So the question remains, why is the invokation failing for you?\nI tried some test code out which I wrote as follows:\n#!/usr/bin/env python\nimport sys\nimport os\n\ndef main():\n \"\"\"Execute twice\"\"\"\n\n cwd = os.getcwd()\n\n print cwd\n print sys.argv\n\n if os.path.exists(\"/tmp/started.txt\"):\n os.unlink(\"/tmp/started.txt\")\n print \"Deleted /tmp/started.txt\"\n print\n return\n\n args = [sys.executable] + sys.argv[:]\n os.system(\"touch /tmp/started.txt\")\n print \"Created /tmp/started.txt\"\n print\n os.execvpe(sys.executable, args, os.environ)\n\nif __name__ == '__main__':\n main()\n\nWhen I execute this code from the command line, it works just fine:\nguest@desktop:~/Python/Test$ python selfreferential.py \n/Users/guest/Python/Test\n['selfreferential.py']\nCreated /tmp/started.txt\n\n/Users/guest/Python/Test\n['selfreferential.py']\nDeleted /tmp/started.txt\n\nguest@desktop:~/Python/Test$ python ./selfreferential.py \n/Users/guest/Python/Test\n['./selfreferential.py']\nCreated /tmp/started.txt\n\n/Users/guest/Python/Test\n['./selfreferential.py']\nDeleted /tmp/started.txt\n\nguest@desktop:~/Python/Test$ cd\nguest@desktop:~$ python Python/Test/selfreferential.py \n/Users/guest\n['Python/Test/selfreferential.py']\nCreated /tmp/started.txt\n\n/Users/guest\n['Python/Test/selfreferential.py']\nDeleted /tmp/started.txt\n\nguest@desktop:~$ python /Users/guest/Python/Test/selfreferential.py \n/Users/guest\n['/Users/guest/Python/Test/selfreferential.py']\nCreated /tmp/started.txt\n\n/Users/guest\n['/Users/guest/Python/Test/selfreferential.py']\nDeleted /tmp/started.txt\n\nguest@desktop:~$ \n\nAs you can see, there was no problem doing what gunicorn was doing. So, maybe your problem has something to do with the environment variable. Or maybe is has something to do with the way your operating system executes things.\n",
"I would suggest a different approach. Wrapp all of the script functionality into a single function, which gets called when the script is executed, which can recursively call itself, instead of executing a new process.\n"
] | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002846416_python.txt |
Q:
what does 'cgi.parse_qs' mean
i find this code :
def _oauth_parse_response(body):
p = cgi.parse_qs(body, keep_blank_values=False)
but i don't know what is mean
thanks
A:
It means "look on the cgi object for an attribute called parse_qs, and call it as a function with body as a positional argument and keep_blank_values as a keyword argument with the value of False".
For the definition of cgi look further up, but it probably is the stdlib module of the same name.
A:
docs.python.org has an excellent search engine, which will show you this:
This function is deprecated in this
module. Use urllib.parse.parse_qs()
instead. It is maintained here only
for backward compatibility.
and once you follow the link, you see:
Parse a query string given as a string
argument (data of type
application/x-www-form-urlencoded).
Data are returned as a dictionary. The
dictionary keys are the unique query
variable names and the values are
lists of values for each name.
and so on.
Much as I may like getting easy rep for answering absolutely trivial questions that anybody with a pulse should have zero trouble answering for themselves, maybe with some help from today's reasonably powerful search engines, some questions are really too easy to answer -- the stackoverflow equivalent of shooting sitting birds. You're not a newbie here -- why not, and I'm going to suggest an absolutely revolutionary strategy!, make the microscopic effort of doing your own searches and asking questions when there is something worth asking?
A:
Parses a query string into a dictionary.
Deprecated in python >= 2.6.
| what does 'cgi.parse_qs' mean | i find this code :
def _oauth_parse_response(body):
p = cgi.parse_qs(body, keep_blank_values=False)
but i don't know what is mean
thanks
| [
"It means \"look on the cgi object for an attribute called parse_qs, and call it as a function with body as a positional argument and keep_blank_values as a keyword argument with the value of False\".\nFor the definition of cgi look further up, but it probably is the stdlib module of the same name.\n",
"docs.python.org has an excellent search engine, which will show you this:\n\nThis function is deprecated in this\n module. Use urllib.parse.parse_qs()\n instead. It is maintained here only\n for backward compatibility.\n\nand once you follow the link, you see:\n\nParse a query string given as a string\n argument (data of type\n application/x-www-form-urlencoded).\n Data are returned as a dictionary. The\n dictionary keys are the unique query\n variable names and the values are\n lists of values for each name.\n\nand so on.\nMuch as I may like getting easy rep for answering absolutely trivial questions that anybody with a pulse should have zero trouble answering for themselves, maybe with some help from today's reasonably powerful search engines, some questions are really too easy to answer -- the stackoverflow equivalent of shooting sitting birds. You're not a newbie here -- why not, and I'm going to suggest an absolutely revolutionary strategy!, make the microscopic effort of doing your own searches and asking questions when there is something worth asking?\n",
"Parses a query string into a dictionary. \nDeprecated in python >= 2.6.\n"
] | [
5,
4,
3
] | [] | [] | [
"python"
] | stackoverflow_0002886611_python.txt |
Q:
Streaming audio (YouTube)
I'm writing a CLI for a music-media-platform. One of the features is going to be that you can directly play YouTube videos from the CLI. I don't really have an idea of how to do it, but this one sounded the most reasonable:
I'm going to use of those sites where you can download music from YouTube, for example, http://keepvid.com/ and then I directly stream and play this, but I have one problem. Is there any Python library capable of doing this and if so, do you have any concrete examples?
I've been looking, but I found nothing, even not with GStreamer.
A:
You need two things to be able to download a YouTube video, the video id, which is represented by the v= section of the URL, and a hidden field t= which is present in the page source. I have no idea what this t value is, but it's what you need :)
You can then download the video using a URL in the format;
http://www.youtube.com/get_video?video_id=*******&t=*******
Where the stars represent the values obtained.
I'm guessing you can ask for the video id from user input, as it's straightforward to obtain. Your program would then download the HTML source for that video, parse the source for the t value, then download the video using the newly constructed URL.
For example, if you open this link in your browser, it should download the video, or you can use a downloading program such as Wget;
http://www.youtube.com/get_video?video_id=3HrSN7176XI&t=vjVQa1PpcFNM4c8MbEhsnGaNvYKoYERIJ-hK7ErLpUI=
A:
It appears that KeepVid is simply a JavaScript bookmarklet that links you to a KeepVid download page where you can then download the YouTube video in any one of a variety of formats. So, unless you want to figure out how to stream the file that it links you to, it's not easily doable. You'd have to scrape the page returned and figure out which URL you wanted to download, and then you'd have to stream from that URL (and some of the formats may or may not be streamable anyway).
And as an aside, even though they don't have a terms of service specified, I'd imagine that since they appear to be mostly advertisement-supported that abusing their functionality by going around their advertisement-supported webpage would be ethically questionable.
| Streaming audio (YouTube) | I'm writing a CLI for a music-media-platform. One of the features is going to be that you can directly play YouTube videos from the CLI. I don't really have an idea of how to do it, but this one sounded the most reasonable:
I'm going to use of those sites where you can download music from YouTube, for example, http://keepvid.com/ and then I directly stream and play this, but I have one problem. Is there any Python library capable of doing this and if so, do you have any concrete examples?
I've been looking, but I found nothing, even not with GStreamer.
| [
"You need two things to be able to download a YouTube video, the video id, which is represented by the v= section of the URL, and a hidden field t= which is present in the page source. I have no idea what this t value is, but it's what you need :)\nYou can then download the video using a URL in the format;\nhttp://www.youtube.com/get_video?video_id=*******&t=*******\n\nWhere the stars represent the values obtained.\nI'm guessing you can ask for the video id from user input, as it's straightforward to obtain. Your program would then download the HTML source for that video, parse the source for the t value, then download the video using the newly constructed URL.\nFor example, if you open this link in your browser, it should download the video, or you can use a downloading program such as Wget;\nhttp://www.youtube.com/get_video?video_id=3HrSN7176XI&t=vjVQa1PpcFNM4c8MbEhsnGaNvYKoYERIJ-hK7ErLpUI=\n",
"It appears that KeepVid is simply a JavaScript bookmarklet that links you to a KeepVid download page where you can then download the YouTube video in any one of a variety of formats. So, unless you want to figure out how to stream the file that it links you to, it's not easily doable. You'd have to scrape the page returned and figure out which URL you wanted to download, and then you'd have to stream from that URL (and some of the formats may or may not be streamable anyway).\nAnd as an aside, even though they don't have a terms of service specified, I'd imagine that since they appear to be mostly advertisement-supported that abusing their functionality by going around their advertisement-supported webpage would be ethically questionable.\n"
] | [
2,
0
] | [] | [] | [
"audio",
"python",
"stream",
"youtube"
] | stackoverflow_0002884588_audio_python_stream_youtube.txt |
Q:
Scrapy Could not find spider Error
I have been trying to get a simple spider to run with scrapy, but keep getting the error:
Could not find spider for domain:stackexchange.com
when I run the code with the expression scrapy-ctl.py crawl stackexchange.com. The spider is as follow:
from scrapy.spider import BaseSpider
from __future__ import absolute_import
class StackExchangeSpider(BaseSpider):
domain_name = "stackexchange.com"
start_urls = [
"http://www.stackexchange.com/",
]
def parse(self, response):
filename = response.url.split("/")[-2]
open(filename, 'wb').write(response.body)
SPIDER = StackExchangeSpider()`
Another person posted almost the exact same problem months ago but did not say how they fixed it, Scrapy spider is not working
I have been following the turtorial exactly at http://doc.scrapy.org/intro/tutorial.html, and cannot figure out why it is not working.
When I run this code in eclipse I get the error
Traceback (most recent call last):
File "D:\Python Documents\dmoz\stackexchange\stackexchange\spiders\stackexchange_spider.py", line 1, in <module>
from scrapy.spider import BaseSpider
ImportError: No module named scrapy.spider
I cannot figure out why it is not finding the base Spider module. Does my spider have to be saved in the scripts directory?
A:
try running python yourproject/spiders/domain.py to see if there are any syntax error. I don't think you should enable absolute import as scrapy relies on relatives imports.
| Scrapy Could not find spider Error | I have been trying to get a simple spider to run with scrapy, but keep getting the error:
Could not find spider for domain:stackexchange.com
when I run the code with the expression scrapy-ctl.py crawl stackexchange.com. The spider is as follow:
from scrapy.spider import BaseSpider
from __future__ import absolute_import
class StackExchangeSpider(BaseSpider):
domain_name = "stackexchange.com"
start_urls = [
"http://www.stackexchange.com/",
]
def parse(self, response):
filename = response.url.split("/")[-2]
open(filename, 'wb').write(response.body)
SPIDER = StackExchangeSpider()`
Another person posted almost the exact same problem months ago but did not say how they fixed it, Scrapy spider is not working
I have been following the turtorial exactly at http://doc.scrapy.org/intro/tutorial.html, and cannot figure out why it is not working.
When I run this code in eclipse I get the error
Traceback (most recent call last):
File "D:\Python Documents\dmoz\stackexchange\stackexchange\spiders\stackexchange_spider.py", line 1, in <module>
from scrapy.spider import BaseSpider
ImportError: No module named scrapy.spider
I cannot figure out why it is not finding the base Spider module. Does my spider have to be saved in the scripts directory?
| [
"try running python yourproject/spiders/domain.py to see if there are any syntax error. I don't think you should enable absolute import as scrapy relies on relatives imports.\n"
] | [
2
] | [] | [] | [
"dns",
"python",
"scrapy"
] | stackoverflow_0002886503_dns_python_scrapy.txt |
Q:
Cookies with urllib
This will probably seem like a really simple question, and I am quite confused as to why this is so difficult for me.
I would like to write a function that takes three inputs: [url, data, cookies] that will use urllib (not urllib2) to get the contents of the requested url.
I figured it'd be simple, so I wrote the following:
def fetch(url, data = None, cookies = None):
if isinstance(data, dict): data = urllib.urlencode(data)
if isinstance(cookies, dict):
# TODO: find a better way to do this
cookies = "; ".join([str(key) + "=" + str(cookies[key]) for key in cookies])
opener = urllib.FancyURLopener()
opener.addheader("Cookie", cookies)
obj = opener.open(url, data)
result = obj.read()
obj.close()
return result
This doesn't work, as far as I can tell (can anyone confirm that?) and I'm stumped.
A:
You didn't say what went wrong when you tried it, or what http server you're testing with. Did the request complete? Did the server fail to recognize your cookies? One thing that jumps out at me is that you're potentially joining multiple cookies into a single header field. Does it work if you use separate Cookie: header fields?
| Cookies with urllib | This will probably seem like a really simple question, and I am quite confused as to why this is so difficult for me.
I would like to write a function that takes three inputs: [url, data, cookies] that will use urllib (not urllib2) to get the contents of the requested url.
I figured it'd be simple, so I wrote the following:
def fetch(url, data = None, cookies = None):
if isinstance(data, dict): data = urllib.urlencode(data)
if isinstance(cookies, dict):
# TODO: find a better way to do this
cookies = "; ".join([str(key) + "=" + str(cookies[key]) for key in cookies])
opener = urllib.FancyURLopener()
opener.addheader("Cookie", cookies)
obj = opener.open(url, data)
result = obj.read()
obj.close()
return result
This doesn't work, as far as I can tell (can anyone confirm that?) and I'm stumped.
| [
"You didn't say what went wrong when you tried it, or what http server you're testing with. Did the request complete? Did the server fail to recognize your cookies? One thing that jumps out at me is that you're potentially joining multiple cookies into a single header field. Does it work if you use separate Cookie: header fields?\n"
] | [
1
] | [] | [] | [
"cookies",
"python",
"urllib"
] | stackoverflow_0002886573_cookies_python_urllib.txt |
Q:
how to import a 'zip' file to my .py
when i use http://github.com/joshthecoder/tweepy-examples ,
i find :
import tweepy
in the appengine\oauth_example\handlers.py
but i can't find a tweepy file or tweepy's 'py' file, except a tweepy.zip file,
i don't think this is right,cauz i never import a zip file,
i find this in app.py:
import sys
sys.path.insert(0, 'tweepy.zip')
why ?
how to import a zip file..
thanks
updated
a.py :
import sys
sys.path.insert(0, 'b.zip')
import b
print b
b.zip:
b file
|-----__init__.py
|-----c.py
c.py:
cc='ccccc'
the error is :
> "D:\Python25\pythonw.exe" "D:\zjm_code\a.py"
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 9, in <module>
import b
ImportError: No module named b
updated2
it is ok now ,
the error's reason is : i rename b.rar to b.zip
A:
The name of the zip file is irrelevent when searching for modules - this allows you to include version numbers in the file name, such as my_b_package.1.2.3.zip.
To import from a zip file, you need to replicate the full package structure within it. In this case, you need a package b, with the __init__.py and c.py modules.
I.e:
b.zip
|
| -- b <dir>
| -- __init__.py
| -- c.py
A:
You don't import zip files, you add them to sys.path so that you can import modules within them. sys.path is a list, and as such the normal list methods/operations (e.g. .append()) all work on it.
| how to import a 'zip' file to my .py | when i use http://github.com/joshthecoder/tweepy-examples ,
i find :
import tweepy
in the appengine\oauth_example\handlers.py
but i can't find a tweepy file or tweepy's 'py' file, except a tweepy.zip file,
i don't think this is right,cauz i never import a zip file,
i find this in app.py:
import sys
sys.path.insert(0, 'tweepy.zip')
why ?
how to import a zip file..
thanks
updated
a.py :
import sys
sys.path.insert(0, 'b.zip')
import b
print b
b.zip:
b file
|-----__init__.py
|-----c.py
c.py:
cc='ccccc'
the error is :
> "D:\Python25\pythonw.exe" "D:\zjm_code\a.py"
Traceback (most recent call last):
File "D:\zjm_code\a.py", line 9, in <module>
import b
ImportError: No module named b
updated2
it is ok now ,
the error's reason is : i rename b.rar to b.zip
| [
"The name of the zip file is irrelevent when searching for modules - this allows you to include version numbers in the file name, such as my_b_package.1.2.3.zip. \nTo import from a zip file, you need to replicate the full package structure within it. In this case, you need a package b, with the __init__.py and c.py modules.\nI.e:\nb.zip\n|\n| -- b <dir>\n | -- __init__.py\n | -- c.py\n\n",
"You don't import zip files, you add them to sys.path so that you can import modules within them. sys.path is a list, and as such the normal list methods/operations (e.g. .append()) all work on it.\n"
] | [
11,
3
] | [] | [] | [
"import",
"python",
"zip"
] | stackoverflow_0002886850_import_python_zip.txt |
Q:
Django Barcode for store sales
I am in process of converting Visual Basic app into Python Django. Currently, it has barcode functionality to process sales at a store. Can this be achieved with python django.
A:
If your definition of barcode functionality is the ability to read and write barcodes, you should keep in mind two things.
Barcodes are actually read by barcode readers, and from the computers' point of view they are just input devices, just like keyboards. When the reader reads a barcode, it just "types" it in, character by character. Usually it's configurable what the reader sends after the code, tab or enter are quite common options. Enter is the easiest to deal with.
There's nothing special in writing barcodes, it's just text with a special font, with *-characters before and after the code.
Handling barcodes doesn't really have much to do with Django. Some tricks are required to get it done within browsers, but these would apply if you were doing it in RoR, .net or whatever:
Handling barcodes from a web app is quite straightforward. A text input is needed and a bit of javascript to make sure the input has focus, and to trigger action when a barcode has been read.
Printing barcodes is not very hard either, just use css3 embedded fonts. If that's too cutting edge, you can always create images of the barcodes server-side, and it'll work with any browser.
| Django Barcode for store sales | I am in process of converting Visual Basic app into Python Django. Currently, it has barcode functionality to process sales at a store. Can this be achieved with python django.
| [
"If your definition of barcode functionality is the ability to read and write barcodes, you should keep in mind two things.\n\nBarcodes are actually read by barcode readers, and from the computers' point of view they are just input devices, just like keyboards. When the reader reads a barcode, it just \"types\" it in, character by character. Usually it's configurable what the reader sends after the code, tab or enter are quite common options. Enter is the easiest to deal with.\nThere's nothing special in writing barcodes, it's just text with a special font, with *-characters before and after the code.\n\nHandling barcodes doesn't really have much to do with Django. Some tricks are required to get it done within browsers, but these would apply if you were doing it in RoR, .net or whatever:\n\nHandling barcodes from a web app is quite straightforward. A text input is needed and a bit of javascript to make sure the input has focus, and to trigger action when a barcode has been read.\nPrinting barcodes is not very hard either, just use css3 embedded fonts. If that's too cutting edge, you can always create images of the barcodes server-side, and it'll work with any browser.\n\n"
] | [
9
] | [] | [] | [
"django",
"python",
"vb6"
] | stackoverflow_0002887045_django_python_vb6.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.