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:
Why is my data not being represented properly in my SQLAchemy model?
I have a peculiar SQLAlchemy ORM problem. This is occurring in a Pylons application, against a Postgresql 8.2 database using psycopg2 as my database driver under SQLAlchemy 0.6.0 (and tried with 0.6.4 as well)
I have defined a User model object that has (at minimum) the following properties:
class User(Base):
__tablename__ = 'users'
__table_args__ = (saschema.UniqueConstraint("login", "company_id"), {})
__mapper_args__ = {
'order_by' : 'lower(users.name)',
}
user_id = Column(Integer, primary_key=True)
email = Column(String)
login = Column(String)
company_id = Column(String, ForeignKey('company.company_id'))
There are others, but those are all that are germane, I think.
I am editing an instance of this in a session using this code (it deals with some of those other properties):
def do_update(user_id):
existing = Session().query(User).filter_by(user_id=user_id).one()
for field in ('login', 'email', 'name', 'is_admin_user'): # only email changes; it's set to "" from "foo@bar.com"
if field in params:
setattr(existing, field, params[field])
if 'advanis_portal_user_id' in params:
if not existing.portal_link:
existing.portal_link = UserPortalLink()
existing.portal_link.advanis_portal_user_id = params['advanis_portal_user_id']
if 'password' in params and existing.password:
existing.password.password = Password.encrypt(existing.login, params['password'])
UserValidator(existing) # raises an exception
self._commit()
return existing
Note the two comments; they describe the sequence of events. Especially, the exception that is raised before the commit.
What I'm doing is taking a User whose email field is set to 'user@example.com' and setting it to '', which causes the validator to raise an exception. Subsequent to this, even after a restart of the Pylons server, users returned by the following query have '' for an email address! These two queries return a user with the '' email address:
Session().query(User).filter_by(login=login, company_id=company).one()
Session().query(User).all()
Here's the SQL/parameters/response for the first one of these two queries:
[sqlalchemy.engine.base.Engine] BEGIN
[sqlalchemy.engine.base.Engine] SELECT users.user_id AS users_user_id, users.login AS users_login, users.name AS users_name, users.email AS users_email, users.company_id AS users_company_id, users.is_admin_user AS users_is_admin_user
FROM users
WHERE %(param_1)s = users.company_id ORDER BY lower(users.name)
[sqlalchemy.engine.base.Engine] {'param_1': u'offby1'}
[sqlalchemy.engine.base.Engine] Col ('users_user_id', 'users_login', 'users_name', 'users_email', 'users_company_id', 'users_is_admin_user')
[sqlalchemy.engine.base.Engine] Row (8, u'newuser', u'A new user', u'chris.rose@advanis.ca', u'offby1', False)
[sqlalchemy.engine.base.Engine] Row (3, u'crose', u'Chris Rose', u'chris.rose@advanis.ca', u'offby1', True)
Note that the email address is returned. This object is encoded as JSON and sent over the wire, and by that time the email property is ''
This query returns the complete user with the email address (Note that this is all the same object!):
Session().query(User).filter_by(user_id=user_id).one()
Here's the detailed logging for that query:
[sqlalchemy.engine.base.Engine] BEGIN
[sqlalchemy.engine.base.Engine] SELECT users.user_id AS users_user_id, users.login AS users_login, users.name AS users_name, users.email AS users_email, users.company_id AS users_company_id, users.is_admin_user AS users_is_admin_user
FROM users
WHERE users.user_id = %(user_id_1)s ORDER BY lower(users.name)
[sqlalchemy.engine.base.Engine] {'user_id_1': u'3'}
[sqlalchemy.engine.base.Engine] Col ('users_user_id', 'users_login', 'users_name', 'users_email', 'users_company_id', 'users_is_admin_user')
[sqlalchemy.engine.base.Engine] Row (3, u'crose', u'Chris Rose', u'chris.rose@advanis.ca', u'offby1', True)
For this query, I get the right user email address back.
What's happening here, and how do I fix it?
A:
I'm not familiar with pylons, but your database returns seem OK (since the email column isn't empty). Is there some sort of caching with pylons?
A:
This is a stab in the dark, but try using Session.commit() instead of self._commit().
| Why is my data not being represented properly in my SQLAchemy model? | I have a peculiar SQLAlchemy ORM problem. This is occurring in a Pylons application, against a Postgresql 8.2 database using psycopg2 as my database driver under SQLAlchemy 0.6.0 (and tried with 0.6.4 as well)
I have defined a User model object that has (at minimum) the following properties:
class User(Base):
__tablename__ = 'users'
__table_args__ = (saschema.UniqueConstraint("login", "company_id"), {})
__mapper_args__ = {
'order_by' : 'lower(users.name)',
}
user_id = Column(Integer, primary_key=True)
email = Column(String)
login = Column(String)
company_id = Column(String, ForeignKey('company.company_id'))
There are others, but those are all that are germane, I think.
I am editing an instance of this in a session using this code (it deals with some of those other properties):
def do_update(user_id):
existing = Session().query(User).filter_by(user_id=user_id).one()
for field in ('login', 'email', 'name', 'is_admin_user'): # only email changes; it's set to "" from "foo@bar.com"
if field in params:
setattr(existing, field, params[field])
if 'advanis_portal_user_id' in params:
if not existing.portal_link:
existing.portal_link = UserPortalLink()
existing.portal_link.advanis_portal_user_id = params['advanis_portal_user_id']
if 'password' in params and existing.password:
existing.password.password = Password.encrypt(existing.login, params['password'])
UserValidator(existing) # raises an exception
self._commit()
return existing
Note the two comments; they describe the sequence of events. Especially, the exception that is raised before the commit.
What I'm doing is taking a User whose email field is set to 'user@example.com' and setting it to '', which causes the validator to raise an exception. Subsequent to this, even after a restart of the Pylons server, users returned by the following query have '' for an email address! These two queries return a user with the '' email address:
Session().query(User).filter_by(login=login, company_id=company).one()
Session().query(User).all()
Here's the SQL/parameters/response for the first one of these two queries:
[sqlalchemy.engine.base.Engine] BEGIN
[sqlalchemy.engine.base.Engine] SELECT users.user_id AS users_user_id, users.login AS users_login, users.name AS users_name, users.email AS users_email, users.company_id AS users_company_id, users.is_admin_user AS users_is_admin_user
FROM users
WHERE %(param_1)s = users.company_id ORDER BY lower(users.name)
[sqlalchemy.engine.base.Engine] {'param_1': u'offby1'}
[sqlalchemy.engine.base.Engine] Col ('users_user_id', 'users_login', 'users_name', 'users_email', 'users_company_id', 'users_is_admin_user')
[sqlalchemy.engine.base.Engine] Row (8, u'newuser', u'A new user', u'chris.rose@advanis.ca', u'offby1', False)
[sqlalchemy.engine.base.Engine] Row (3, u'crose', u'Chris Rose', u'chris.rose@advanis.ca', u'offby1', True)
Note that the email address is returned. This object is encoded as JSON and sent over the wire, and by that time the email property is ''
This query returns the complete user with the email address (Note that this is all the same object!):
Session().query(User).filter_by(user_id=user_id).one()
Here's the detailed logging for that query:
[sqlalchemy.engine.base.Engine] BEGIN
[sqlalchemy.engine.base.Engine] SELECT users.user_id AS users_user_id, users.login AS users_login, users.name AS users_name, users.email AS users_email, users.company_id AS users_company_id, users.is_admin_user AS users_is_admin_user
FROM users
WHERE users.user_id = %(user_id_1)s ORDER BY lower(users.name)
[sqlalchemy.engine.base.Engine] {'user_id_1': u'3'}
[sqlalchemy.engine.base.Engine] Col ('users_user_id', 'users_login', 'users_name', 'users_email', 'users_company_id', 'users_is_admin_user')
[sqlalchemy.engine.base.Engine] Row (3, u'crose', u'Chris Rose', u'chris.rose@advanis.ca', u'offby1', True)
For this query, I get the right user email address back.
What's happening here, and how do I fix it?
| [
"I'm not familiar with pylons, but your database returns seem OK (since the email column isn't empty). Is there some sort of caching with pylons?\n",
"This is a stab in the dark, but try using Session.commit() instead of self._commit().\n"
] | [
0,
0
] | [] | [] | [
"orm",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0003752674_orm_pylons_python_sqlalchemy.txt |
Q:
Print info about exception in python 2.5?
Python 2.5 won't let me use this syntax:
try:
code_that_raises_exception()
except Exception as e:
print e
raise
So how should I print information about an exception?
Thanks
EDIT: I'm writing a plugin for a program that includes kind of a pseudo python interpreter. It prints print statements but doesn't show exceptions at all.
A:
the 'as' keyword is a python 3 (introduced in 2.6) addition, you need to use a comma:
try:
code_that_raises_exception()
except Exception, e:
print e
raise
A:
try:
codethatraises()
except Exception, e:
print e
raise
not as easy to read as the latest and greatest syntax, but identical semantics.
| Print info about exception in python 2.5? | Python 2.5 won't let me use this syntax:
try:
code_that_raises_exception()
except Exception as e:
print e
raise
So how should I print information about an exception?
Thanks
EDIT: I'm writing a plugin for a program that includes kind of a pseudo python interpreter. It prints print statements but doesn't show exceptions at all.
| [
"the 'as' keyword is a python 3 (introduced in 2.6) addition, you need to use a comma:\ntry:\n code_that_raises_exception()\nexcept Exception, e:\n print e\n raise\n\n",
"try:\n codethatraises()\nexcept Exception, e:\n print e\n raise\n\nnot as easy to read as the latest and greatest syntax, but ident... | [
9,
2
] | [] | [] | [
"exception",
"exception_handling",
"printing",
"python"
] | stackoverflow_0003808812_exception_exception_handling_printing_python.txt |
Q:
decorator inside class & decorated classmethod without 'self' gives strange results
Example code:
# -*- coding: utf-8 -*-
from functools import wraps
class MyClass(object):
def __init__(self):
pass
#decorator inside class
def call(f):
@wraps(f)
def wrapper(*args):
print 'Wrapper: ', args
return wrapper
#decorated 'method' without self
@call
def myfunc(a):
pass
c = MyClass()
c.myfunc(1)
Returns:
Wrapper: (<test3.MyClass object at 0xb788a34c>, 1)
Is this normal? Can someone explain?
If this is a feature I would use it in my library.
A:
This is perfectly normal.
The function myfunc is replacecd by an instance of wrapper. The signature of wrapper is (*args). because it is a bound method, the first argument is the instance of MyClass which is printed out after the string `Wrapper: '.
What's confusing you?
It's worth noting that if you use call as a decorator from outside of MyClass, it will generate a TypeError. One way around this is to apply the staticmethod decorator to it but then you can't call it during class construction.
It's a little bit hacky but I address how to have it both ways here.
update after comment
it gets the instance as the first argument regardless of if you type self in the parameter list because after the class is created, and an instance instantiated, it is a bound method. when you call it in the form
@instance.call
def foo(bar):
return bar + 1
it expands to
def foo(bar):
return bar + 1
foo = instance.call(f)
but note that you are calling it on an instance! This will automatically expand to a call of the form
def foo(bar):
return bar + 1
foo = MyClass.call(instance, f)
This is how methods work. But you only defined call to take one argument so this raises a TypeError.
As for calling it during class construction, it works fine. but the function that it returns gets passed an instance of MyClass when it is called for the same reason that I explained above. Specifically, whatever arguments you explicity pass to it come after the implicit and automatic placement of the instance that it is called upon at the front of the argument list.
A:
@call
def myfunc(a):
...
is equivalent to
def myfunc(a):
...
myfunc=call(myfunc)
The orginial myfunc may have expected only one argument, a, but after being decorated with call, the new myfunc can take any number of positional arguments, and they will all be put in args.
Notice also that
def call(f)
never calls f. So the fact that
def myfunc(a)
lacks the normal self argument is not an issue. It just never comes up.
When you call c.myfunc(1), wrapper(*args) gets called.
What is args? Well, since c.myfunc is a method call, c is sent as the first argument, followed by any subsequent arguments. In this case, the subsequent argument is 1. Both arguments are sent to wrapper, so args is the 2-tuple (c,1).
Thus, you get
Wrapper: (<test3.MyClass object at 0xb788a34c>, 1)
| decorator inside class & decorated classmethod without 'self' gives strange results | Example code:
# -*- coding: utf-8 -*-
from functools import wraps
class MyClass(object):
def __init__(self):
pass
#decorator inside class
def call(f):
@wraps(f)
def wrapper(*args):
print 'Wrapper: ', args
return wrapper
#decorated 'method' without self
@call
def myfunc(a):
pass
c = MyClass()
c.myfunc(1)
Returns:
Wrapper: (<test3.MyClass object at 0xb788a34c>, 1)
Is this normal? Can someone explain?
If this is a feature I would use it in my library.
| [
"This is perfectly normal.\nThe function myfunc is replacecd by an instance of wrapper. The signature of wrapper is (*args). because it is a bound method, the first argument is the instance of MyClass which is printed out after the string `Wrapper: '.\nWhat's confusing you?\nIt's worth noting that if you use call a... | [
1,
1
] | [] | [] | [
"class",
"decorator",
"python"
] | stackoverflow_0003808967_class_decorator_python.txt |
Q:
Jinja2 PackageLoader on google app engine
I want to use jinja2.PackageLoader on Google App engine, but that appears to depend on pkg_resources, which wasn't added until Python 2.6. Am I Out of luck?
A:
You should be able to include pkg_resources.py in your application directory (or elsewhere in sys.path if you're modifying it in your scripts); according to Guido it should work since App Engine 1.2.1.
| Jinja2 PackageLoader on google app engine | I want to use jinja2.PackageLoader on Google App engine, but that appears to depend on pkg_resources, which wasn't added until Python 2.6. Am I Out of luck?
| [
"You should be able to include pkg_resources.py in your application directory (or elsewhere in sys.path if you're modifying it in your scripts); according to Guido it should work since App Engine 1.2.1.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"jinja2",
"python"
] | stackoverflow_0003809304_google_app_engine_jinja2_python.txt |
Q:
Is the Python standard library really standard?
Is the Python standard library standard in the sense that if Python is installed, then the standard library is installed too?
The documentation reads
For Unix-like operating systems Python is normally provided as a collection of packages, so it may be necessary to use the packaging tools provided with the operating system to obtain some or all of the optional components.
The standard library index only lists as optional the "Optional Operating System Services", as far as I can tell.
So, is everything else always available on a platform, if Python is installed? If not, what can be expected on the most common ones (Windows, Mac OS X, Linux)?
PS: I am teaching a Python class to graduate students, and I would love to be able to tell them that Python always comes with batteries included; this is of practical importance, for them (when they arrive in a new lab, or use a new machine, it is useful for them to know what to expect in terms of standard modules availability).
A:
It's not a Python issue. You can teach that the batteries are included. They are.
It's the distributions that are incomplete.
We've been unhappy with the Red Hat Enterprise Linux having old versions of Python. However, there are recipes for upgrades.
It's a common security practice to turn off all developer packages, leaving Python incomplete. This is a common situation outside Python and outside the essential Linux distribution.
Batteries are included under normal circumstances. But, it's also very easy to strip some or all of the batteries. And many organizations will -- for a variety of reasons -- create incomplete libraries.
It's not Python. It's the environments that are incomplete.
A:
Generally yes -- everything not listed in the optional section will always be available.
These are some of the things that may vary from OS to OS installation:
http://docs.python.org/library/someos.html
You probably won't use these unless you're doing fairly advanced programming.
A:
It depends on the distribution packager. For example on Debian the profiling modules profile and cprofile are installed separately as python-profiler. Other modules may be separated like this too on different distributions.
| Is the Python standard library really standard? | Is the Python standard library standard in the sense that if Python is installed, then the standard library is installed too?
The documentation reads
For Unix-like operating systems Python is normally provided as a collection of packages, so it may be necessary to use the packaging tools provided with the operating system to obtain some or all of the optional components.
The standard library index only lists as optional the "Optional Operating System Services", as far as I can tell.
So, is everything else always available on a platform, if Python is installed? If not, what can be expected on the most common ones (Windows, Mac OS X, Linux)?
PS: I am teaching a Python class to graduate students, and I would love to be able to tell them that Python always comes with batteries included; this is of practical importance, for them (when they arrive in a new lab, or use a new machine, it is useful for them to know what to expect in terms of standard modules availability).
| [
"It's not a Python issue. You can teach that the batteries are included. They are.\nIt's the distributions that are incomplete.\nWe've been unhappy with the Red Hat Enterprise Linux having old versions of Python. However, there are recipes for upgrades.\nIt's a common security practice to turn off all developer ... | [
8,
6,
2
] | [] | [] | [
"python",
"standard_library"
] | stackoverflow_0003807111_python_standard_library.txt |
Q:
Best data structure for dictionary in Java (and also Python)
Here is my requirement:
Input: Random String of sufficiently long ex: fdjhkajajkfdj
Output: fdj has a 2 occurences and separated by x chars
I want to put all three letter words in an array and check if they are the same
Eg:
a[0] = fdj
a[1] = djh
a[2] = jhk
a[3] = hka
a[4] = kaj
.
.
.
a[n] =fdj
My answer is a[0] and a[n] matches, may be more than 2 occurances.
Question: So what kind of array should I use which is optimal in this situation. I am using Java (and also python). I was thinking of Dict.
A:
In Java you could use the Map interface ( http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html )
I would use HashMap so that the key is the 3 letter word and the value is the count of occurances. Here's some sample pseudo code
HashMap<String, int> wordCountMap = new HashMap<String, int>();
for(....) // for each 3 letter word in the input
{
String word = ...; // current three letter word
if(wordCountMap.containsKey(word))
wordCountMap.put(word, wordCountMap.get(word)++);
else
wordCountMap.put(word, 1);
}
Then you can loop through the key/value pairs and return their occurance count.
To return the number of characters between the words, you can do this separately after counting the occurances by using String manipulation (see String.indexOf). Pseudo code for this is....
String orginalInput = "fdjhkajajkfdj";
String word = "fdj";
int firstOccurance = originalInput.indexOf();
int secondOccurance = originalInput.indexOf(firstOccurance+1);
int charsInBetween = secondOccurance - firstOccurance - 3; // difference in indices minus length of word
A:
In Python a dict is fine.
In Java, you could use a HashSet if you need to detect only the first match, but if you want to count the number of matches, you could use a Map
Edit: you changed the parameters of the question, so here's what I suggest now. Use a Map> - the key is the 3 letter word, and you're maintaining a list of index values that the string occurs. You can use an equivalent in Python
A:
you could sort them and look for duplicates or put them into a linked hash set and check for a duplicate before you insert something.
A:
Well. fdj will be matched because it is the first 3 characters of the string? Or does it come from somewhere else? If you have more then 2 occurences of your needle, do you need the distance between the first 2 matches, or the first and the last, or all the distances for each couple of matches?
Well, I can give you a function that gives you all the matches.
>>> def find_matches(needle, hackstay):
... '''returns a list of positions of needle in hackstay'''
... ptr = 0
... found = []
... while True:
... idx = hackstay[ptr:].find(needle)
... if idx < 0: return found
... found.append(ptr+idx)
... ptr += idx+len(needle)
...
>>>
>>>
>>> find_matches('fdj','fdjhkajajkfdj')
[0, 10]
Distance between 2 elements of the array is just the bigger element minus the smaller element minus the length of needle.
Example:
>>> res = find_matches('fdj','fdjhkajajkfdj')
>>> distance = abs(res[0]-res[1])-len('fdj')
>>> print distance
7
With this you can decide by yourself, where needle comes from and what distances you need. Hope it helps!
PS: If anybody can suggest how to improve that code, please do! My feeling says that this can be written shorter (like using found = [i for ??? if ???]), but I don't know, how.
A:
Your way of storing three letter words in an Array is NOT Efficient. Please consider storing the String in a Suffix Tree or simply in an Array and use the KMP Algorithm to find the max occurence of the string you have to search. Later the counts can be stored however you choose.
| Best data structure for dictionary in Java (and also Python) | Here is my requirement:
Input: Random String of sufficiently long ex: fdjhkajajkfdj
Output: fdj has a 2 occurences and separated by x chars
I want to put all three letter words in an array and check if they are the same
Eg:
a[0] = fdj
a[1] = djh
a[2] = jhk
a[3] = hka
a[4] = kaj
.
.
.
a[n] =fdj
My answer is a[0] and a[n] matches, may be more than 2 occurances.
Question: So what kind of array should I use which is optimal in this situation. I am using Java (and also python). I was thinking of Dict.
| [
"In Java you could use the Map interface ( http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html )\nI would use HashMap so that the key is the 3 letter word and the value is the count of occurances. Here's some sample pseudo code\nHashMap<String, int> wordCountMap = new HashMap<String, int>();\nfor(..... | [
1,
0,
0,
0,
0
] | [] | [] | [
"java",
"python"
] | stackoverflow_0003809308_java_python.txt |
Q:
How to configure ipy_user_conf.py to get IPython to to start with the right IDLE set as editor?
64-bit Vista
Python 2.6
IPython 0.10
Also have Python 2.7 and 3.1
My ipy_user_conf.py has example lines showing how to set an editor. I've tried
ipy_editors.idle()
but
[C:Python26/Scripts]
|4>ed xxx.py
Editing... > C:\Python26\lib\idlelib/idle.py "xxx.py"
opens the IDLE for Python 3.1, and doesn't open xxx.py.
I next imitated a sample line in ipy_user_conf.py,
ipy_editors.scite('c:/opt/scite/scite.exe')
as
ipy_editors.idle("c:/Python26/Lib/idlelib/idle.pyw")
but
[C:Python26/Scripts]
|4>ed xxx.py
Editing... > c:/Python26/Lib/idlelib/idle.pyw "xxx.py"
opens the FILE c:/Python26/Lib/idlelib/idle.pyw in the IDLE for Python 3.1
I've run out of ideas. Advice, please.
BTW run xxx.py works fine.
A:
The most likely cause is Windows' file name extension associations. I'm guessing Python 3.1 was the last version of python that you installed, so by default, .py and .pyw are now associated with the 3.1 executable. (One way you can verify which python version is associated with the .py/.pyw extensions is to run assoc .py. There are other ways also.)
To get around this, explicitly say which python version you want to run:
ipy_editors.idle('c:/Python26/pythonw.exe c:/Python26/Lib/idlelib/idle.pyw')
Edit:
A pythonic way to test the association would be to create a test.py file such as:
import sys
print sys.version
Then at a command prompt, just run it as test.py.
| How to configure ipy_user_conf.py to get IPython to to start with the right IDLE set as editor? | 64-bit Vista
Python 2.6
IPython 0.10
Also have Python 2.7 and 3.1
My ipy_user_conf.py has example lines showing how to set an editor. I've tried
ipy_editors.idle()
but
[C:Python26/Scripts]
|4>ed xxx.py
Editing... > C:\Python26\lib\idlelib/idle.py "xxx.py"
opens the IDLE for Python 3.1, and doesn't open xxx.py.
I next imitated a sample line in ipy_user_conf.py,
ipy_editors.scite('c:/opt/scite/scite.exe')
as
ipy_editors.idle("c:/Python26/Lib/idlelib/idle.pyw")
but
[C:Python26/Scripts]
|4>ed xxx.py
Editing... > c:/Python26/Lib/idlelib/idle.pyw "xxx.py"
opens the FILE c:/Python26/Lib/idlelib/idle.pyw in the IDLE for Python 3.1
I've run out of ideas. Advice, please.
BTW run xxx.py works fine.
| [
"The most likely cause is Windows' file name extension associations. I'm guessing Python 3.1 was the last version of python that you installed, so by default, .py and .pyw are now associated with the 3.1 executable. (One way you can verify which python version is associated with the .py/.pyw extensions is to run as... | [
1
] | [] | [] | [
"ipython",
"python",
"vista64"
] | stackoverflow_0003809703_ipython_python_vista64.txt |
Q:
Python; reading file and finding desired text
Need to create a function with two params, a filename to open and a pattern.
The pattern will be a search string.
Eg. the function will open sentence.txt that has something like "The quick brown fox" (can possibly be more than one line)
The pattern will be "brown fox"
So if found, as this will be, it should return a line number and index of the character the found string starts on. Else, return -1.
Catch is I've never programmed in python before so I don't know the syntax.
Previously coded in C, C#, Java, VB, etc..
EDIT:
.....Id
.....Name
#
my intent was for you to write HW3 code as iteration or
nested iterations that explicitly index the character
string as an array; i.e, the Python index() also known as
string.index() function is not allowed for this homework.
#
filename = raw_input('Enter filename: ')
pattern = raw_input('Enter pattern: ')
def findPattern(fname, pat):
Reading in one whole chunk
filetext = open(fname).read()
if pat in filetext:
print("Found it -- chunk")
else:
print("Nothing -- chunk")
Reading in line by line
for search in open(fname):
if pat in search:
print("Found it -- line")
else:
print("Nothing -- line")
findPattern(filename, pattern)
A:
you can simulate simple "grep" with the "in" operator
def grep(filename, pattern):
for n,line in enumerate(open(filename)):
if pattern in line:
print line, n
To get index, you can use str.index() or str.find()
A:
Here's a very simple grep. You could hack it out to use regular expressions pretty trivially. globbing wouldn't be much more difficult with glob. Also, the code you want is in there spread between grep and main so that might be of more interest than a custom grep ;)
def grep(filename, needle):
with open(filename) as f_in:
matches = ((i, line.find(needle), line) for i, line in enumerate(f_in))
return [match for match in matches if match[0] != -1]
def main(filename, needle):
matches = grep(filename, needle)
if matches:
print "{0} found on {1} lines in {2}".format(needle, len(matches), filename)
for line in matches:
print "{0}:{1}:{2}".format(*line)
return 1
else:
return -1
if __name__=='__main__':
import sys
filename = sys.argv[1]
needle = sys.argv[2]
return sys.exit(main(filename, needle))
Note that I haven't tested this code so there might be slight bugs. If it compiles, it should run fine though.
Also, you should tell your teacher that signalling failure with return codes is a terrible way to do things. If the caller of the function that you're going to write needs to know if no matches were found, it can just check for an empty list.
| Python; reading file and finding desired text | Need to create a function with two params, a filename to open and a pattern.
The pattern will be a search string.
Eg. the function will open sentence.txt that has something like "The quick brown fox" (can possibly be more than one line)
The pattern will be "brown fox"
So if found, as this will be, it should return a line number and index of the character the found string starts on. Else, return -1.
Catch is I've never programmed in python before so I don't know the syntax.
Previously coded in C, C#, Java, VB, etc..
EDIT:
.....Id
.....Name
#
my intent was for you to write HW3 code as iteration or
nested iterations that explicitly index the character
string as an array; i.e, the Python index() also known as
string.index() function is not allowed for this homework.
#
filename = raw_input('Enter filename: ')
pattern = raw_input('Enter pattern: ')
def findPattern(fname, pat):
Reading in one whole chunk
filetext = open(fname).read()
if pat in filetext:
print("Found it -- chunk")
else:
print("Nothing -- chunk")
Reading in line by line
for search in open(fname):
if pat in search:
print("Found it -- line")
else:
print("Nothing -- line")
findPattern(filename, pattern)
| [
"you can simulate simple \"grep\" with the \"in\" operator\ndef grep(filename, pattern):\n for n,line in enumerate(open(filename)):\n if pattern in line:\n print line, n\n\nTo get index, you can use str.index() or str.find()\n",
"Here's a very simple grep. You could hack it out to use regula... | [
3,
1
] | [] | [] | [
"file",
"python",
"search"
] | stackoverflow_0003809373_file_python_search.txt |
Q:
Mac Ports Python 2.6.6 and Tkinter
I apologize if this has been asked but does Tkinter work in Python 2.6.6 when installed with Mac Ports? Or do I need to pass the no_tkinter variant?
Thanks for any help!
A:
As of MacPorts python26 @2.6.6_0 and tk @8.5.8_0, Tkinter appears to only work if you don't mind using an X11-based Tk. There is a +quartz variant for the Tk port which does not require X11 but it is not yet supported in 64-bit mode, the preferred build and execution architecture on OS X 10.6, and at the moment it seems to not work in 32-bit mode either (tk @8.5.8_0). If you don't mind having MacPorts pull in a bunch of X11 client build dependencies and using X11 for Tkinter applications, the default variant looks like it works OK (lightly tested with OS X 10.6.4 and python26 @2.6.6_0). This applies to IDLE as well, since it uses Tkinter. Otherwise, stick to +no_tkinter if you can live without Tkinter and IDLE.
By the way, the Python 2.6.6 installed by the python.org installer (32-bit only) uses either the Apple-supplied Quartz Tk 8.4 for OS X 10.4 through 10.6 or it will use an ActiveState Tcl/Tk 8.4 if you have installed it. MacPorts currently has no provision for using either of them.
A:
pytkinter 2.4.6 is the latest version available on macports and works with python 2.4
http://trac.macports.org/browser/trunk/dports/python/py-tkinter/Portfile
| Mac Ports Python 2.6.6 and Tkinter | I apologize if this has been asked but does Tkinter work in Python 2.6.6 when installed with Mac Ports? Or do I need to pass the no_tkinter variant?
Thanks for any help!
| [
"As of MacPorts python26 @2.6.6_0 and tk @8.5.8_0, Tkinter appears to only work if you don't mind using an X11-based Tk. There is a +quartz variant for the Tk port which does not require X11 but it is not yet supported in 64-bit mode, the preferred build and execution architecture on OS X 10.6, and at the moment i... | [
2,
0
] | [] | [] | [
"macports",
"python",
"tkinter"
] | stackoverflow_0003808807_macports_python_tkinter.txt |
Q:
Python for indexing and searching using a cluster?
After an unfortunate misadventure with MySQL, I finally gave up on using it.
What I have?
Large set of files in the following format:
ID1: String String String String
ID2: String String String String
ID3: String String String String
ID4: String String String String
What I did?
Used MySQL on a powerful machine to import everything into a database in the following form:
ID1 String
ID1 String
ID1 String
ID1 String
...
...
What happened?
The database import was successful. Indexing is failing because apparently it requires more than 200 GB for 2 billion records. Reasonable request but I simply don't have that much space because the table itself is occupying about 240 GB after normalizing.
What I am planning to do?
I have a cluster of 20 nodes with about 80GB access for all of them combined (all of them have an NFS mount). I setup the nodes for distributed computing using Parallel Python. I am planning to rewrite my logic to utilize the power of the cluster.
My Question:
I need to do a lot of the following type of lookups:
What IDs contain a given string?
For instance, given an arbitrary string: "String1", I need to know that say, "ID1, ID2234" contain it.
I know of two methods for now:
Using python call grep
Each of the 20
nodes takes control over a set of
files and upon a request for search,
searches their associated files.
Can someone suggest a good approach to speed up this otherwise inefficient task?
A:
For the requirement of looking up which IDs are associated with a given string, I suggest inverting the ID/string relation so the records are keyed by unique strings and the associated data is a sequence of IDs. A string lookup can the be implemented by either a binary search if sorted, or a hash algorithm. This may concentrate your data considerably if you have a lot of the same strings repeating.
A:
I'd suggest looking at the use of a non-relational database to support this. There are a number of key/value stores that you could look at for storing your data, which should be more efficient than a database. You may want to look at NoSQL on Wikipedia to start with.
EDIT: Are you using the most compact data types possible for the data in your database? Are your IDs integers of the lowest size possible to store the range of IDs? If your strings are ASCII, are you storing them as ASCII strings rather than Unicode (VARCHAR rather than NVARCHAR)?
| Python for indexing and searching using a cluster? | After an unfortunate misadventure with MySQL, I finally gave up on using it.
What I have?
Large set of files in the following format:
ID1: String String String String
ID2: String String String String
ID3: String String String String
ID4: String String String String
What I did?
Used MySQL on a powerful machine to import everything into a database in the following form:
ID1 String
ID1 String
ID1 String
ID1 String
...
...
What happened?
The database import was successful. Indexing is failing because apparently it requires more than 200 GB for 2 billion records. Reasonable request but I simply don't have that much space because the table itself is occupying about 240 GB after normalizing.
What I am planning to do?
I have a cluster of 20 nodes with about 80GB access for all of them combined (all of them have an NFS mount). I setup the nodes for distributed computing using Parallel Python. I am planning to rewrite my logic to utilize the power of the cluster.
My Question:
I need to do a lot of the following type of lookups:
What IDs contain a given string?
For instance, given an arbitrary string: "String1", I need to know that say, "ID1, ID2234" contain it.
I know of two methods for now:
Using python call grep
Each of the 20
nodes takes control over a set of
files and upon a request for search,
searches their associated files.
Can someone suggest a good approach to speed up this otherwise inefficient task?
| [
"For the requirement of looking up which IDs are associated with a given string, I suggest inverting the ID/string relation so the records are keyed by unique strings and the associated data is a sequence of IDs. A string lookup can the be implemented by either a binary search if sorted, or a hash algorithm. This ... | [
1,
0
] | [] | [] | [
"cluster_computing",
"distributed",
"indexing",
"python",
"search"
] | stackoverflow_0003809891_cluster_computing_distributed_indexing_python_search.txt |
Q:
Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python?
Here's a common situation when compiling data in dictionaries from different sources:
Say you have a dictionary that stores lists of things, such as things I like:
likes = {
'colors': ['blue','red','purple'],
'foods': ['apples', 'oranges']
}
and a second dictionary with some related values in it:
favorites = {
'colors':'yellow',
'desserts':'ice cream'
}
You then want to iterate over the "favorites" object and either append the items in that object to the list with the appropriate key in the "likes" dictionary or add a new key to it with the value being a list containing the value in "favorites".
There are several ways to do this:
for key in favorites:
if key in likes:
likes[key].append(favorites[key])
else:
likes[key] = list(favorites[key])
or
for key in favorites:
try:
likes[key].append(favorites[key])
except KeyError:
likes[key] = list(favorites[key])
And many more as well...
I generally use the first syntax because it feels more pythonic, but if there are other, better ways, I'd love to know what they are. Thanks!
A:
Use collections.defaultdict, where the default value is a new list instance.
>>> import collections
>>> mydict = collections.defaultdict(list)
In this way calling .append(...) will always succeed, because in case of a non-existing key append will be called on a fresh empty list.
You can instantiate the defaultdict with a previously generated list, in case you get the dict likes from another source, like so:
>>> mydict = collections.defaultdict(list, likes)
Note that using list as the default_factory attribute of a defaultdict is also discussed as an example in the documentation.
A:
Use collections.defaultdict:
import collections
likes = collections.defaultdict(list)
for key, value in favorites.items():
likes[key].append(value)
defaultdict takes a single argument, a factory for creating values for unknown keys on demand. list is a such a function, it creates empty lists.
And iterating over .items() will save you from using the key to get the value.
A:
Except defaultdict, the regular dict offers one possibility (that might look a bit strange): dict.setdefault(k[, d]):
for key, val in favorites.iteritems():
likes.setdefault(key, []).append(val)
Thank you for the +20 in rep -- I went from 1989 to 2009 in 30 seconds. Let's remember it is 20 years since the Wall fell in Europe..
A:
>>> from collections import defaultdict
>>> d = defaultdict(list, likes)
>>> d
defaultdict(<class 'list'>, {'colors': ['blue', 'red', 'purple'], 'foods': ['apples', 'oranges']})
>>> for i, j in favorites.items():
d[i].append(j)
>>> d
defaultdict(<class 'list'>, {'desserts': ['ice cream'], 'colors': ['blue', 'red', 'purple', 'yellow'], 'foods': ['apples', 'oranges']})
A:
All of the answers are defaultdict, but I'm not sure that's the best way to go about it. Giving out defaultdict to code that expects a dict can be bad. (See: How do I make a defaultdict safe for unexpecting clients? ) I'm personally torn on the matter. (I actually found this question looking for an answer to "which is better, dict.get() or defaultdict") Someone in the other thread said that you don't want a defaultdict if you don't want this behavior all the time, and that might be true. Maybe using defaultdict for the convenience is the wrong way to go about it. I think there are two needs being conflated here:
"I want a dict whose default values are empty lists." to which defaultdict(list) is the correct solution.
and
"I want to append to the list at this key if it exists and create a list if it does not exist." to which my_dict.get('foo', []) with append() is the answer.
What do you guys think?
| Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python? | Here's a common situation when compiling data in dictionaries from different sources:
Say you have a dictionary that stores lists of things, such as things I like:
likes = {
'colors': ['blue','red','purple'],
'foods': ['apples', 'oranges']
}
and a second dictionary with some related values in it:
favorites = {
'colors':'yellow',
'desserts':'ice cream'
}
You then want to iterate over the "favorites" object and either append the items in that object to the list with the appropriate key in the "likes" dictionary or add a new key to it with the value being a list containing the value in "favorites".
There are several ways to do this:
for key in favorites:
if key in likes:
likes[key].append(favorites[key])
else:
likes[key] = list(favorites[key])
or
for key in favorites:
try:
likes[key].append(favorites[key])
except KeyError:
likes[key] = list(favorites[key])
And many more as well...
I generally use the first syntax because it feels more pythonic, but if there are other, better ways, I'd love to know what they are. Thanks!
| [
"Use collections.defaultdict, where the default value is a new list instance.\n>>> import collections\n>>> mydict = collections.defaultdict(list)\n\nIn this way calling .append(...) will always succeed, because in case of a non-existing key append will be called on a fresh empty list.\nYou can instantiate the defau... | [
5,
3,
2,
1,
1
] | [] | [] | [
"iteration",
"python"
] | stackoverflow_0001553467_iteration_python.txt |
Q:
Appengine - Reportlab (Get Photo from Model)
I´m using Reportlab to generate a PDF.
Can´t retrieve a photo from a model.
#Personal Info
p.drawImage('myPhoto.jpg', 40, 730)
p.drawString(50, 670, 'Your name:' + '%s' % user.name)
p.drawImage (50, 640, 'Photo: %s' % (user.photo))
When i create on generate PDF, i got this error:
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 513, in __call__
handler.post(*groups)
File "C:\Users\hp\workspace\myApp\src\main.py", line 419, in post
p.drawImage (50, 640, 'Photo: %s' % (user.photo))
File "reportlab.zip\reportlab\pdfgen\canvas.py", line 825, in drawImage
File "reportlab.zip\reportlab\pdfbase\pdfdoc.py", line 2076, in __init__
File "C:\Python25\lib\ntpath.py", line 189, in splitext
i = p.rfind('.')
AttributeError: 'int' object has no attribute 'rfind'
If i comment the line which n.º 419, that calls the photo, everything goes fine.
I´ve already inspected in Datastore Viewer and the models are ok.
Can someone point out what´s going wrong?
Should i use %s instead of str? But throws same error.
A:
According to the ReportLab API reference, drawImage() has arguments 'image, x, y', whereas it looks as though you are passing 'x, y, string'.
The image argument to drawImage() requires a filename or ImageReader.
According to this post, the ImageReader constructor can take several types of arguments.
Update:
In this code which you posted you are assigning the ImageReader to 'image', but passing 'imagem' (which doesn't exist) to drawImage:
image = ImageReader(user.photo)
p.drawImage(imagem)
Also, what type of model property is user.photo?
Update 2:
You're getting an error about NoneType - are you sure user.photo is a valid blob, and not None?
Also, a blob is a subclass of str, but ImageReader requires a StringIO - so I think you need to wrap the blob in a StringIO to pass it to ImageReader, for example:
import StringIO
image = ImageReader(StringIO.StringIO(user.photo))
p.drawImage(image)
By the way, my guess is that ImageReader('http://www.reportlab.com/rsrc/encryption.gif') may have failed because it may be attempting to load the image from that server, using an API which app engine doesn't support (ie, not urlfetch).
Update 3:
Actually it looks like it's a bug in ReportLab.
I downloaded version 2.4 of ReportLab, and found this in utils.py:
def _isPILImage(im):
try:
return isinstance(im,Image.Image)
except ImportError:
return 0
class ImageReader(object):
"Wraps up either PIL or Java to get data from bitmaps"
_cache={}
def __init__(self, fileName):
...
if _isPILImage(fileName):
The ImageReader constructor calls _isPILImage to see if it was passed a PIL image. However PIL is not available on app engine, so Image is None, and therefore referencing Image.Image throws the in _isPILImage AttributeError: 'NoneType' object has no attribute 'Image'. which you are seeing.
I also found this blog post which describes how to use ReportLab with images. See the section 'Images in PDFs' for details on how to fix this issue, as well as another modification which is required to get it to work on app engine. Note that the line numbers in that blog post don't seem to match the 2.4 version which I downloaded, or the line numbers in your error messages - so search for the code mentioned, rather than the line numbers.
Also note that ReportLab without PIL (ie as it will run on app engine) can only draw JPEG images (as also mentioned in that blog post).
Finally, in this code you posted:
def get(self, image):
if image is not None:
image = ImageReader(StringIO.StringIO(user.photo))
p.drawImage(40, 700, image)
p.setLineWidth(.3)
p.setFont('Helvetica', 10)
p.line(50, 660, 560, 660)
The first issue is that you are calling drawImage() with 'x, y, image', when the argments should be 'image, x, y'.
Secondly, neither user or p are defined here (maybe you cut out that code?).
Thirdly, why is there an image argument to get() - do you parse something out of the URL when you create the webapp.WSGIApplication()? If not, then image will be None, which is why nothing will happen.
Update 4:
The Imaging Library not available, unable to import bitmaps only jpegs error which you are now getting is because ReportLab is unable to read the jpeg to find its width and height. Maybe the jpeg was corrupted when you loaded it into the blob, or maybe the jpeg is in a format which ReportLab doesn't support.
In ReportLab's lib\utils.py, you could temporarily try changing the following (around line 578 of version 2.5):
try:
self._width,self._height,c=readJPEGInfo(self.fp)
except:
raise RuntimeError('Imaging Library not available, unable to import bitmaps only jpegs')
To just this:
self._width,self._height,c=readJPEGInfo(self.fp)
This will allow you to see the actual exception which readJPEGInfo() is throwing, which might help find the cause of the problem.
Another thing to try to help narrow down the problem might be to put the file.jpg which you uploaded for the user into your project, then do something like this:
imagem = canvas.ImageReader(StringIO.StringIO(open('file.jpg', 'rb').read()))
This will load the jpeg directly from the file, using the ImageReader, instead of from the blob.
If this works, then the problem is that your blob is invalid, so you should look at your image upload code. If it fails, then the jpeg itself is invalid (or unsupported by ReportLab).
Update 5:
You're using this:
photo = images.resize(self.request.get('photo'), 32, 32)
According to the documentation on resize on this page, it takes an output_encoding argument which defaults to PNG. So try this instead:
photo = images.resize(self.request.get('photo'), 32, 32, images.JPEG)
| Appengine - Reportlab (Get Photo from Model) | I´m using Reportlab to generate a PDF.
Can´t retrieve a photo from a model.
#Personal Info
p.drawImage('myPhoto.jpg', 40, 730)
p.drawString(50, 670, 'Your name:' + '%s' % user.name)
p.drawImage (50, 640, 'Photo: %s' % (user.photo))
When i create on generate PDF, i got this error:
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 513, in __call__
handler.post(*groups)
File "C:\Users\hp\workspace\myApp\src\main.py", line 419, in post
p.drawImage (50, 640, 'Photo: %s' % (user.photo))
File "reportlab.zip\reportlab\pdfgen\canvas.py", line 825, in drawImage
File "reportlab.zip\reportlab\pdfbase\pdfdoc.py", line 2076, in __init__
File "C:\Python25\lib\ntpath.py", line 189, in splitext
i = p.rfind('.')
AttributeError: 'int' object has no attribute 'rfind'
If i comment the line which n.º 419, that calls the photo, everything goes fine.
I´ve already inspected in Datastore Viewer and the models are ok.
Can someone point out what´s going wrong?
Should i use %s instead of str? But throws same error.
| [
"According to the ReportLab API reference, drawImage() has arguments 'image, x, y', whereas it looks as though you are passing 'x, y, string'.\nThe image argument to drawImage() requires a filename or ImageReader.\nAccording to this post, the ImageReader constructor can take several types of arguments.\nUpdate:\nIn... | [
12
] | [] | [] | [
"django_models",
"google_app_engine",
"python",
"reportlab"
] | stackoverflow_0003798885_django_models_google_app_engine_python_reportlab.txt |
Q:
Python unicode popen or Popen error reading unicode
I have a program that generates the following output:
┌───────────────────────┐
│10 day weather forecast│
└───────────────────────┘
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
Tonight Sep 27 Clear 54 0 %
Tue Sep 28 Sunny 85/61 0 %
Wed Sep 29 Sunny 86/62 0 %
Thu Sep 30 Sunny 87/65 0 %
Fri Oct 01 Sunny 85/62 0 %
Sat Oct 02 Sunny 81/59 0 %
Sun Oct 03 Sunny 79/56 0 %
Mon Oct 04 Sunny 78/58 0 %
Tue Oct 05 Sunny 81/61 0 %
Wed Oct 06 Sunny 81/61 0 %
Last Updated Sep 27 10:20 p.m. CT
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
This doesn't seem to format right on this site, but the lower lines at the top and the upper lines at the bottom result in a unicode error.
Here is the code example for os.popen
>>> buffer = popen('10day', 'r').read()
Traceback (most recent call last):
File "/home/woodnt/python/10_day_forecast.py", line 129, in <module>
line_lower(51)
File "/home/woodnt/python/lib/box.py", line 24, in line_lower
print upper_line * len
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-50: ordinal not in range(128)
>>> print buffer
┌───────────────────────┐
│10 day weather forecast│
└───────────────────────┘
>>>
Here is the same for subprocess.Popen:
f = Popen('10day', stdout=PIPE, stdin=PIPE, stderr=PIPE)
o, er = f.communicate()
print o
┌───────────────────────┐
│10 day weather forecast│
└───────────────────────┘
print er
Traceback (most recent call last):
File "/home/woodnt/python/10_day_forecast.py", line 129, in <module>
line_lower(51)
File "/home/woodnt/python/lib/box.py", line 24, in line_lower
print upper_line * len
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-50: ordinal not in range(128)
Any ideas if this can be made to work without a lot of "under the hood" work? I'm just learning programming and starting with python
A:
I'd say running your program from the console should work correctly because Python can guess the console encoding of the terminal window (cp437 on US Windows), but when run through a pipe Python uses the default of ascii. Try changing your program to encode all Unicode output to an explicit encoding, such as:
print (upper_line * len).encode('cp437')
Then when you read it from the pipe, you can either decode back to Unicode or print it directly to the terminal.
| Python unicode popen or Popen error reading unicode | I have a program that generates the following output:
┌───────────────────────┐
│10 day weather forecast│
└───────────────────────┘
▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁
Tonight Sep 27 Clear 54 0 %
Tue Sep 28 Sunny 85/61 0 %
Wed Sep 29 Sunny 86/62 0 %
Thu Sep 30 Sunny 87/65 0 %
Fri Oct 01 Sunny 85/62 0 %
Sat Oct 02 Sunny 81/59 0 %
Sun Oct 03 Sunny 79/56 0 %
Mon Oct 04 Sunny 78/58 0 %
Tue Oct 05 Sunny 81/61 0 %
Wed Oct 06 Sunny 81/61 0 %
Last Updated Sep 27 10:20 p.m. CT
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
This doesn't seem to format right on this site, but the lower lines at the top and the upper lines at the bottom result in a unicode error.
Here is the code example for os.popen
>>> buffer = popen('10day', 'r').read()
Traceback (most recent call last):
File "/home/woodnt/python/10_day_forecast.py", line 129, in <module>
line_lower(51)
File "/home/woodnt/python/lib/box.py", line 24, in line_lower
print upper_line * len
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-50: ordinal not in range(128)
>>> print buffer
┌───────────────────────┐
│10 day weather forecast│
└───────────────────────┘
>>>
Here is the same for subprocess.Popen:
f = Popen('10day', stdout=PIPE, stdin=PIPE, stderr=PIPE)
o, er = f.communicate()
print o
┌───────────────────────┐
│10 day weather forecast│
└───────────────────────┘
print er
Traceback (most recent call last):
File "/home/woodnt/python/10_day_forecast.py", line 129, in <module>
line_lower(51)
File "/home/woodnt/python/lib/box.py", line 24, in line_lower
print upper_line * len
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-50: ordinal not in range(128)
Any ideas if this can be made to work without a lot of "under the hood" work? I'm just learning programming and starting with python
| [
"I'd say running your program from the console should work correctly because Python can guess the console encoding of the terminal window (cp437 on US Windows), but when run through a pipe Python uses the default of ascii. Try changing your program to encode all Unicode output to an explicit encoding, such as:\npr... | [
2
] | [] | [] | [
"popen",
"python",
"shell",
"unicode"
] | stackoverflow_0003810302_popen_python_shell_unicode.txt |
Q:
Using python in android to interface to sql
I know you can use python and other scripting languages in android. But I haven't seen weather or not it was possible to use python as an interface to sqlite in android. Is this possible? This is the first android app where I've needed sqlite, and using the java api's is retarded.
If this isn't possible, can someone point me to a good tutorial on sqlite in android? I've found a bunch, but all of them are entirely different and I'm totally lost on which is the best way to do it.
It's just hard to picture how google expects you to use the sqlite database. It seems like you need like 10 different classes just to query a database.
A:
Actually you just need 3 classes:
A ContentProvider, as found here: http://developer.android.com/guide/topics/providers/content-providers.html
Second you need is a SQLiteOpenHelper and last but not least a Cursor
Edit: Just noticed it's not obvious from the snippets what the db variable is. It's the SQLiteOpenHelper or better my extension of it (where I've only overridden the onCreate, onUpgrade and constructor. See below ^^
The ContentProvider is the one which will be communicating with the database and do the inserts, updates, deletes. The content provider will also allow other parts of your code (even other Apps, if you allow it) to access the data stored in the sqlite.
You can then override the insert/delete/query/update functions and add your functionality to it, for example perform different actions depending on the URI of the intent.
public int delete(Uri uri, String whereClause, String[] whereArgs) {
int count = 0;
switch(URI_MATCHER.match(uri)){
case ITEMS:
// uri = content://com.yourname.yourapp.Items/item
// delete all rows
count = db.delete(TABLE_ITEMS, whereClause, whereArgs);
break;
case ITEMS_ID:
// uri = content://com.yourname.yourapp.Items/item/2
// delete the row with the id 2
String segment = uri.getPathSegments().get(1);
count = db.delete(TABLE_ITEMS,
Item.KEY_ITEM_ID +"="+segment
+(!TextUtils.isEmpty(whereClause)?" AND ("+whereClause+")":""),
whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown Uri: "+uri);
}
return count;
}
The UriMatcher is defined as
private static final int ITEMS = 1;
private static final int ITEMS_ID = 2;
private static final String AUTHORITY_ITEMS ="com.yourname.yourapp.Items";
private static final UriMatcher URI_MATCHER;
static {
URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
URI_MATCHER.addURI(AUTHORITY_ITEMS, "item", ITEMS);
URI_MATCHER.addURI(AUTHORITY_ITEMS, "item/#", ITEMS_ID);
}
This way you can decide if only 1 result shall be returned or updated or if all should be queried or not.
The SQLiteOpenHelper will actually perform the insert and also take care of upgrades if the structure of your SQLite database changes, you can perform it there by overriding
class ItemDatabaseHelper extends SQLiteOpenHelper {
public ItemDatabaseHelper(Context context){
super(context, "myDatabase.db", null, ITEMDATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String createItemsTable = "create table " + TABLE_ITEMS + " (" +
...
");";
// Begin Transaction
db.beginTransaction();
try{
// Create Items table
db.execSQL(createItemsTable);
// Transaction was successful
db.setTransactionSuccessful();
} catch(Exception ex) {
Log.e(this.getClass().getName(), ex.getMessage(), ex);
} finally {
// End transaction
db.endTransaction();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String dropItemsTable = "DROP TABLE IF EXISTS " + TABLE_ITEMS;
// Begin transaction
db.beginTransaction();
try {
if(oldVersion<2){
// Upgrade from version 1 to version 2: DROP the whole table
db.execSQL(dropItemsTable);
onCreate(db);
Log.i(this.getClass().toString(),"Successfully upgraded to Version 2");
}
if(oldVersion<3) {
// minor change, perform an ALTER query
db.execSQL("ALTER ...");
}
db.setTransactionSuccessful();
} catch(Exception ex){
Log.e(this.getClass().getName(), ex.getMessage(), ex);
} finally {
// Ends transaction
// If there was an error, the database won't be altered
db.endTransaction();
}
}
}
and then the easiest part of all: Perform a query:
String[] rows = new String[] {"_ID", "_name", "_email" };
Uri uri = Uri.parse("content://com.yourname.yourapp.Items/item/2";
// Alternatively you can also use getContentResolver().insert/update/query/delete methods
Cursor c = managedQuery(uri, rows, "someRow=1", null, null);
That's basically all and the most elegant way to do it as far as I know.
| Using python in android to interface to sql | I know you can use python and other scripting languages in android. But I haven't seen weather or not it was possible to use python as an interface to sqlite in android. Is this possible? This is the first android app where I've needed sqlite, and using the java api's is retarded.
If this isn't possible, can someone point me to a good tutorial on sqlite in android? I've found a bunch, but all of them are entirely different and I'm totally lost on which is the best way to do it.
It's just hard to picture how google expects you to use the sqlite database. It seems like you need like 10 different classes just to query a database.
| [
"Actually you just need 3 classes:\nA ContentProvider, as found here: http://developer.android.com/guide/topics/providers/content-providers.html\nSecond you need is a SQLiteOpenHelper and last but not least a Cursor\nEdit: Just noticed it's not obvious from the snippets what the db variable is. It's the SQLiteOpenH... | [
1
] | [] | [] | [
"android",
"android_scripting",
"python",
"sqlite"
] | stackoverflow_0003800944_android_android_scripting_python_sqlite.txt |
Q:
Optimizing mean in python
I have a function which updates the centroid (mean) in a K-means algoritm.
I ran a profiler and noticed that this function uses a lot of computing time.
It looks like:
def updateCentroid(self, label):
X=[]; Y=[]
for point in self.clusters[label].points:
X.append(point.x)
Y.append(point.y)
self.clusters[label].centroid.x = numpy.mean(X)
self.clusters[label].centroid.y = numpy.mean(Y)
So I ponder, is there a more efficient way to calculate the mean of these points?
If not, is there a more elegant way to formulate it? ;)
EDIT:
Thanks for all great responses!
I was thinking that perhaps I can calculate the mean cumulativly, using something like:
where x_bar(t) is the new mean and x_bar(t-1) is the old mean.
Which would result in a function similar to this:
def updateCentroid(self, label):
cluster = self.clusters[label]
n = len(cluster.points)
cluster.centroid.x *= (n-1) / n
cluster.centroid.x += cluster.points[n-1].x / n
cluster.centroid.y *= (n-1) / n
cluster.centroid.y += cluster.points[n-1].y / n
Its not really working but do you think this could work with some tweeking?
A:
A K-means algorithm is already implemented in scipy.cluster.vq. If there is something about that implementation that you are trying to change, then I'd suggest start by studying the code there:
In [62]: import scipy.cluster.vq as scv
In [64]: scv.__file__
Out[64]: '/usr/lib/python2.6/dist-packages/scipy/cluster/vq.pyc'
PS. Because the algorithm you posted holds the data behind a dict (self.clusters) and attribute lookup (.points) you are forced to use slow Python looping just to get at your data. A major speed gain could be achieved by sticking with numpy arrays. See the scipy implementation of k-means clustering for ideas on a better data structure.
A:
Why not avoid constructing the extra arrays?
def updateCentroid(self, label):
sumX=0; sumY=0
N = len( self.clusters[label].points)
for point in self.clusters[label].points:
sumX += point.x
sumY += point.y
self.clusters[label].centroid.x = sumX/N
self.clusters[label].centroid.y = sumY/N
A:
The costly part of your function is most certainly the iteration over the points. Avoid it altogether by making self.clusters[label].points a numpy array itself, and then compute the mean directly on it. For example if points contains X and Y coordinates concatenated in a 1D array:
points = self.clusters[label].points
x_mean = numpy.mean(points[0::2])
y_mean = numpy.mean(points[1::2])
A:
Without extra lists:
def updateCentroid(self, label):
self.clusters[label].centroid.x = numpy.fromiter(point.x for point in self.clusters[label].points, dtype = np.float).mean()
self.clusters[label].centroid.y = numpy.fromiter(point.y for point in self.clusters[label].points, dtype = np.float).mean()
A:
Perhaps the added features of numpy's mean are adding a bit of overhead.
>>> def myMean(itr):
... c = t = 0
... for item in itr:
... c += 1
... t += item
... return t / c
...
>>> import timeit
>>> a = range(20)
>>> t1 = timeit.Timer("myMean(a)","from __main__ import myMean, a")
>>> t1.timeit()
6.8293311595916748
>>> t2 = timeit.Timer("average(a)","from __main__ import a; from numpy import average")
>>> t2.timeit()
69.697283029556274
>>> t3 = timeit.Timer("average(array(a))","from __main__ import a; from numpy import average, array")
>>> t3.timeit()
51.65147590637207
>>> t4 = timeit.Timer("fromiter(a,npfloat).mean()","from __main__ import a; from numpy import average, fromiter,float as npfloat")
>>> t4.timeit()
18.513712167739868
Looks like numpy's best performance came when using fromiter.
A:
Ok, I figured out a moving average solution which is fast without changing the data structures:
def updateCentroid(self, label):
cluster = self.clusters[label]
n = len(cluster.points)
cluster.centroid.x = ((n-1)*cluster.centroid.x + cluster.points[n-1].x)/n
cluster.centroid.y = ((n-1)*cluster.centroid.y + cluster.points[n-1].y)/n
This lowered computation time (for the whole k means algorithm) to 13% of original. =)
Thank you all for some great insight!
A:
Try this:
def updateCentroid(self, label):
self.clusters[label].centroid.x = numpy.array([point.x for point in self.clusters[label].points]).mean()
self.clusters[label].centroid.y = numpy.array([point.y for point in self.clusters[label].points]).mean()
A:
That's the problem with profilers that only tell you about functions. This is the method I use, and it pinpoints costly lines of code, including points where functions are called.
That said, there's a general idea that data structure is free. As @Michael-Anderson asked, why not avoid making an array? That's the first thing I saw in your code, that you're building arrays by appending. You don't need to.
A:
One way to go is add an x_sum and y_sum to your "clusters" object and sum the coordinates as points are added. If things are moving around, you can also update the sum as points move. Then getting the centroid is just a matter of dividing the x_sum and y_sum by the number of points. If your points are numpy vectors that can be added, then you don't even need to sum the components, just maintain a sum of all the vectors and multiply be 1/len at the end.
| Optimizing mean in python | I have a function which updates the centroid (mean) in a K-means algoritm.
I ran a profiler and noticed that this function uses a lot of computing time.
It looks like:
def updateCentroid(self, label):
X=[]; Y=[]
for point in self.clusters[label].points:
X.append(point.x)
Y.append(point.y)
self.clusters[label].centroid.x = numpy.mean(X)
self.clusters[label].centroid.y = numpy.mean(Y)
So I ponder, is there a more efficient way to calculate the mean of these points?
If not, is there a more elegant way to formulate it? ;)
EDIT:
Thanks for all great responses!
I was thinking that perhaps I can calculate the mean cumulativly, using something like:
where x_bar(t) is the new mean and x_bar(t-1) is the old mean.
Which would result in a function similar to this:
def updateCentroid(self, label):
cluster = self.clusters[label]
n = len(cluster.points)
cluster.centroid.x *= (n-1) / n
cluster.centroid.x += cluster.points[n-1].x / n
cluster.centroid.y *= (n-1) / n
cluster.centroid.y += cluster.points[n-1].y / n
Its not really working but do you think this could work with some tweeking?
| [
"A K-means algorithm is already implemented in scipy.cluster.vq. If there is something about that implementation that you are trying to change, then I'd suggest start by studying the code there:\nIn [62]: import scipy.cluster.vq as scv\nIn [64]: scv.__file__\nOut[64]: '/usr/lib/python2.6/dist-packages/scipy/cluster... | [
5,
3,
3,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"numpy",
"optimization",
"python"
] | stackoverflow_0003803673_numpy_optimization_python.txt |
Q:
Regular expression for string between two strings?
Sorry, I know this is probably a duplicate but having searched for 'python regular expression match between' I haven't found anything that answers my question!
The document (which to make clear, is a long HTML page) I'm searching has a whole bunch of strings in it (inside a JavaScript function) that look like this:
link: '/Hidden/SidebySideGreen/dei1=1204970159862'};
link: '/Hidden/SidebySideYellow/dei1=1204970159862'};
I want to extract the links (i.e. everything between quotes within these strings) - e.g. /Hidden/SidebySideYellow/dei1=1204970159862
To get the links, I know I need to start with:
re.matchall(regexp, doc_sting)
But what should regexp be?
A:
The answer to your question depends on how the rest of the string may look like. If they are all like this link: '<URL>'}; then you can do it very simple using simple string manipulation:
myString = "link: '/Hidden/SidebySideGreen/dei1=1204970159862'};"
print( myString[7:-3] )
(If you just have one string with multiple lines by that, you can just split the string into lines.)
If it is a bit more complex though, using regular expressions are fine. One example that just looks for the url inside of the quotes would be:
myDoc = """link: '/Hidden/SidebySideGreen/dei1=1204970159862'};
link: '/Hidden/SidebySideYellow/dei1=1204970159862'};"""
print( re.findall( "'([^']+)'", myDoc ) )
Depending on how the whole string looks, you might have to include the link: as well:
print( re.findall( "link: '([^']+)'", myDoc ) )
A:
I'd start with:
regexp = "'([^']+)'"
And check if it works okay - I mean, if the only condition is that string is in one line between '', it should be good as it is.
A:
Use a few simple splits
>>> s="link: '/Hidden/SidebySideGreen/dei1=1204970159862'};"
>>> s.split("'")
['link: ', '/Hidden/SidebySideGreen/dei1=1204970159862', '};']
>>> for i in s.split("'"):
... if "/" in i:
... print i
...
/Hidden/SidebySideGreen/dei1=1204970159862
>>>
| Regular expression for string between two strings? | Sorry, I know this is probably a duplicate but having searched for 'python regular expression match between' I haven't found anything that answers my question!
The document (which to make clear, is a long HTML page) I'm searching has a whole bunch of strings in it (inside a JavaScript function) that look like this:
link: '/Hidden/SidebySideGreen/dei1=1204970159862'};
link: '/Hidden/SidebySideYellow/dei1=1204970159862'};
I want to extract the links (i.e. everything between quotes within these strings) - e.g. /Hidden/SidebySideYellow/dei1=1204970159862
To get the links, I know I need to start with:
re.matchall(regexp, doc_sting)
But what should regexp be?
| [
"The answer to your question depends on how the rest of the string may look like. If they are all like this link: '<URL>'}; then you can do it very simple using simple string manipulation:\nmyString = \"link: '/Hidden/SidebySideGreen/dei1=1204970159862'};\"\nprint( myString[7:-3] )\n\n(If you just have one string w... | [
3,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003811064_python_regex.txt |
Q:
Error when the Email formencode validator
I wanted to create an IDN-aware formencode validator to use in one of my projects. I used a portion of code from the Django project (http://code.djangoproject.com/svn/django/trunk/django/core/validators.py) to do that, but there must be a trivial error in my code I can't find :
class Email(formencode.validators.Email):
def _to_python(self, value, state):
try:
return super(Email, self)._to_python(value, state)
except formencode.Invalid as e:
# Trivial case failed. Try for possible IDN domain-part
print 'heywo !'
if value and u'@' in value:
parts = value.split(u'@')
try:
parts[-1] = parts[-1].encode('idna')
except UnicodeError:
raise e
try:
super(Email, self)._to_python(u'@'.join(parts), state)
except formencode.Invalid as ex:
raise ex
return value
else:
raise e
When I try to validate an email with an IDN domain (ex: test@wääl.de), the Invalid exception raised by the first call is thrown, and the portion of code after the first except is never executed ('heywo !' is never printed).
There is an example :
>>> from test.lib.validators import Email
>>> Email().to_python(u'test@zääz.de')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/FormEncode-1.2.3dev-py2.6.egg/formencode /api.py", line 416, in to_python
vp(value, state)
File "/usr/local/lib/python2.6/dist-packages/FormEncode-1.2.3dev-py2.6.egg/formencode /validators.py", line 1352, in validate_python
value, state)
Invalid: The domain portion of the email address is invalid (the portion after the @: z\xe4\xe4z.de)
What did I do wrong ?
Thanks.
A:
Okay, found the answer. I was overloading _to_python instead of validate_python. The class now looks like :
class Email(formencode.validators.Email):
def validate_python(self, value, state):
try:
super(Email, self).validate_python(value, state)
except formencode.Invalid as e:
# Trivial case failed. Try for possible IDN domain-part
if value and u'@' in value:
parts = value.split(u'@')
try:
parts[-1] = parts[-1].encode('idna')
except UnicodeError:
raise e
try:
super(Email, self).validate_python(u'@'.join(parts), state)
except formencode.Invalid as ex:
raise ex
else:
raise e
It's working perfectly :)
| Error when the Email formencode validator | I wanted to create an IDN-aware formencode validator to use in one of my projects. I used a portion of code from the Django project (http://code.djangoproject.com/svn/django/trunk/django/core/validators.py) to do that, but there must be a trivial error in my code I can't find :
class Email(formencode.validators.Email):
def _to_python(self, value, state):
try:
return super(Email, self)._to_python(value, state)
except formencode.Invalid as e:
# Trivial case failed. Try for possible IDN domain-part
print 'heywo !'
if value and u'@' in value:
parts = value.split(u'@')
try:
parts[-1] = parts[-1].encode('idna')
except UnicodeError:
raise e
try:
super(Email, self)._to_python(u'@'.join(parts), state)
except formencode.Invalid as ex:
raise ex
return value
else:
raise e
When I try to validate an email with an IDN domain (ex: test@wääl.de), the Invalid exception raised by the first call is thrown, and the portion of code after the first except is never executed ('heywo !' is never printed).
There is an example :
>>> from test.lib.validators import Email
>>> Email().to_python(u'test@zääz.de')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/FormEncode-1.2.3dev-py2.6.egg/formencode /api.py", line 416, in to_python
vp(value, state)
File "/usr/local/lib/python2.6/dist-packages/FormEncode-1.2.3dev-py2.6.egg/formencode /validators.py", line 1352, in validate_python
value, state)
Invalid: The domain portion of the email address is invalid (the portion after the @: z\xe4\xe4z.de)
What did I do wrong ?
Thanks.
| [
"Okay, found the answer. I was overloading _to_python instead of validate_python. The class now looks like :\nclass Email(formencode.validators.Email):\n def validate_python(self, value, state):\n try:\n super(Email, self).validate_python(value, state)\n except formencode.Invalid as e:\n... | [
0
] | [] | [] | [
"formencode",
"python"
] | stackoverflow_0003808698_formencode_python.txt |
Q:
executemany problem, MySQLdb
I'm using MySQLdb and run into the following problem:
STMT="""INSERT INTO test_table VALUES (%s, %s, %s, %s, %s)"""
rows=[('Wed Apr 14 14:00:00 2010', 23L, -2.3, 4.41, 0.83923)]
conn.cursor().executemay(STMT, rows)
results in:
Traceback (most recent call last):
File "run.py", line 122, in <module>
File "C:\Python25\lib\site-packages\mysql_python-1.2.2.0002-py2.5-win32.egg\MySQLdb\cursors.py", line 276, in _do_query
db.query(q)
_mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1")
Any hints ?
A:
Try to write all columns in your INSERT explicitly:
STMT = 'INSERT INTO test_table (col1, col2, col3, col4, col5) VALUES (%s, %s, %s, %s, %s)'
A:
How many columns are there altogether in test_table? Probably not 5, judging from the error. Try running SHOW CREATE TABLE test_table to see how the table is defined.
It is a good idea to explicitly list the column names when inserting in case new columns are added. Try this instead:
INSERT INTO test_table (col1, col2, col3, col4, col5) VALUES (%s, %s, %s, %s, %s)
You should change col1, col2, etc. to your real column names.
| executemany problem, MySQLdb | I'm using MySQLdb and run into the following problem:
STMT="""INSERT INTO test_table VALUES (%s, %s, %s, %s, %s)"""
rows=[('Wed Apr 14 14:00:00 2010', 23L, -2.3, 4.41, 0.83923)]
conn.cursor().executemay(STMT, rows)
results in:
Traceback (most recent call last):
File "run.py", line 122, in <module>
File "C:\Python25\lib\site-packages\mysql_python-1.2.2.0002-py2.5-win32.egg\MySQLdb\cursors.py", line 276, in _do_query
db.query(q)
_mysql_exceptions.OperationalError: (1136, "Column count doesn't match value count at row 1")
Any hints ?
| [
"Try to write all columns in your INSERT explicitly:\nSTMT = 'INSERT INTO test_table (col1, col2, col3, col4, col5) VALUES (%s, %s, %s, %s, %s)'\n\n",
"How many columns are there altogether in test_table? Probably not 5, judging from the error. Try running SHOW CREATE TABLE test_table to see how the table is defi... | [
2,
1
] | [] | [] | [
"api",
"database",
"mysql",
"python",
"sql"
] | stackoverflow_0003811431_api_database_mysql_python_sql.txt |
Q:
Running Python-script in thread and redirecting std.out/std.err to wx.TextCtrl in GUI
I'm trying to write a GUI that reads in settings for a python-script, then generates the script and runs it. The script can take dozens of minutes to run so in order to not block the GUI and frustrate the user I'm running it in a separate thread. Before I did this I used a separate class to redirect the std.out and std.err of the program to a TextCtrl. This worked fine except for the GUI getting blocked during execution.
Running the script from the thread with the redirection-class still blocks the GUI. In order not to block the GUI I need to turn the redirection off. All std.out/err from both the script and the gui then goes into the console.
Here is the class that redirects and how I call it.
# For redirecting stdout/stderr to txtctrl.
class RedirectText(object):
def __init__(self,aWxTextCtrl):
self.out=aWxTextCtrl
def write(self,string):
self.out.WriteText(string)
self.redir=RedirectText(self.bottom_text)
sys.stdout=self.redir
sys.stderr=self.redir
sys.stdin=self.redir
I've tried using some kind of a communication class from the thread to the GUI without success. That is, the GUI still gets blocked.
Does anyone have some hints or a solution for this problem, that is to get the stdout/err from the script to the GUI without blocking the GUI?
A:
Yeah. From the thread, use wx.CallAfter to send the text to the GUI to a thread-safe way. Then it can take the text and display it. Another way to do it would be to use subprocess and communicate with that. There's an example of that here:
http://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-traceroute-and-more/
There are also some methods listed in the comments of this article:
http://www.blog.pythonlibrary.org/2009/01/01/wxpython-redirecting-stdout-stderr/
Unfortunately, my commenting system at that time didn't do a good job with indentation.
A:
Another solution I have used with success would be to use python logging instead of stdout/stderr. In order to do that, you write a subclass that extends logging.Handler, to customize the font and the text color to be presented in a wx.TextCtrl in your wx application:
import logging
from logging import Handler
class WxHandler(Handler):
def __init__(self, logCtrl):
"""
Initialize the handler.
logCtrl = an instance of wx.TextCtrl
"""
self.logCtrl = logCtrl
Handler.__init__(self)
def flush(self):
pass
def emit(self, record):
"""
Emit a record.
If a formatter is specified, it is used to format the record.
The record is then written to the stream with a trailing newline. If
exception information is present, it is formatted using
traceback.print_exception and appended to the stream. If the stream
has an 'encoding' attribute, it is used to encode the message before
output to the stream.
"""
try:
lastPos = self.logCtrl.GetLastPosition()
msg = self.format(record)
self.logCtrl.WriteText(msg)
self.logCtrl.WriteText('\r\n')
f = wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Arial', wx.FONTENCODING_ISO8859_1)
if record.levelno == logging.INFO:
textColour = wx.Colour(0, 0, 205)
elif record.levelno == logging.WARN:
textColour = wx.Colour(250, 128, 114)
elif record.levelno >= logging.ERROR:
textColour = wx.Colour(220, 20, 60)
else:
textColour = wx.Colour(0, 0, 0)
self.logCtrl.SetStyle(lastPos, lastPos + len(msg), wx.TextAttr(textColour, wx.NullColour, f))
except:
self.handleError(record)
In order to configure the logger:
def configureWxLogger(logCtrl, loggingLevel):
"""
Wx Logger config
"""
logger = logging.getLogger()
logger.setLevel(loggingLevel)
ch = WxHandler(logCtrl)
formatter = logging.Formatter("%(asctime)-20s - %(levelname)-8s - %(message)s")
formatter.datefmt = '%d/%m/%Y-%H:%M:%S'
ch.setFormatter(formatter)
logger.addHandler(ch)
return logger
And, finally, to bind the text control to the log output:
self.logCtrl = wx.TextCtrl(self, -1, "", size=(600, 200), style=wx.TE_MULTILINE|wx.TE_RICH2)
wxLoggingHelper.configureWxLogger(self.logCtrl, logging.DEBUG)
| Running Python-script in thread and redirecting std.out/std.err to wx.TextCtrl in GUI | I'm trying to write a GUI that reads in settings for a python-script, then generates the script and runs it. The script can take dozens of minutes to run so in order to not block the GUI and frustrate the user I'm running it in a separate thread. Before I did this I used a separate class to redirect the std.out and std.err of the program to a TextCtrl. This worked fine except for the GUI getting blocked during execution.
Running the script from the thread with the redirection-class still blocks the GUI. In order not to block the GUI I need to turn the redirection off. All std.out/err from both the script and the gui then goes into the console.
Here is the class that redirects and how I call it.
# For redirecting stdout/stderr to txtctrl.
class RedirectText(object):
def __init__(self,aWxTextCtrl):
self.out=aWxTextCtrl
def write(self,string):
self.out.WriteText(string)
self.redir=RedirectText(self.bottom_text)
sys.stdout=self.redir
sys.stderr=self.redir
sys.stdin=self.redir
I've tried using some kind of a communication class from the thread to the GUI without success. That is, the GUI still gets blocked.
Does anyone have some hints or a solution for this problem, that is to get the stdout/err from the script to the GUI without blocking the GUI?
| [
"Yeah. From the thread, use wx.CallAfter to send the text to the GUI to a thread-safe way. Then it can take the text and display it. Another way to do it would be to use subprocess and communicate with that. There's an example of that here:\nhttp://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-tracerout... | [
2,
2
] | [] | [] | [
"multithreading",
"python",
"redirect",
"user_interface",
"wxpython"
] | stackoverflow_0003556290_multithreading_python_redirect_user_interface_wxpython.txt |
Q:
Buildout + Nose failing with passed options options
After running a buildout operation on my project, I can run nose with the following command:
# ./bin/nosetests
----------------------------------------------------------------------
Ran 0 tests in 0.310s
However, when I try to pass options (such as -w for the base directory, I get the following:
# ./bin/nosetests -vv --detailed-errors --exe
Usage: nosetests [options]
nosetests: error: no such option: -v
I've checked the test files which are being ran, and removed all lines importing either getopt or OptionParser to ensure they're not getting in the way, but I'm still getting the same error regardless.
I believe one of the files we're testing requires getopt to function... is there any way I can get nosetests to work with buildout without these errors?
A:
You can use noserunner buildout recipe
Here is example buildout.cfg:
[buildout]
parts = test
index = http://download.zope.org/simple
[test]
recipe = pbp.recipe.noserunner
eggs = pbp.recipe.noserunner
working-directory = ${buildout:directory}
This will create script test in bin directory. Runner will run all tests found in path set in working-directory
| Buildout + Nose failing with passed options options | After running a buildout operation on my project, I can run nose with the following command:
# ./bin/nosetests
----------------------------------------------------------------------
Ran 0 tests in 0.310s
However, when I try to pass options (such as -w for the base directory, I get the following:
# ./bin/nosetests -vv --detailed-errors --exe
Usage: nosetests [options]
nosetests: error: no such option: -v
I've checked the test files which are being ran, and removed all lines importing either getopt or OptionParser to ensure they're not getting in the way, but I'm still getting the same error regardless.
I believe one of the files we're testing requires getopt to function... is there any way I can get nosetests to work with buildout without these errors?
| [
"You can use noserunner buildout recipe\nHere is example buildout.cfg:\n[buildout]\nparts = test\nindex = http://download.zope.org/simple\n\n[test]\nrecipe = pbp.recipe.noserunner\neggs = pbp.recipe.noserunner\nworking-directory = ${buildout:directory}\n\nThis will create script test in bin directory. Runner will r... | [
5
] | [] | [] | [
"buildout",
"nose",
"python"
] | stackoverflow_0003557865_buildout_nose_python.txt |
Q:
Creating a website to communicate with an embedded device
I'm currently working on a project where I'm trying to control an embedded device through an Internet facing website. The idea is is that a user can go to a website and tell this device to preform some kind of action. An action on the website would be translated into a series of CLI commands and then sent to the device. Communication could potentially go both ways in the future, but right now I'm focusing on server-to-device.
The web server is a LAMP stack using Python (Django) and the device I'm trying to communicate with is a Beagle Board running eLinux. There would be only one device existing at any time communicating to the server.
I have all the functional parts written on the server and device side, but I'm having a bit of trouble figuring out how to write the communication layer. One of my big issues is that the device will be mobile and will be moving locations every few days. So, I can't guarantee a static IP address for the device. My networking programming knowledge is pretty minimal so I don't have that great an idea on where to start.
Does anyone have any ideas/resources on how I can start developing this kind of communication?
Thanks!
A:
You can simply register a dynamic host name using a provider like DynDNS and have the device update it's IP on that website so the dynamic hostname always points to the device IP - there are plenty of clients, scripts etc. available for Linux that do just that.
A:
If the server is going to be static, you could always get the device to establish a connection to the server to report it's IP address.
You could write a simple UDP server for the device to listen for incoming communications and then write a client in python for your web server to call.
A:
My normal mode of conduct (certainly as it could have to go through NATs and the like) is to have the device set up a reverse SSH tunnel that just 'calls home': http://www.howtoforge.com/reverse-ssh-tunneling
Mind you, SSH connections break from time to time, so I'd set a heartbeat method on the server, and if the client (Beagle Board) misses a set amount of heartbeats, let it destroy the tunnel & create a new one.
A:
the device will be mobile and will be moving locations every few days. So, I can't guarantee a static IP address for the device.
Your device can be a client of the web site.
Your web site has two interfaces.
HTML interface to people.
A non-HTML interface to the device. As a client of a web site, the device will need an HTTP client-side library to send a request to the web site. This request will include the device's IP address, plus all the usual malarky buried in an HTTP request. (There are a bunch of standard headers that are sent in a request)
Once the device has made it's initial request, then your web site can save the device's current status and communicate with it through another protocol if you want to do that.
(I'm guessing that "I have all the functional parts written on the server and device side" means you have some other protocol for controlling the device, and this protocol isn't based on HTTP.)
It might be simplest in the long run to have the device poll the web site for commands or updates or things. That way the device is a pure web client using only HTTP, and your web site is a pure web server, using only HTTP. Then you don't need your more specialized second protocol. Using only HTTP means you can use SSL to assure a secure communication.
If your device uses HTTP to get commands and updates, you'll need to work out a usable representation for data that can easily be encoded into HTTP requests and responses. Choices include XML, JSON and YAML. You can always invent your own data format; however, you'll probably be happier debugging a standardized format like JSON.
Building these two interfaces in Django is pretty trivial. You'll simply have some URL's which are for people and some which are for your device. You'll have view functions for people that return HTML pages, and view functions for your device that return JSON or XML messages.
| Creating a website to communicate with an embedded device | I'm currently working on a project where I'm trying to control an embedded device through an Internet facing website. The idea is is that a user can go to a website and tell this device to preform some kind of action. An action on the website would be translated into a series of CLI commands and then sent to the device. Communication could potentially go both ways in the future, but right now I'm focusing on server-to-device.
The web server is a LAMP stack using Python (Django) and the device I'm trying to communicate with is a Beagle Board running eLinux. There would be only one device existing at any time communicating to the server.
I have all the functional parts written on the server and device side, but I'm having a bit of trouble figuring out how to write the communication layer. One of my big issues is that the device will be mobile and will be moving locations every few days. So, I can't guarantee a static IP address for the device. My networking programming knowledge is pretty minimal so I don't have that great an idea on where to start.
Does anyone have any ideas/resources on how I can start developing this kind of communication?
Thanks!
| [
"You can simply register a dynamic host name using a provider like DynDNS and have the device update it's IP on that website so the dynamic hostname always points to the device IP - there are plenty of clients, scripts etc. available for Linux that do just that.\n",
"If the server is going to be static, you could... | [
3,
3,
2,
0
] | [] | [] | [
"apache",
"beagleboard",
"embedded",
"python"
] | stackoverflow_0003808581_apache_beagleboard_embedded_python.txt |
Q:
Python RE - different matching for finditer and findall
here is some code:
>>> p = re.compile(r'\S+ (\[CC\] )+\S+')
>>> s1 = 'always look [CC] on the bright side'
>>> s2 = 'always look [CC] [CC] on the bright side'
>>> s3 = 'always look [CC] on the [CC] bright side'
>>> m1 = p.search(s1)
>>> m1.group()
'look [CC] on'
>>> p.findall(s1)
['[CC] ']
>>> itr = p.finditer(s1)
>>> for i in itr:
... i.group()
...
'look [CC] on'
Obviously, this is more relevant for finding all matches in s3 in which findall returns: ['[CC] ', '[CC] '], as it seems that findall only matches the inner group in p while finditer matches the whole pattern.
Why is that happening?
(I defined p as i did in order to allow capturing patterns that contain sequences of [CC]s such as 'look [CC] [CC] on' in s2).
Thanks
A:
i.group() returns the whole match, including the non-whitespace characters before and after your group. To get the same result as in your findall example, use i.group(1)
http://docs.python.org/library/re.html#re.MatchObject.group
In [4]: for i in p.finditer(s1):
...: i.group(1)
...:
...:
Out[4]: '[CC] '
| Python RE - different matching for finditer and findall | here is some code:
>>> p = re.compile(r'\S+ (\[CC\] )+\S+')
>>> s1 = 'always look [CC] on the bright side'
>>> s2 = 'always look [CC] [CC] on the bright side'
>>> s3 = 'always look [CC] on the [CC] bright side'
>>> m1 = p.search(s1)
>>> m1.group()
'look [CC] on'
>>> p.findall(s1)
['[CC] ']
>>> itr = p.finditer(s1)
>>> for i in itr:
... i.group()
...
'look [CC] on'
Obviously, this is more relevant for finding all matches in s3 in which findall returns: ['[CC] ', '[CC] '], as it seems that findall only matches the inner group in p while finditer matches the whole pattern.
Why is that happening?
(I defined p as i did in order to allow capturing patterns that contain sequences of [CC]s such as 'look [CC] [CC] on' in s2).
Thanks
| [
"i.group() returns the whole match, including the non-whitespace characters before and after your group. To get the same result as in your findall example, use i.group(1)\nhttp://docs.python.org/library/re.html#re.MatchObject.group\nIn [4]: for i in p.finditer(s1):\n...: i.group(1)\n...: \n...: \nOut[4]... | [
1
] | [] | [] | [
"findall",
"python",
"regex"
] | stackoverflow_0003811743_findall_python_regex.txt |
Q:
Fastest way to calculate euclidian distance in 2D space
What is the fastes way of determening which point q out of n points in 2D space is the closest (smallest euclidian distance) to point p, see attached imgage.
My current method of doing this in Python is storing all the distances in a list and then running
numpy.argmin(list_of_distances)
This is however a bit slow when calculating this for m number of points p. Or is it?
A:
Instead of calculating the distances, you could calculate the squared distances. That way you don't need to perform n * m square roots.
A:
This falls under closest point query -problems.
How many points are expected? Are your points static or do they change? One naive but powerful approach for static points would be to pre-compute every known distance, which would result in O(1) lookup.
A:
Put everything as soon as possible into numpy and do calculations there. If you have many points, it is much faster than calculating distances in lists:
import numpy as np
px, py
x = np.fromiter(point.x for point in points, dtype = np.float)
y = np.fromiter(point.y for point in points, dtype = np.float)
i_closest = np.argmin((x - px) ** 2 + (y - py) ** 2)
| Fastest way to calculate euclidian distance in 2D space | What is the fastes way of determening which point q out of n points in 2D space is the closest (smallest euclidian distance) to point p, see attached imgage.
My current method of doing this in Python is storing all the distances in a list and then running
numpy.argmin(list_of_distances)
This is however a bit slow when calculating this for m number of points p. Or is it?
| [
"Instead of calculating the distances, you could calculate the squared distances. That way you don't need to perform n * m square roots.\n",
"This falls under closest point query -problems. \nHow many points are expected? Are your points static or do they change? One naive but powerful approach for static points ... | [
5,
4,
1
] | [] | [] | [
"distance",
"optimization",
"python"
] | stackoverflow_0003811621_distance_optimization_python.txt |
Q:
Why would it be important that a content delivery network uses a "reverse caching proxy"?
I was reading a description of a project on Github that is a Python-based content delivery network.
Why is it important that it uses a "reverse caching proxy" - and what does that mean in this context?
A:
I think you have the question backwards. It would make more sense to ask "Why would it be important that a reverse caching proxy uses a CDN ?".
Typically you put a reverse caching proxy in front of a web server. All inbound requests go through the proxy which may or may not pass the request to the web server.
It's great for reducing the load on the web server by caching static or dynamic content, and for other purposes such as security, compression, etc.
In this case, it's useless to use this proxy if your application is already hosted on Google App Engine (and a violation of ToS as well). It's meant to be used in front of a web server hosted elsewhere, a practice also known as web server "acceleration".
Just to clarify, SymPullCDN is a reverse caching proxy, not a "Python-based content delivery network". The 'CDN' part of the SymPullCDN name refers to the CDN aspect of GAE (many datacenters around the world) which is a nice feature for a proxy.
| Why would it be important that a content delivery network uses a "reverse caching proxy"? | I was reading a description of a project on Github that is a Python-based content delivery network.
Why is it important that it uses a "reverse caching proxy" - and what does that mean in this context?
| [
"I think you have the question backwards. It would make more sense to ask \"Why would it be important that a reverse caching proxy uses a CDN ?\".\nTypically you put a reverse caching proxy in front of a web server. All inbound requests go through the proxy which may or may not pass the request to the web server.\n... | [
2
] | [] | [] | [
"caching",
"content_delivery_network",
"google_app_engine",
"python",
"reverse_proxy"
] | stackoverflow_0003811665_caching_content_delivery_network_google_app_engine_python_reverse_proxy.txt |
Q:
Deleting rows in a ManyToMany intermediate table
I have two tables with a ManyToMany relation between them. Sometimes I need to refresh the
database so I delete elements from both tables. However relations between deleted rows are still stored inside the automatically created intermediary table.
To clarify the problem, here is a small code:
from elixir import *
metadata.bind = "sqlite:///test.db"
metadata.bind.echo = True
options_defaults['shortnames'] = True
class A(Entity):
name = Field(Unicode(128))
blist = ManyToMany("B",cascade='all,delete, delete-orphan')
class B(Entity):
name = Field(Unicode(128))
alist = ManyToMany("A",cascade='all,delete, delete-orphan')
setup_all()
create_all()
a1 = A()
a1.name = u"john"
b1 = B()
b1.name = u"blue"
a1.blist.append(b1)
session.commit()
session.query(A).delete()
session.query(B).delete()
session.commit()
A dump of the sqlite database now contains:
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE a (
id INTEGER NOT NULL,
name VARCHAR(128),
PRIMARY KEY (id)
);
CREATE TABLE b (
id INTEGER NOT NULL,
name VARCHAR(128),
PRIMARY KEY (id)
);
CREATE TABLE b_alist__a_blist (
a_id INTEGER NOT NULL,
b_id INTEGER NOT NULL,
PRIMARY KEY (a_id, b_id),
CONSTRAINT a_blist_fk FOREIGN KEY(a_id) REFERENCES a (id),
CONSTRAINT b_alist_fk FOREIGN KEY(b_id) REFERENCES b (id)
);
INSERT INTO "b_alist__a_blist" VALUES(1,1);
COMMIT;
I would like "b_alist__a_blist" table to be emptied either when a1 or b1 is deleted.
Is this possible without using ON DELETE statements that are not always supported with SQLite?
Since I'm certainly not the only one using a ManyToMany relationship with Elixir, the solution to this problem is probably trivial.
The code given above generates sqlalchemy warnings:
sqlalchemy/orm/properties.py:842:
SAWarning: On B.alist, delete-orphan
cascade is not supported on a
many-to-many or many-to-one
relationship when single_parent is not
set. Set single_parent=True on the
relationship().
self._determine_direction()
This is just because I'm now randomly trying to add cascade options in this ManyToMany relation. This should be a sign that delete-orphan is not the correct option.
A:
I think I have found the answer.
First, the problem is the same with sqlalchemy alone.
Then, this seems only to happen when using this syntax:
session.query(B).delete()
But one can obtain the desired behavior by using:
session.delete(b) #where b is an instance of B
A simple iteration of session.delete(b) for each b might then do the trick.
Maybe someone can comment on this difference of session.query().delete() and session.delete()...
| Deleting rows in a ManyToMany intermediate table | I have two tables with a ManyToMany relation between them. Sometimes I need to refresh the
database so I delete elements from both tables. However relations between deleted rows are still stored inside the automatically created intermediary table.
To clarify the problem, here is a small code:
from elixir import *
metadata.bind = "sqlite:///test.db"
metadata.bind.echo = True
options_defaults['shortnames'] = True
class A(Entity):
name = Field(Unicode(128))
blist = ManyToMany("B",cascade='all,delete, delete-orphan')
class B(Entity):
name = Field(Unicode(128))
alist = ManyToMany("A",cascade='all,delete, delete-orphan')
setup_all()
create_all()
a1 = A()
a1.name = u"john"
b1 = B()
b1.name = u"blue"
a1.blist.append(b1)
session.commit()
session.query(A).delete()
session.query(B).delete()
session.commit()
A dump of the sqlite database now contains:
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE a (
id INTEGER NOT NULL,
name VARCHAR(128),
PRIMARY KEY (id)
);
CREATE TABLE b (
id INTEGER NOT NULL,
name VARCHAR(128),
PRIMARY KEY (id)
);
CREATE TABLE b_alist__a_blist (
a_id INTEGER NOT NULL,
b_id INTEGER NOT NULL,
PRIMARY KEY (a_id, b_id),
CONSTRAINT a_blist_fk FOREIGN KEY(a_id) REFERENCES a (id),
CONSTRAINT b_alist_fk FOREIGN KEY(b_id) REFERENCES b (id)
);
INSERT INTO "b_alist__a_blist" VALUES(1,1);
COMMIT;
I would like "b_alist__a_blist" table to be emptied either when a1 or b1 is deleted.
Is this possible without using ON DELETE statements that are not always supported with SQLite?
Since I'm certainly not the only one using a ManyToMany relationship with Elixir, the solution to this problem is probably trivial.
The code given above generates sqlalchemy warnings:
sqlalchemy/orm/properties.py:842:
SAWarning: On B.alist, delete-orphan
cascade is not supported on a
many-to-many or many-to-one
relationship when single_parent is not
set. Set single_parent=True on the
relationship().
self._determine_direction()
This is just because I'm now randomly trying to add cascade options in this ManyToMany relation. This should be a sign that delete-orphan is not the correct option.
| [
"I think I have found the answer. \nFirst, the problem is the same with sqlalchemy alone. \nThen, this seems only to happen when using this syntax:\nsession.query(B).delete()\n\nBut one can obtain the desired behavior by using:\nsession.delete(b) #where b is an instance of B\n\nA simple iteration of session.delete... | [
1
] | [] | [] | [
"orm",
"python",
"python_elixir",
"sqlalchemy",
"sqlite"
] | stackoverflow_0003808632_orm_python_python_elixir_sqlalchemy_sqlite.txt |
Q:
How to strip " (quotes) from post data
I have a textbox. When the user enters the " symbol. I had to strip that symbol before storing into the database.
Django code:
postDict = request.POST.copy()
profile = quser.get_profile()
profile.i_like= postDict['value']
profile=profile.save()
A:
No, you need to escape the quotes, not strip them. Depending on your database, functions such as mysql_real_escape_sting() will do this
(assumption, you're using PHP because you've tagged this question "PHP")
A:
(Python answer) You can either remove the quotes by simply replacing them in the string (by using myString.replace( '"', '' )) or – which would be a better solution – store the quotes in the database as well but just make sure that they are escaped correctly. How this works depends on your database, but “escaping” is a good keyword to search for, another would be “prepared statements” when you are using an SQL database.
A:
You can use escape function, build in to django. This function returns the given HTML with ampersands, quotes and angle brackets encoded.
Example:
In [1]: from django.utils.html import escape
In [2]: escape('"test"')
Out[2]: u'"test"'
A:
Use str_replace() for that. You might also just need to escape it, and store it in the database.
$text2 = str_replace('"', '', $text1); //removing
$text2 = str_replace('"', '\"', $text1); //escaping
| How to strip " (quotes) from post data | I have a textbox. When the user enters the " symbol. I had to strip that symbol before storing into the database.
Django code:
postDict = request.POST.copy()
profile = quser.get_profile()
profile.i_like= postDict['value']
profile=profile.save()
| [
"No, you need to escape the quotes, not strip them. Depending on your database, functions such as mysql_real_escape_sting() will do this\n(assumption, you're using PHP because you've tagged this question \"PHP\")\n",
"(Python answer) You can either remove the quotes by simply replacing them in the string (by usin... | [
1,
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003812462_django_python.txt |
Q:
Using Pip, how do I force upgrade non-upgraded packages only?
When running Pip with a requirements.txt file which has fixed versions, we get the following error (or similar):
VersionConflict: (solrpy 0.9.1
(.../lib/python2.6/site-packages/solrpy-0.9.1-py2.6.egg),
Requirement.parse('solrpy==0.9.3'))
because the version conflicts. Using pip install -U -r requirements.txt fixes this, but it also forces us to download all the packages again. One of the nice things about Pip is that it will know what's installed and not re-download/install it.
Is there any way around this? I guess what I want is a "soft upgrade", where it only upgrades the packages if they conflict.
A:
Seems there is an outstanding bug for this: http://bitbucket.org/ianb/pip/issue/13/
| Using Pip, how do I force upgrade non-upgraded packages only? | When running Pip with a requirements.txt file which has fixed versions, we get the following error (or similar):
VersionConflict: (solrpy 0.9.1
(.../lib/python2.6/site-packages/solrpy-0.9.1-py2.6.egg),
Requirement.parse('solrpy==0.9.3'))
because the version conflicts. Using pip install -U -r requirements.txt fixes this, but it also forces us to download all the packages again. One of the nice things about Pip is that it will know what's installed and not re-download/install it.
Is there any way around this? I guess what I want is a "soft upgrade", where it only upgrades the packages if they conflict.
| [
"Seems there is an outstanding bug for this: http://bitbucket.org/ianb/pip/issue/13/\n"
] | [
1
] | [
"Upgrade the solrpy package separately:\npip install -U --no-deps solrpy\n\nI think you can probably omit the --no-deps parameter, but you might want to try this first, and the former second, if you have problems:\npip install -U solrpy\n\nI don't believe there is a way to just update higher versioned packaged alre... | [
-1
] | [
"pip",
"python",
"setuptools"
] | stackoverflow_0003812133_pip_python_setuptools.txt |
Q:
Are there any basic standards and practices for making human readable code?
More specifically making HTML, Java, and python more readable? Does anyone have suggestions for this programming student?
A:
Make sure your code is well structured (proper indentation, blank lines to separate sections of code, etc.) and use standard, consistent, and fully named (rather than incomprehensible abbreviated) variable names.
Others would suggest using proper comments. I would tend to disagree. If your code is well structured and variables well named, then comments would just clutter things up. The exception to the rule being when you must do something counter-intuitive to work around a bug somewhere else (I've had to resort to this in WCF and Entity Framework code in the past).
A:
Proper indention and informative comments.
A:
Use consistent casing and naming.
Use tabs (and brackets where available) to provide a visual flow.
Use comments that explain what's happening conceptually as well as technically. (e.g., //Do we have a valid user? not //Check that user_ID is not -1)
I'm sure some more seasoned developers will have more suggestions, but those are my top 3.
A:
Use indentation, comments and coding conventions( for Python check PEP8 )
A:
Try to read your code out loud (or at least in your head).
A:
Have a look at this book: Clean Code: a handbook of agile software craftsmanship. It is all about making code readable and understandable.
A:
One piece of advice is not to be lazy with names. For example, if you have a Java class which is an implementation of the Transformer interface, and it transforms String to Date, don't hesitate to name the class StringToDateTransformerImpl.
A:
Well, you can always use the "ignorant test". Show your code to someone who knows absolutely nothing about programmation. If he can see more or less what a function does, the code is probably readable.
A:
Proper indentation when writing HTML can be a lifesaver, especially when you're interacting with any sort of nested elements. Just be consistent with the indentation and be sure to update surrounding lines when you move or delete an indented element. This makes it much easier to update the page, as the level of indentation will give a clue as to where you are in the page without resorting to some sort of Ctrl+F maneuver.
It's also worth noting that if you're using CSS in conjunction with HTML, proper naming is critical! It will improve your workflow and the readability of your code.
I'm also a big fan of indentation, spacing, and comments when writing "real" (Java, Python, C, etc.) code. I lean towards (x + 1) over (x+1) because I personally think it makes a big difference in readability. I space out casts, increments, etc. and they catch my eye much more easily. Be consistent with your bracket/indentation style, and comment liberally - remember, re-writing a method name is not a comment!
| Are there any basic standards and practices for making human readable code? | More specifically making HTML, Java, and python more readable? Does anyone have suggestions for this programming student?
| [
"Make sure your code is well structured (proper indentation, blank lines to separate sections of code, etc.) and use standard, consistent, and fully named (rather than incomprehensible abbreviated) variable names.\nOthers would suggest using proper comments. I would tend to disagree. If your code is well structured... | [
5,
5,
5,
5,
3,
3,
2,
2,
1
] | [] | [] | [
"html",
"human_readable",
"java",
"python"
] | stackoverflow_0003812778_html_human_readable_java_python.txt |
Q:
Python socket programming
How can I know if a node that is being accessed using TCP socket is alive or if the connection was interrupted and other errors?
Thanks!
A:
You can't. Any intermediate nodes can drop your packets or the reply packets from the remote node.
| Python socket programming | How can I know if a node that is being accessed using TCP socket is alive or if the connection was interrupted and other errors?
Thanks!
| [
"You can't. Any intermediate nodes can drop your packets or the reply packets from the remote node.\n"
] | [
2
] | [] | [] | [
"distributed",
"python",
"sockets",
"system"
] | stackoverflow_0003813451_distributed_python_sockets_system.txt |
Q:
Proper way to create an abstraction layer in python
I have a project I'm working on (http://github.com/lusis/vogeler). One of the goals is to provide swappable persistance and messaging backends. I think I have a workable model in place but wanted to get input from the Python crowd about best practices. You can see the new implementation here:
http://github.com/lusis/vogeler/blob/master/vogeler/db/generic.py
couch2.py is my subclass of generic.
Essentially the generic class provides a common set of interfaces (createdb, usedb, create, update) which call private methods such as _create_db, _use_db and so on.
My expectation is that the database specific stuff will subclass GenericPersistence and override the private methods. Is that considered bad form? Overriding private methods in general feels kind of weird but the end result is that it works. I just want to make sure I'm not breaking some sort of unwritten contract about subclassing in Python.
A:
I think, by convention, the single underscore is a hint that the attribute is an implementation detail that may be changed in the future. Subclasses should not override or invoke underscored methods, because their presence may not be relied on.
So, I'd change the underscored methods to hooks: _update --> update_hook
and ask developers to override the *_hook methods.
| Proper way to create an abstraction layer in python | I have a project I'm working on (http://github.com/lusis/vogeler). One of the goals is to provide swappable persistance and messaging backends. I think I have a workable model in place but wanted to get input from the Python crowd about best practices. You can see the new implementation here:
http://github.com/lusis/vogeler/blob/master/vogeler/db/generic.py
couch2.py is my subclass of generic.
Essentially the generic class provides a common set of interfaces (createdb, usedb, create, update) which call private methods such as _create_db, _use_db and so on.
My expectation is that the database specific stuff will subclass GenericPersistence and override the private methods. Is that considered bad form? Overriding private methods in general feels kind of weird but the end result is that it works. I just want to make sure I'm not breaking some sort of unwritten contract about subclassing in Python.
| [
"I think, by convention, the single underscore is a hint that the attribute is an implementation detail that may be changed in the future. Subclasses should not override or invoke underscored methods, because their presence may not be relied on.\nSo, I'd change the underscored methods to hooks: _update --> update_h... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003813577_python.txt |
Q:
Interesting Python Idiom for removing the only item in a single entry list
Stumbled across this today, thought it might be worthy of discussing.
Python idiom for taking the single
item from a list
It sometimes happens in code that I
have a list, let’s call it stuff, and
I know for certain that this list
contains exactly one item. And I want
to get this item and put it in a
variable, call it thing. What’s the
best way to do this? In the past I
used to do this:
thing = stuff[0]
But I think that’s not the best idiom. I came up
with a better one:
(thing,) = stuff
Why is this one better?
Readability: It lets the reader know
that stuff has exactly one element.
Free assert: It makes Python assert
that stuff has exactly one element, so
if I was wrong in my original
assumption that stuff has exactly one
element, Python will shout at me
before this manifests itself as a
hard-to-find bug someplace else in the
program.
Hard to miss: The previous
method had a [0] at the end. Now,
that’s easy to notice in a line as
short as thing = stuff[0]. But what if
the line were something messy like
this:
thing = some_dict[my_object.get_foobar_handler()][0]
In this case, the [0] at the end is
easy to miss, because when casually
glancing the code, it might seem
connected to that function call or
dict lookup. So the reader might miss
the fact that we’re taking an item out
of a list here. This would be better
in this case:
(thing,) = some_dict[my_object.get_foobar_handler()]
General for any “collection” (props to
Ulrik for noting this): This method
works even when stuff is a set or any
other kind of collection. stuff[0]
wouldn’t work on a set because set
doesn’t support access by index
number. Have fun programming!
(http://blog.garlicsim.org/post/1198230058/python-idiom-for-taking-the-single-item-from-a-list)
In general, I'm torn on the idea. He makes a compelling argument with the free assert and increased readability (should it become a pattern). On the other hand, until/if it becomes popular, its a bit harder to read.
What does the community think?
A:
The blog poster wants a single statement to function as (1) extracting an item from a list, (2) an assert, and (3) as a comment telling the user that the list has only one item.
I'm a huge fan of minimizing the number of lines of code, but I vastly prefer the following:
assert len(stuff) == 1, "stuff should have length 1 but has length %d" % len(stuff)
thing = stuff[0]
Explicit is better than implicit.
A:
I prefer:
[thing] = stuff
if only because I think (thing,) is ugly. But I like the concept in general.
A:
One is likely to miss the comma on its own, and I would rather index stuff over putting brackets, (and that comma), around thing.
I guess I am currently wired to write thing = stuff[0]
| Interesting Python Idiom for removing the only item in a single entry list | Stumbled across this today, thought it might be worthy of discussing.
Python idiom for taking the single
item from a list
It sometimes happens in code that I
have a list, let’s call it stuff, and
I know for certain that this list
contains exactly one item. And I want
to get this item and put it in a
variable, call it thing. What’s the
best way to do this? In the past I
used to do this:
thing = stuff[0]
But I think that’s not the best idiom. I came up
with a better one:
(thing,) = stuff
Why is this one better?
Readability: It lets the reader know
that stuff has exactly one element.
Free assert: It makes Python assert
that stuff has exactly one element, so
if I was wrong in my original
assumption that stuff has exactly one
element, Python will shout at me
before this manifests itself as a
hard-to-find bug someplace else in the
program.
Hard to miss: The previous
method had a [0] at the end. Now,
that’s easy to notice in a line as
short as thing = stuff[0]. But what if
the line were something messy like
this:
thing = some_dict[my_object.get_foobar_handler()][0]
In this case, the [0] at the end is
easy to miss, because when casually
glancing the code, it might seem
connected to that function call or
dict lookup. So the reader might miss
the fact that we’re taking an item out
of a list here. This would be better
in this case:
(thing,) = some_dict[my_object.get_foobar_handler()]
General for any “collection” (props to
Ulrik for noting this): This method
works even when stuff is a set or any
other kind of collection. stuff[0]
wouldn’t work on a set because set
doesn’t support access by index
number. Have fun programming!
(http://blog.garlicsim.org/post/1198230058/python-idiom-for-taking-the-single-item-from-a-list)
In general, I'm torn on the idea. He makes a compelling argument with the free assert and increased readability (should it become a pattern). On the other hand, until/if it becomes popular, its a bit harder to read.
What does the community think?
| [
"The blog poster wants a single statement to function as (1) extracting an item from a list, (2) an assert, and (3) as a comment telling the user that the list has only one item. \nI'm a huge fan of minimizing the number of lines of code, but I vastly prefer the following:\nassert len(stuff) == 1, \"stuff should h... | [
7,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003812858_python.txt |
Q:
how to set namespace prefixes in xml.etree
I wish to set the namespace prefix in xml.etree. I found register_namespace(prefix, url) on the Web but this threw "unknown attribute". I have also tried nsmap=NSMAP but this also fails. I'd be grateful for example syntax that shows how to add specified namespace prefixes
A:
register_namespace was only introduced in lxml 2.3 (still beta)
I believe you can provide an nsmap parameter (dictionary with prefix-uri mappings) when creating an element, but I don't think you can change it for an existing element. (there is an .nsmap property on the element, but changing that doesn't seem to work. There is also a .prefix property on the element, but that's read-only)
| how to set namespace prefixes in xml.etree | I wish to set the namespace prefix in xml.etree. I found register_namespace(prefix, url) on the Web but this threw "unknown attribute". I have also tried nsmap=NSMAP but this also fails. I'd be grateful for example syntax that shows how to add specified namespace prefixes
| [
"register_namespace was only introduced in lxml 2.3 (still beta)\nI believe you can provide an nsmap parameter (dictionary with prefix-uri mappings) when creating an element, but I don't think you can change it for an existing element. (there is an .nsmap property on the element, but changing that doesn't seem to w... | [
1
] | [] | [] | [
"python",
"xml.etree"
] | stackoverflow_0003814365_python_xml.etree.txt |
Q:
How to mock chained function calls in python?
I'm using the mock library written by Michael Foord to help with my testing on a django application.
I'd like to test that I'm setting up my query properly, but I don't think I need to actually hit the database, so I'm trying to mock out the query.
I can mock out the first part of the query just fine, but I am not getting the results I'd like when I chain additional things on.
The function:
@staticmethod
def get_policies(policy_holder, current_user):
if current_user.agency:
return Policy.objects.filter(policy_holder=policy_holder, version__agency=current_user.agency).distinct()
else:
return Policy.objects.filter(policy_holder=policy_holder)
and my test: The first assertion passes, the second one fails.
def should_get_policies_for_agent__user(self):
with mock.patch.object(policy_models.Policy, "objects") as query_mock:
user_mock = mock.Mock()
user_mock.agency = "1234"
policy_models.Policy.get_policies("policy_holder", user_mock)
self.assertEqual(query_mock.method_calls, [("filter", (), {
'policy_holder': "policy_holder",
'version__agency': user_mock.agency,
})])
self.assertTrue(query_mock.distinct.called)
I'm pretty sure the issue is that the initial query_mock is returning a new mock after the .filter() is called, but I don't know how to capture that new mock and make sure .distinct() was called on it.
Is there a better way to be testing what I am trying to get at? I'm trying to make sure that the proper query is being called.
A:
Each mock object holds onto the mock object that it returned when it is called. You can get a hold of it using your mock object's return_value property.
For your example,
self.assertTrue(query_mock.distinct.called)
distinct wasn't called on your mock, it was called on the return value of the filter method of your mock, so you can assert that distinct was called by doing this:
self.assertTrue(query_mock.filter.return_value.distinct.called)
| How to mock chained function calls in python? | I'm using the mock library written by Michael Foord to help with my testing on a django application.
I'd like to test that I'm setting up my query properly, but I don't think I need to actually hit the database, so I'm trying to mock out the query.
I can mock out the first part of the query just fine, but I am not getting the results I'd like when I chain additional things on.
The function:
@staticmethod
def get_policies(policy_holder, current_user):
if current_user.agency:
return Policy.objects.filter(policy_holder=policy_holder, version__agency=current_user.agency).distinct()
else:
return Policy.objects.filter(policy_holder=policy_holder)
and my test: The first assertion passes, the second one fails.
def should_get_policies_for_agent__user(self):
with mock.patch.object(policy_models.Policy, "objects") as query_mock:
user_mock = mock.Mock()
user_mock.agency = "1234"
policy_models.Policy.get_policies("policy_holder", user_mock)
self.assertEqual(query_mock.method_calls, [("filter", (), {
'policy_holder': "policy_holder",
'version__agency': user_mock.agency,
})])
self.assertTrue(query_mock.distinct.called)
I'm pretty sure the issue is that the initial query_mock is returning a new mock after the .filter() is called, but I don't know how to capture that new mock and make sure .distinct() was called on it.
Is there a better way to be testing what I am trying to get at? I'm trying to make sure that the proper query is being called.
| [
"Each mock object holds onto the mock object that it returned when it is called. You can get a hold of it using your mock object's return_value property.\nFor your example, \nself.assertTrue(query_mock.distinct.called)\n\ndistinct wasn't called on your mock, it was called on the return value of the filter method of... | [
24
] | [] | [] | [
"django",
"mocking",
"python"
] | stackoverflow_0003813688_django_mocking_python.txt |
Q:
I am writing a scraper that downloads all the image files from a multiple pages across the same site and saves them to a specific folder
the pages have only one variable which changes, and each page only holds one image.
(example: http://www.example.com/photos/ooo1.jpg ...http://www.example.com/photos/1745.jpg)
I'm currently building the script with python and beautfulSoup but am having a problem creating a loop with the changing variable. I just getting started with python, so thanks for the help.
A:
for i in xrange(1, 1746):
file = urllib2.urlopen("http://www.example.com/photos/%04d.jpg" % i)
...
# Write file locally
...
You don't need Beautiful soup if you already know the image urls.
| I am writing a scraper that downloads all the image files from a multiple pages across the same site and saves them to a specific folder | the pages have only one variable which changes, and each page only holds one image.
(example: http://www.example.com/photos/ooo1.jpg ...http://www.example.com/photos/1745.jpg)
I'm currently building the script with python and beautfulSoup but am having a problem creating a loop with the changing variable. I just getting started with python, so thanks for the help.
| [
"for i in xrange(1, 1746):\n file = urllib2.urlopen(\"http://www.example.com/photos/%04d.jpg\" % i)\n ...\n # Write file locally\n ...\n\nYou don't need Beautiful soup if you already know the image urls.\n"
] | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0003815016_beautifulsoup_html_python.txt |
Q:
Implementing C's enum and union in python
I'm trying to figure out some C code so that I can port it into python. The code is for reading a proprietary binary data file format. It has been straightforward thus far -- it's mainly been structs and I have been using the struct library to ask for particular ctypes from the file. However, I just came up on this bit of code and I'm at a loss for how to implement it in python. In particular, I'm not sure how to deal with the enum or the union.
#define BYTE char
#define UBYTE unsigned char
#define WORD short
#define UWORD unsigned short
typedef enum {
TEEG_EVENT_TAB1=1,
TEEG_EVENT_TAB2=2
} TEEG_TYPE;
typedef struct
{
TEEG_TYPE Teeg;
long Size;
union
{
void *Ptr; // Memory pointer
long Offset
};
} TEEG;
Secondly, in the below struct definition, I'm not sure what the colons after the variable names mean, (e.g., KeyPad:4). Does it mean I'm supposed to read 4 bytes?
typedef struct
{
UWORD StimType;
UBYTE KeyBoard;
UBYTE KeyPad:4;
UBYTE Accept:4;
long Offset;
} EVENT1;
In case it's useful, an abstract example of the way I've been accessing the file in python is as follows:
from struct import unpack, calcsize
def get(ctype, size=1):
"""Reads and unpacks binary data into the desired ctype."""
if size == 1:
size = ''
else:
size = str(size)
chunk = file.read(calcsize(size + ctype))
return unpack(size + ctype, chunk)[0]
file = open("file.bin", "rb")
file.seek(1234)
var1 = get('i')
var2 = get('4l')
var3 = get('10s')
A:
Enums: There are no enums in the language. Various idioms have been proposed, but none is really widespread. The most straightforward (and in this case sufficient) solution is
TEEG_EVENT_TAB1 = 1
TEEG_EVENT_TAB2 = 2
Unions: ctypes has unions.
The fieldname : n syntax is called a bitfield and, yeah, does mean "this is n bits big". Again, ctypes has them.
A:
I don't know the answer to all of your question, but for enums that you do not need a lookup-by-value on, (is, just using it to avoid magic numbers), I like to use a small class. A regular dict is another option that works fine. If you need lookup-by-value, you may want another structure though.
class TeegType(object):
TEEG_EVENT_TAB1 = 1
TEEG_EVENT_TAB2 = 2
print TeegType.TEEG_EVENT_TAB1
A:
What you really need to know is:
What is the size of an enum?. You will use this answer to generate your unpacking code.
What is the size of a union?. Summary: the size of the largest member.
How do you deal with that pointer? You should take a look at the ctypes module. For what you are doing, it may be easier to work with than the struct module. In particular, it can work with pointers arriving via C.
How do you coerce/cast the data read from the struct into the right type to work with in python? This is why I recommended ctypes in the bullet above; this module has functions for performing the necessary casts.
A:
The C enum declaration is a syntactic wrapper around some integer type. See Is the sizeof(enum) == sizeof(int), always?. How big an int is will depend on the particular C compiler. I would probably start by trying 16 bits.
The union reserves a block of memory the size of the largest of the contained data types. Again, the exact size will depend on the C implementation, but I would expect 32 bits for a 32-bit architecture, or 64-bits if this is compiled as native 64-bit code. Generally speaking, you will be able to store the contents of the union in a Python integer or long, regardless of whether what has been saved in it is a pointer or an offset.
A more interesting question is why a pointer would ever be written to a disk file. You may find that the union field is only treated as a pointer when the TEEG struct is in memory, but when written to disk, it is always an integer offset.
As for the :4 notation, as several people have noted, these are "bit fields," meaning a sequence of bits, several of which can be packed into a single space. If I recall correctly, bitfields in C are packed into ints, so both of these 4-bit fields will be packed into a single integer. They can be unpacked with appropriate use of Python's "&" (bitwise and) and ">>" (right shift) operators. Again, exactly how the fields have been packed into the integer, and the size of the integer field itself, will depend on the particular C implementation.
Maybe the following code snippet will help you:
SIZEOF_TEEG_TYPE = 2 # First guess for enum is two bytes
FMT_TEEG_TYPE = "h" # Could be "b", "B", "h", "H", "l", "L", "q" or "Q"
SIZEOF_LONG = 4 # Use 8 in 64-bit Unix architectures
FMT_LONG = "l" # Use "q" in 64-bit Unix architectures
# Life gets more interesting if you are reading 64-bit
# using 32-bit Python
SIZEOF_PTR_LONG_UNION = 4 # Use 8 in any 64-bit architecture
FMT_PTR_LONG_UNION = "l" # Use "q" in any 64-bit architecture
# Life gets more interesting if you are reading 64-bit
# using 32-bit Python
SIZEOF_TEEG_STRUCT = SIZEOF_TEEG_TYPE + SIZEOF_LONG + SIZEOF_PTR_LONG_UNION
FMT_TEEG_STRUCT = FMT_TEEG_TYPE + FMT_LONG + FMT_PTR_LONG_UNION
# Constants for TEEG_EVENTs
TEEG_EVENT_TAB1 = 1
TEEG_EVENT_TAB2 = 2
.
.
.
# Read a TEEG structure
teeg_raw = file_handle.read( SIZEOF_TEEG_STRUCT )
teeg_type, teeg_size, teeg_offset = struct.unpack( FMT_TEEG_STRUCT, teeg_raw )
.
.
.
# Use TEEG_TYPE information
if teeg_type == TEEG_EVENT_TAB1:
Do something useful
elif teeg_type == TEEG_EVENT_TAB2:
Do something else useful
else:
raise ValueError( "Encountered illegal TEEG_EVENT type %d" % teeg_type )
| Implementing C's enum and union in python | I'm trying to figure out some C code so that I can port it into python. The code is for reading a proprietary binary data file format. It has been straightforward thus far -- it's mainly been structs and I have been using the struct library to ask for particular ctypes from the file. However, I just came up on this bit of code and I'm at a loss for how to implement it in python. In particular, I'm not sure how to deal with the enum or the union.
#define BYTE char
#define UBYTE unsigned char
#define WORD short
#define UWORD unsigned short
typedef enum {
TEEG_EVENT_TAB1=1,
TEEG_EVENT_TAB2=2
} TEEG_TYPE;
typedef struct
{
TEEG_TYPE Teeg;
long Size;
union
{
void *Ptr; // Memory pointer
long Offset
};
} TEEG;
Secondly, in the below struct definition, I'm not sure what the colons after the variable names mean, (e.g., KeyPad:4). Does it mean I'm supposed to read 4 bytes?
typedef struct
{
UWORD StimType;
UBYTE KeyBoard;
UBYTE KeyPad:4;
UBYTE Accept:4;
long Offset;
} EVENT1;
In case it's useful, an abstract example of the way I've been accessing the file in python is as follows:
from struct import unpack, calcsize
def get(ctype, size=1):
"""Reads and unpacks binary data into the desired ctype."""
if size == 1:
size = ''
else:
size = str(size)
chunk = file.read(calcsize(size + ctype))
return unpack(size + ctype, chunk)[0]
file = open("file.bin", "rb")
file.seek(1234)
var1 = get('i')
var2 = get('4l')
var3 = get('10s')
| [
"Enums: There are no enums in the language. Various idioms have been proposed, but none is really widespread. The most straightforward (and in this case sufficient) solution is\nTEEG_EVENT_TAB1 = 1\nTEEG_EVENT_TAB2 = 2\n\nUnions: ctypes has unions.\nThe fieldname : n syntax is called a bitfield and, yeah, does mean... | [
8,
2,
0,
0
] | [] | [] | [
"c",
"python",
"struct",
"unions"
] | stackoverflow_0003814952_c_python_struct_unions.txt |
Q:
Ways to Move up and Down the dir structure in Python
#Moving up/down dir structure
print os.listdir('.')
print os.listdir('..')
print os.listdir('../..')
Any othe ways??? I got saving dirs before going deeper, then reassigning later.
A:
This should do the trick:
for root, dirs, files in os.walk(os.getcwd()):
for name in dirs:
try:
os.rmdir(os.path.join(root, name))
except WindowsError:
print 'Skipping', os.path.join(root, name)
This will walk the file system beginning in the directory the script is run from. It deletes the empty directories at each level.
A:
Of course there are -
thre are both os.walk - which returns tuples with the subdirectories, and the files tehrein as
os.path.walk, which takes a callback function to be called for each file in a directory structure.
You can check the online help for both functions.
A:
You can use os.chdir()
http://docs.python.org/library/os.html#os-file-dir
Am I missing something in the question?
A:
"and what if you wanted to move all the files up to the root directory?"
You could do something like:
for root, dirs, files in os.walk(os.getcwd()):
for f in files:
try:
shutil.move(os.path.join(root, f), os.getcwd())
except:
print f, 'already exists in', os.getcwd()
| Ways to Move up and Down the dir structure in Python | #Moving up/down dir structure
print os.listdir('.')
print os.listdir('..')
print os.listdir('../..')
Any othe ways??? I got saving dirs before going deeper, then reassigning later.
| [
"This should do the trick:\nfor root, dirs, files in os.walk(os.getcwd()):\n for name in dirs:\n try:\n os.rmdir(os.path.join(root, name))\n except WindowsError:\n print 'Skipping', os.path.join(root, name)\n\nThis will walk the file system beginning in the directory the scrip... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003806562_python.txt |
Q:
Running Python Scripts From MS Office
I have installed PythonWin installed..
I can read and write to Excel from Python, not a problem. Not the usage I need.
All examples I have found are more complex than I need. Since, I'm moving away
from Excel, I need a half steps for testing.
Whats the simplest way to fire off python scripts from Excel. I dont need gui.
Usage: On open of xls excute python script. Nothing fancy.
Right now, I simply execute the scripts manually before opening xls.
Private Sub Workbook_Open()
MyPythonScript.pyw ' this is where scripts should go. just one is all I need.
End Sub
A:
You can use Excel's Shell function*, e.g.
Sub RunExternalProg()
Dim return_value As Double
return_value = Shell("C:\Python26\pythonw.exe C:\my_script.py", vbHide)
Debug.Print return_value
End Sub
You may need to change the path to the pythonw executable; depending on your setup.
*Shell runs an executable program and returns a Variant (Double)
representing the program's task ID if successful, otherwise it returns zero.
| Running Python Scripts From MS Office | I have installed PythonWin installed..
I can read and write to Excel from Python, not a problem. Not the usage I need.
All examples I have found are more complex than I need. Since, I'm moving away
from Excel, I need a half steps for testing.
Whats the simplest way to fire off python scripts from Excel. I dont need gui.
Usage: On open of xls excute python script. Nothing fancy.
Right now, I simply execute the scripts manually before opening xls.
Private Sub Workbook_Open()
MyPythonScript.pyw ' this is where scripts should go. just one is all I need.
End Sub
| [
"You can use Excel's Shell function*, e.g.\nSub RunExternalProg()\n\n Dim return_value As Double\n return_value = Shell(\"C:\\Python26\\pythonw.exe C:\\my_script.py\", vbHide)\n Debug.Print return_value\n\nEnd Sub\n\nYou may need to change the path to the pythonw executable; depending on your setup.\n\n*Sh... | [
4
] | [] | [] | [
"excel",
"python",
"pywin32",
"vba"
] | stackoverflow_0003815340_excel_python_pywin32_vba.txt |
Q:
Python - How do I differentiate between two list elements that point to the same object?
I have a Ring structure implemented as follows (based on a cookbook recipe I found):
class Ring(list):
def turn(self):
last = self.pop(0)
self.append(last)
def setTop(self, objectReference):
if objectReference not in self:
raise ValueError, "object is not in ring"
while self[0] is not objectReference:
self.turn()
Say I do the following:
x = Ring([1,2,3,4,4])
x.setTop(4)
My code will always set the first 4 (currently x[3]) to x[0]. It seems (via object identity and hash id testing between x[3] and x[4]) that Python is reusing the 4 object.
How do I tell Python that I really want the second 4 (currently x[4]) to be at the top?
Apologies for the basic question ... one of the downfalls of being a self-taught beginner.
Thanks,
Mike
===EDIT===
For what it's worth, I dropped the setTop method from the class. I had added it to the standard recipe thinking "hey, this would be neat and might be useful." As the answers (esp. "what's the difference", which is spot on) and my own experience using the structure show, it's a crappy method that doesn't support any of my use cases.
In other words, adding something because I could instead of fulfilling a need = fail.
A:
From Learning Python, 4th edition -- Chapter 6:
At least conceptually, each time you generate a new value in your script by running an
expression, Python creates a new object (i.e., a chunk of memory) to represent that
value. Internally, as an optimization, Python caches and reuses certain kinds of un-
changeable objects, such as small integers and strings (each 0 is not really a new piece
of memory—more on this caching behavior later). But, from a logical perspective, it
works as though each expression’s result value is a distinct object and each object is a
distinct piece of memory.
The question is..
if x[3] is x[4]:
print "What's the difference?"
A:
If you know you want the second, then do
x = Ring([1,2,3,4,4])
x.setTop(4)
x.turn()
x.setTop(4)
You can enhance setTop() to take an additional parameter and do it inside.
A:
Cpython has an "integer cache" for smallish integers, so that values from -5 up to 255 (may vary by version or Python implentation) reuse the same object for a given value. That is, all 4s are the same int object with a value of 4. This is done to reduce the necessity for object creation.
There are a few ways to work around this.
You can use long integers (e.g., write 4L instead of 4). Python does not use the cache for long integers. (You could also use floats, as these are likewise not cached.) If you do a lot of math with the numbers, however, this could incur some performance penalty.
You can wrap each item in a list or tuple (reasonably convenient because there is simple syntax for this, though it's more syntax than long integers or floats).
You can create your own object to wrap the integer. The object would have all the same methods as an integer (so it works like an integer in math, comparisons, printing, etc.) but each instance would be unique.
I personally like using long ints in this case. You can easily convert the integers to longs in the constructor, and in any method that adds an item.
A:
It sounds like you always want to turn at least once, right? If so, re-write your setTop method like so:
def setTop(self, objectReference):
if objectReference not in self:
raise ValueError, "object is not in ring"
self.turn()
while self[0] is not objectReference:
self.turn()
Then it cycles between the expected states:
>>> x = Ring([1,2,3,4,4])
>>> x
[1, 2, 3, 4, 4]
>>> x.setTop(4)
>>> x
[4, 4, 1, 2, 3]
>>> x.setTop(4)
>>> x
[4, 1, 2, 3, 4]
>>> x.setTop(4)
>>> x
[4, 4, 1, 2, 3]
A:
I also don't know enough to be sure, but I guess numbers, even though beeing objects, are the same objects when used in different points of your code.
Why do I think so? Look:
>>> type(2)
<type 'int'>
>>> type(lambda x:x)
<type 'function'>
>>> 2 is 2
True
>>> (lambda x: x) is (lambda x: x)
False
2 objects are not identical when created twice. But numbers are not created by you, they are already there. And it makes no sense to give one 4 a different object from another 4. At least I don't see one.
A:
For small numbers, python will have a cache of objects premade to avoid the costs of making new objects. They will have the same object identity. Java does this as well. You need a way to make it avoid doing this.
A:
Python reuses small integers and short strings. As far as I know, there's no way around this - you'll have to get along with this and the fact that setTop only rotates until the first match. I suppose you could add an optinal parameter, n = 1, and turn until the n th match. But that's kinda beside the point, isn't it?
Unrelatedly, consider this:
>>> class Point(object):
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __eq__(self, other):
... return (self.x == other.x and self.y == other.y)
...
>>> a_ring = Ring(Point(1, 2), Point(15, -9), Point(0, 0))
>>> a_ring.seTop(Point(15, -9))
Traceback ...
...
ValueError: object not in ring
Not how it is supposed to work, is it? You should use while self[0] != objectReference (which is btw a misleading name) to avoid this.
| Python - How do I differentiate between two list elements that point to the same object? | I have a Ring structure implemented as follows (based on a cookbook recipe I found):
class Ring(list):
def turn(self):
last = self.pop(0)
self.append(last)
def setTop(self, objectReference):
if objectReference not in self:
raise ValueError, "object is not in ring"
while self[0] is not objectReference:
self.turn()
Say I do the following:
x = Ring([1,2,3,4,4])
x.setTop(4)
My code will always set the first 4 (currently x[3]) to x[0]. It seems (via object identity and hash id testing between x[3] and x[4]) that Python is reusing the 4 object.
How do I tell Python that I really want the second 4 (currently x[4]) to be at the top?
Apologies for the basic question ... one of the downfalls of being a self-taught beginner.
Thanks,
Mike
===EDIT===
For what it's worth, I dropped the setTop method from the class. I had added it to the standard recipe thinking "hey, this would be neat and might be useful." As the answers (esp. "what's the difference", which is spot on) and my own experience using the structure show, it's a crappy method that doesn't support any of my use cases.
In other words, adding something because I could instead of fulfilling a need = fail.
| [
"From Learning Python, 4th edition -- Chapter 6:\n\nAt least conceptually, each time you generate a new value in your script by running an\n expression, Python creates a new object (i.e., a chunk of memory) to represent that\n value. Internally, as an optimization, Python caches and reuses certain kinds of un-\n ... | [
4,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003814843_python.txt |
Q:
Quick counting with linked Django Models
I've got a stack of Models something like this (I'm typing it out in relative shorthand):
class User:
pass
class ItemList:
pass
# A User can have more than one ItemList
# An ItemList can have more than one User
# Classic M2M
class ItemListOwnership:
user = fk(User)
itemlist = fk(ItemList)
# An ItemList has multiple Items
class Item:
itemlist = fk(ItemList)
What I want to do is display a simple count of how many items a given user (or existing queryset of users) have on their various lists. I need to count across the M2M divide.
That's where I'm stuck. I'm happy with a pure SQL method if that's the only thing that works but I really don't want to get into a situation where I'm issuing n + 1 queries per user (where n is the number of lists a user has) just for a count...
Edit: I'm not using a "real" models.ManyToMany(..) relationship because I define additional things in ItemListOwnership that describe the relationship slightly better. If it's a killer, I can probably move this metadata elsewhere and get rid of ItemListOwnership and stick a m2m in ItemList
A:
Firstly, defining extra fields in a linking table is what the through functionality of ManyToManyField is for. So, keep your ItemListOwnership table with its FKs, but add a userlist=ManyToMany('User', through='ItemListOwnership') to UserList.
Once you've done this, you can easily count the number of items for each user by using annotate:
from django.db.models import Count
User.objects.all().annotate(item_count=Count('userlist__item'))
Now each user has an item_count attribute which is the number of items they have.
| Quick counting with linked Django Models | I've got a stack of Models something like this (I'm typing it out in relative shorthand):
class User:
pass
class ItemList:
pass
# A User can have more than one ItemList
# An ItemList can have more than one User
# Classic M2M
class ItemListOwnership:
user = fk(User)
itemlist = fk(ItemList)
# An ItemList has multiple Items
class Item:
itemlist = fk(ItemList)
What I want to do is display a simple count of how many items a given user (or existing queryset of users) have on their various lists. I need to count across the M2M divide.
That's where I'm stuck. I'm happy with a pure SQL method if that's the only thing that works but I really don't want to get into a situation where I'm issuing n + 1 queries per user (where n is the number of lists a user has) just for a count...
Edit: I'm not using a "real" models.ManyToMany(..) relationship because I define additional things in ItemListOwnership that describe the relationship slightly better. If it's a killer, I can probably move this metadata elsewhere and get rid of ItemListOwnership and stick a m2m in ItemList
| [
"Firstly, defining extra fields in a linking table is what the through functionality of ManyToManyField is for. So, keep your ItemListOwnership table with its FKs, but add a userlist=ManyToMany('User', through='ItemListOwnership') to UserList.\nOnce you've done this, you can easily count the number of items for eac... | [
3
] | [] | [] | [
"django",
"django_models",
"python",
"sql"
] | stackoverflow_0003815395_django_django_models_python_sql.txt |
Q:
How to write a script (for Windows XP) to run a python program?
Basically, I'd like to run a script (versus typing python program.py) or even have a shortcut that I could click on and start the program. Any ideas?
A:
From python.org:
On Windows systems, there is no
notion of an “executable mode”. The
Python installer automatically
associates .py files with python.exe
so that a double-click on a Python
file will run it as a script. The
extension can also be .pyw, in that
case, the console window that normally
appears is suppressed.
Also from python.org:
On Windows 2000, the standard Python
installer already associates the .py
extension with a file type
(Python.File) and gives that file type
an open command that runs the
interpreter (D:\Program
Files\Python\python.exe "%1" %*). This
is enough to make scripts executable
from the command prompt as ‘foo.py’.
If you’d rather be able to execute the
script by simple typing ‘foo’ with no
extension you need to add .py to the
PATHEXT environment variable.
A:
Try using a batch file (.bat).
Type in whatever commands you want to execute in the proper order, in notepad, such as:
python program.py
Save the file as iHateTyping.bat
Open the command prompt using Run.
Go to the directory where you saved the file using cd.
Type in:
iHateTyping.bat
& you're done.
I encourage you to read more about batch files in the link highlighted above.
A:
Press Ctrl+R, then type python.py to run your Python script.
| How to write a script (for Windows XP) to run a python program? | Basically, I'd like to run a script (versus typing python program.py) or even have a shortcut that I could click on and start the program. Any ideas?
| [
"From python.org:\n\nOn Windows systems, there is no\n notion of an “executable mode”. The\n Python installer automatically\n associates .py files with python.exe\n so that a double-click on a Python\n file will run it as a script. The\n extension can also be .pyw, in that\n case, the console window that nor... | [
2,
1,
1
] | [
"Use py2exe to create a portable windows executable file.\n"
] | [
-1
] | [
"python",
"windows_xp"
] | stackoverflow_0003815746_python_windows_xp.txt |
Q:
Python how to exit main function
Possible Duplicates:
Terminating a Python script
Terminating a Python Program
My question is how to exit out in Python main function? I have tried 'return' but it gave the error SyntaxError: 'return' outside function. Can anyone help? Thanks.
if __name__ == '__main__':
try:
if condition:
(I want to exit here)
do something
finally:
do something
A:
You can use sys.exit() to exit from the middle of the main function.
However, I would recommend not doing any logic there. Instead, put everything in a function, and call that from __main__ - then you can use return as normal.
A:
You can't return because you're not in a function. You can exit though.
import sys
sys.exit(0)
0 (the default) means success, non-zero means failure.
A:
If you don't feel like importing anything, you can try:
raise SystemExit, 0
A:
use sys module
import sys
sys.exit()
A:
Call sys.exit.
| Python how to exit main function |
Possible Duplicates:
Terminating a Python script
Terminating a Python Program
My question is how to exit out in Python main function? I have tried 'return' but it gave the error SyntaxError: 'return' outside function. Can anyone help? Thanks.
if __name__ == '__main__':
try:
if condition:
(I want to exit here)
do something
finally:
do something
| [
"You can use sys.exit() to exit from the middle of the main function.\nHowever, I would recommend not doing any logic there. Instead, put everything in a function, and call that from __main__ - then you can use return as normal.\n",
"You can't return because you're not in a function. You can exit though.\nimport... | [
117,
32,
12,
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0003815860_python.txt |
Q:
Tornado Request Handler
For some reason i am unable to instantiate the set_cookie outside of the MainHandler..
This is a little code to show what im wanting to do..
Can Anyone help??
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from GenCookie import *
class MainHandler(tornado.web.RequestHandler):
def get(self):
g=GenCookie()
response = g.genCookie()
class GenCookie:
def genCookie(self):
print self.request.remote_ip
print self.cookies
print self.request.headers
expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
if ("uid" in cookies):
self.set_cookie("uid", value=cookies["uid"],expires=expires)
else:
self.set_cookie("uid", value='dfc278623ab44df2bd501e106e81d146',expires=expires)
return
Any ideas?
A:
I thought that explains itself.
set_cookie is a method of tornado.web.RequestHandler
while in your code "self.set_cookie", self refers to object of class GenCookie.
Your code can be modified to pass the necessary reference
class MainHandler(tornado.web.RequestHandler):
def get(self):
g=GenCookie(self)
response = g.genCookie()
class GenCookie:
def __init__(self, reqHandler):
self.reqHandler = reqHandler
def genCookie(self):
print self.request.remote_ip
print self.cookies
print self.request.headers
expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
if ("uid" in self.cookies):
self.reqHandler.set_cookie("uid", value=self.cookies["uid"],expires=expires)
else:
self.reqHandler.set_cookie("uid", value='dfc278623ab44df2bd501e106e81d146',expires=expires)
return
| Tornado Request Handler | For some reason i am unable to instantiate the set_cookie outside of the MainHandler..
This is a little code to show what im wanting to do..
Can Anyone help??
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from GenCookie import *
class MainHandler(tornado.web.RequestHandler):
def get(self):
g=GenCookie()
response = g.genCookie()
class GenCookie:
def genCookie(self):
print self.request.remote_ip
print self.cookies
print self.request.headers
expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
if ("uid" in cookies):
self.set_cookie("uid", value=cookies["uid"],expires=expires)
else:
self.set_cookie("uid", value='dfc278623ab44df2bd501e106e81d146',expires=expires)
return
Any ideas?
| [
"I thought that explains itself.\nset_cookie is a method of tornado.web.RequestHandler\nwhile in your code \"self.set_cookie\", self refers to object of class GenCookie.\nYour code can be modified to pass the necessary reference\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n g=GenCooki... | [
7
] | [] | [] | [
"class",
"python",
"request",
"setcookie",
"tornado"
] | stackoverflow_0003816105_class_python_request_setcookie_tornado.txt |
Q:
Is there a DB/ORM pattern for attributes?
i want to create an object with different key-value as attributes, for example:
animal
id
name
attribute
id
name
and mapping
animal_attribute
animal_id
attribute_id
so i can have a entry "duck", which has multiple attribute "flying", "swimming", etc. Each attribute type would have its own table defining some variables
attribute_flying
animal_id
height
length
..
attribute_swimming
animal_id
depth
..
is there a better way to do this? Also how would the object layout work in programming (python)?
A:
You have several alternatives.
If you have not very deep hierarchy of objects and just several attributes, then you can create one table and add columns for every attribute you need to support
Other way is to create table for each object and map each attribute to different column.
Approach you want to use is not very good due to the following issues:
Hard to check if all required attibutes are existing for the animal.
Hard to load all attributes for the animal. (actually, if you want to load several animals in one query, then you stuck)
It is hard to use different values for attributes.
It is hard to make aggregate queries.
Actually this is so called Entity-Attribute-Value antipattern, as described in SQL Antipatterns book.
To resolve this antipattern it is required to rethink how you will store your inheritance in database. There are several approaches:
table per class hierarchy
table per subclass
table per concrete class
Exact solution depends on your task, currently it is hard to decide what is the best solution. Possible you should use table per subclass. In this case you will store common attributes in one table and all specific for the animal goes to the additional table.
sqlalchemy supports all three major types of inheritance, read about inheritance configuration in the documentation and choose what is best for your needs.
| Is there a DB/ORM pattern for attributes? | i want to create an object with different key-value as attributes, for example:
animal
id
name
attribute
id
name
and mapping
animal_attribute
animal_id
attribute_id
so i can have a entry "duck", which has multiple attribute "flying", "swimming", etc. Each attribute type would have its own table defining some variables
attribute_flying
animal_id
height
length
..
attribute_swimming
animal_id
depth
..
is there a better way to do this? Also how would the object layout work in programming (python)?
| [
"You have several alternatives.\nIf you have not very deep hierarchy of objects and just several attributes, then you can create one table and add columns for every attribute you need to support\nOther way is to create table for each object and map each attribute to different column.\nApproach you want to use is no... | [
4
] | [] | [] | [
"database",
"database_design",
"python",
"sqlalchemy"
] | stackoverflow_0003816220_database_database_design_python_sqlalchemy.txt |
Q:
Numpy/Python performing terribly vs. Matlab
Novice programmer here. I'm writing a program that analyzes the relative spatial locations of points (cells). The program gets boundaries and cell type off an array with the x coordinate in column 1, y coordinate in column 2, and cell type in column 3. It then checks each cell for cell type and appropriate distance from the bounds. If it passes, it then calculates its distance from each other cell in the array and if the distance is within a specified analysis range it adds it to an output array at that distance.
My cell marking program is in wxpython so I was hoping to develop this program in python as well and eventually stick it into the GUI. Unfortunately right now python takes ~20 seconds to run the core loop on my machine while MATLAB can do ~15 loops/second. Since I'm planning on doing 1000 loops (with a randomized comparison condition) on ~30 cases times several exploratory analysis types this is not a trivial difference.
I tried running a profiler and array calls are 1/4 of the time, almost all of the rest is unspecified loop time.
Here is the python code for the main loop:
for basecell in range (0, cellnumber-1):
if firstcelltype == np.array((cellrecord[basecell,2])):
xloc=np.array((cellrecord[basecell,0]))
yloc=np.array((cellrecord[basecell,1]))
xedgedist=(xbound-xloc)
yedgedist=(ybound-yloc)
if xloc>excludedist and xedgedist>excludedist and yloc>excludedist and yedgedist>excludedist:
for comparecell in range (0, cellnumber-1):
if secondcelltype==np.array((cellrecord[comparecell,2])):
xcomploc=np.array((cellrecord[comparecell,0]))
ycomploc=np.array((cellrecord[comparecell,1]))
dist=math.sqrt((xcomploc-xloc)**2+(ycomploc-yloc)**2)
dist=round(dist)
if dist>=1 and dist<=analysisdist:
arraytarget=round(dist*analysisdist/intervalnumber)
addone=np.array((spatialraw[arraytarget-1]))
addone=addone+1
targetcell=arraytarget-1
np.put(spatialraw,[targetcell,targetcell],addone)
Here is the matlab code for the main loop:
for basecell = 1:cellnumber;
if firstcelltype==cellrecord(basecell,3);
xloc=cellrecord(basecell,1);
yloc=cellrecord(basecell,2);
xedgedist=(xbound-xloc);
yedgedist=(ybound-yloc);
if (xloc>excludedist) && (yloc>excludedist) && (xedgedist>excludedist) && (yedgedist>excludedist);
for comparecell = 1:cellnumber;
if secondcelltype==cellrecord(comparecell,3);
xcomploc=cellrecord(comparecell,1);
ycomploc=cellrecord(comparecell,2);
dist=sqrt((xcomploc-xloc)^2+(ycomploc-yloc)^2);
if (dist>=1) && (dist<=100.4999);
arraytarget=round(dist*analysisdist/intervalnumber);
spatialsum(1,arraytarget)=spatialsum(1,arraytarget)+1;
end
end
end
end
end
end
Thanks!
A:
Here are some ways to speed up your python code.
First: Don't make np arrays when you are only storing one value. You do this many times over in your code. For instance,
if firstcelltype == np.array((cellrecord[basecell,2])):
can just be
if firstcelltype == cellrecord[basecell,2]:
I'll show you why with some timeit statements:
>>> timeit.Timer('x = 111.1').timeit()
0.045882196294822819
>>> t=timeit.Timer('x = np.array(111.1)','import numpy as np').timeit()
0.55774970267830071
That's an order of magnitude in difference between those calls.
Second: The following code:
arraytarget=round(dist*analysisdist/intervalnumber)
addone=np.array((spatialraw[arraytarget-1]))
addone=addone+1
targetcell=arraytarget-1
np.put(spatialraw,[targetcell,targetcell],addone)
can be replaced with
arraytarget=round(dist*analysisdist/intervalnumber)-1
spatialraw[arraytarget] += 1
Third: You can get rid of the sqrt as Philip mentioned by squaring analysisdist beforehand. However, since you use analysisdist to get arraytarget, you might want to create a separate variable, analysisdist2 that is the square of analysisdist and use that for your comparison.
Fourth: You are looking for cells that match secondcelltype every time you get to that point rather than finding those one time and using the list over and over again. You could define an array:
comparecells = np.where(cellrecord[:,2]==secondcelltype)[0]
and then replace
for comparecell in range (0, cellnumber-1):
if secondcelltype==np.array((cellrecord[comparecell,2])):
with
for comparecell in comparecells:
Fifth: Use psyco. It is a JIT compiler. Matlab has a built-in JIT compiler if you're using a somewhat recent version. This should speed-up your code a bit.
Sixth: If the code still isn't fast enough after all previous steps, then you should try vectorizing your code. It shouldn't be too difficult. Basically, the more stuff you can have in numpy arrays the better. Here's my try at vectorizing:
basecells = np.where(cellrecord[:,2]==firstcelltype)[0]
xlocs = cellrecord[basecells, 0]
ylocs = cellrecord[basecells, 1]
xedgedists = xbound - xloc
yedgedists = ybound - yloc
whichcells = np.where((xlocs>excludedist) & (xedgedists>excludedist) & (ylocs>excludedist) & (yedgedists>excludedist))[0]
selectedcells = basecells[whichcells]
comparecells = np.where(cellrecord[:,2]==secondcelltype)[0]
xcomplocs = cellrecords[comparecells,0]
ycomplocs = cellrecords[comparecells,1]
analysisdist2 = analysisdist**2
for basecell in selectedcells:
dists = np.round((xcomplocs-xlocs[basecell])**2 + (ycomplocs-ylocs[basecell])**2)
whichcells = np.where((dists >= 1) & (dists <= analysisdist2))[0]
arraytargets = np.round(dists[whichcells]*analysisdist/intervalnumber) - 1
for target in arraytargets:
spatialraw[target] += 1
You can probably take out that inner for loop, but you have to be careful because some of the elements of arraytargets could be the same. Also, I didn't actually try out all of the code, so there could be a bug or typo in there. Hopefully, it gives you a good idea of how to do this. Oh, one more thing. You make analysisdist/intervalnumber a separate variable to avoid doing that division over and over again.
A:
Not too sure about the slowness of python but you Matlab code can be HIGHLY optimized. Nested for-loops tend to have horrible performance issues. You can replace the inner loop with a vectorized function ... as below:
for basecell = 1:cellnumber;
if firstcelltype==cellrecord(basecell,3);
xloc=cellrecord(basecell,1);
yloc=cellrecord(basecell,2);
xedgedist=(xbound-xloc);
yedgedist=(ybound-yloc);
if (xloc>excludedist) && (yloc>excludedist) && (xedgedist>excludedist) && (yedgedist>excludedist);
% for comparecell = 1:cellnumber;
% if secondcelltype==cellrecord(comparecell,3);
% xcomploc=cellrecord(comparecell,1);
% ycomploc=cellrecord(comparecell,2);
% dist=sqrt((xcomploc-xloc)^2+(ycomploc-yloc)^2);
% if (dist>=1) && (dist<=100.4999);
% arraytarget=round(dist*analysisdist/intervalnumber);
% spatialsum(1,arraytarget)=spatialsum(1,arraytarget)+1;
% end
% end
% end
%replace with:
secondcelltype_mask = secondcelltype == cellrecord(:,3);
xcomploc_vec = cellrecord(secondcelltype_mask ,1);
ycomploc_vec = cellrecord(secondcelltype_mask ,2);
dist_vec = sqrt((xcomploc_vec-xloc)^2+(ycomploc_vec-yloc)^2);
dist_mask = dist>=1 & dist<=100.4999
arraytarget_vec = round(dist_vec(dist_mask)*analysisdist/intervalnumber);
count = accumarray(arraytarget_vec,1, [size(spatialsum,1),1]);
spatialsum(:,1) = spatialsum(:,1)+count;
end
end
end
There may be some small errors in there since I don't have any data to test the code with but it should get ~10X speed up on the Matlab code.
From my experience with numpy I've noticed that swapping out for-loops for vectorized/matrix-based arithmetic has noticeable speed-ups as well. However, without the shapes the shapes of all of your variables its hard to vectorize things.
A:
You can avoid some of the math.sqrt calls by replacing the lines
dist=math.sqrt((xcomploc-xloc)**2+(ycomploc-yloc)**2)
dist=round(dist)
if dist>=1 and dist<=analysisdist:
arraytarget=round(dist*analysisdist/intervalnumber)
with
dist=(xcomploc-xloc)**2+(ycomploc-yloc)**2
dist=round(dist)
if dist>=1 and dist<=analysisdist_squared:
arraytarget=round(math.sqrt(dist)*analysisdist/intervalnumber)
where you have the line
analysisdist_squared = analysis_dist * analysis_dist
outside of the main loop of your function.
Since math.sqrt is called in the innermost loop, you should have from math import sqrt at the top of the module and just call the function as sqrt.
I would also try replacing
dist=(xcomploc-xloc)**2+(ycomploc-yloc)**2
with
dist=(xcomploc-xloc)*(xcomploc-xloc)+(ycomploc-yloc)*(ycomploc-yloc)
There's a chance it will produce faster byte code to do multiplication rather than exponentiation.
I doubt these will get you all the way to MATLABs performance, but they should help reduce some overhead.
A:
If you have a multicore, you could maybe give the multiprocessing module a try and use multiple processes to make use of all the cores.
Instead of sqrt you could use x**0.5, which is, if I remember correct, slightly faster.
| Numpy/Python performing terribly vs. Matlab | Novice programmer here. I'm writing a program that analyzes the relative spatial locations of points (cells). The program gets boundaries and cell type off an array with the x coordinate in column 1, y coordinate in column 2, and cell type in column 3. It then checks each cell for cell type and appropriate distance from the bounds. If it passes, it then calculates its distance from each other cell in the array and if the distance is within a specified analysis range it adds it to an output array at that distance.
My cell marking program is in wxpython so I was hoping to develop this program in python as well and eventually stick it into the GUI. Unfortunately right now python takes ~20 seconds to run the core loop on my machine while MATLAB can do ~15 loops/second. Since I'm planning on doing 1000 loops (with a randomized comparison condition) on ~30 cases times several exploratory analysis types this is not a trivial difference.
I tried running a profiler and array calls are 1/4 of the time, almost all of the rest is unspecified loop time.
Here is the python code for the main loop:
for basecell in range (0, cellnumber-1):
if firstcelltype == np.array((cellrecord[basecell,2])):
xloc=np.array((cellrecord[basecell,0]))
yloc=np.array((cellrecord[basecell,1]))
xedgedist=(xbound-xloc)
yedgedist=(ybound-yloc)
if xloc>excludedist and xedgedist>excludedist and yloc>excludedist and yedgedist>excludedist:
for comparecell in range (0, cellnumber-1):
if secondcelltype==np.array((cellrecord[comparecell,2])):
xcomploc=np.array((cellrecord[comparecell,0]))
ycomploc=np.array((cellrecord[comparecell,1]))
dist=math.sqrt((xcomploc-xloc)**2+(ycomploc-yloc)**2)
dist=round(dist)
if dist>=1 and dist<=analysisdist:
arraytarget=round(dist*analysisdist/intervalnumber)
addone=np.array((spatialraw[arraytarget-1]))
addone=addone+1
targetcell=arraytarget-1
np.put(spatialraw,[targetcell,targetcell],addone)
Here is the matlab code for the main loop:
for basecell = 1:cellnumber;
if firstcelltype==cellrecord(basecell,3);
xloc=cellrecord(basecell,1);
yloc=cellrecord(basecell,2);
xedgedist=(xbound-xloc);
yedgedist=(ybound-yloc);
if (xloc>excludedist) && (yloc>excludedist) && (xedgedist>excludedist) && (yedgedist>excludedist);
for comparecell = 1:cellnumber;
if secondcelltype==cellrecord(comparecell,3);
xcomploc=cellrecord(comparecell,1);
ycomploc=cellrecord(comparecell,2);
dist=sqrt((xcomploc-xloc)^2+(ycomploc-yloc)^2);
if (dist>=1) && (dist<=100.4999);
arraytarget=round(dist*analysisdist/intervalnumber);
spatialsum(1,arraytarget)=spatialsum(1,arraytarget)+1;
end
end
end
end
end
end
Thanks!
| [
"Here are some ways to speed up your python code.\nFirst: Don't make np arrays when you are only storing one value. You do this many times over in your code. For instance,\nif firstcelltype == np.array((cellrecord[basecell,2])):\n\ncan just be\n if firstcelltype == cellrecord[basecell,2]:\n\nI'll show you why with ... | [
27,
2,
0,
0
] | [] | [] | [
"matlab",
"numpy",
"python"
] | stackoverflow_0003815357_matlab_numpy_python.txt |
Q:
Validate a name in Python
For an internationalised project, I have to validate the global syntax for a name (first, last) with Python. But the lack of unicode classes support is really maling things harder.
Is there any regex / library to do that ?
Examples:
Björn, Anne-Charlotte, توماس, 毛, or מיק must be accepted.
-Björn, Anne--Charlotte, Tom_ or entries like that should be rejected.
Is there any simple way to do that ?
Thanks.
A:
Python does support unicode in regular expressions if you specify the re.UNICODE flag. You can probably use something like this:
r'^[^\W_]+(-[^\W_]+)?$'
Test code:
# -*- coding: utf-8 -*-
import re
names = [
u'Björn',
u'Anne-Charlotte',
u'توماس',
u'毛',
u'מיק',
u'-Björn',
u'Anne--Charlotte',
u'Tom_',
]
for name in names:
regex = re.compile(r'^[^\W_]+(-[^\W_]+)?$', re.U)
print u'{0:20} {1}'.format(name, regex.match(name) is not None)
Result:
Björn True
Anne-Charlotte True
توماس True
毛 True
מיק True
-Björn False
Anne--Charlotte False
Tom_ False
If you also want to disallow digits in names then change [^\W_] to [^\W\d_] in both places.
| Validate a name in Python | For an internationalised project, I have to validate the global syntax for a name (first, last) with Python. But the lack of unicode classes support is really maling things harder.
Is there any regex / library to do that ?
Examples:
Björn, Anne-Charlotte, توماس, 毛, or מיק must be accepted.
-Björn, Anne--Charlotte, Tom_ or entries like that should be rejected.
Is there any simple way to do that ?
Thanks.
| [
"Python does support unicode in regular expressions if you specify the re.UNICODE flag. You can probably use something like this:\nr'^[^\\W_]+(-[^\\W_]+)?$'\n\nTest code:\n# -*- coding: utf-8 -*-\nimport re\n\nnames = [\n u'Björn',\n u'Anne-Charlotte',\n u'توماس',\n u'毛',... | [
13
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003816332_python_regex.txt |
Q:
Is there a pure Python Lucene?
The ruby folks have Ferret. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.
A:
Whoosh is a new project which is similar to lucene, but is pure python.
A:
The only one pure-python (not involving even C extension) search solution I know of is Nucular. It's slow (much slower than PyLucene) and unstable yet.
We moved from PyLucene-based home baked search and indexing to Solr but YMMV.
A:
I recently found pyndexter. It provides abstract interface to various different backend full-text search engines/indexers. And it ships with a default pure-python implementation.
These things can be disastrously slow though in Python.
A:
For some applications pure Python is overrated. Take a look at Xapian.
A:
lupy was a lucene port to pure python.The lupy people suggest that you use PyLucene. Sorry. Maybe you can use the Java sources in combination with Jython.
A:
+1 to the Xapian and Pyndexter answers.
Ferret is actually written in C with Ruby bindings on top. A pure Ruby search engine would be even slower than a pure Python one. I would love to see "someone else" write a Cython/Pyrex layer for Python interface to Ferret, but won't do it myself because why bother when there are Python bindings for Xapian.
A:
For non-pure Python, Sphinx Search with Python API works the fastest. From the benchmarks from multiple blogs, Sphinx Search is way faster than Lucene, uses way less memory and it is in C.
I am developing a multi-document search engine based on it, using python and web2py as framework.
A:
After weeks of searching for this, I found a nice Python solution: repoze.catalog. It's not strictly Python-only because it uses ZODB for storage, but it seems a better dependency to me than something like SOLR.
| Is there a pure Python Lucene? | The ruby folks have Ferret. Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.
| [
"Whoosh is a new project which is similar to lucene, but is pure python.\n",
"The only one pure-python (not involving even C extension) search solution I know of is Nucular. It's slow (much slower than PyLucene) and unstable yet.\nWe moved from PyLucene-based home baked search and indexing to Solr but YMMV.\n",
... | [
44,
6,
4,
3,
2,
2,
2,
1
] | [] | [] | [
"ferret",
"full_text_search",
"lucene",
"python"
] | stackoverflow_0000438315_ferret_full_text_search_lucene_python.txt |
Q:
how can I upload a kml file with a script to google maps?
I have a python script, that generates kml files. Now I want to upload this kml file within the script (not per hand) to the "my maps" section of google maps. Does anybody have a python or other script/code to do so?
A:
Summary: You can't until issue 2590 is fixed, which may be a while because Google have closed this issue as WontFix. There are workarounds you can try to achieve the same end result, but as it stands you cannot simply upload a KML file using the Google Maps Data API.
Long version:
I don't didn't have any Python code to do this, but the Google Maps Data API allows you to do this with a series of HTTP requests. See Uploading KML in the HTTP Protocol section of the Developers Guide for the documentation on how to do this. So one possible Python solution would be to use something like httplib in the standard library to do the appropriate HTTP requests for you.
After various edits and your feedback in the comments, here is a script that takes a Google username and password via the command line (be careful how you use it!) to obtain the authorization_token variable by making a ClientLogin authentication request. With a valid username and password, the auth token can be used in the Authorization header for POSTing the KML data to the Maps Data API.
#!/usr/bin/env python
import httplib
import optparse
import sys
import urllib
class GoogleMaps(object):
source = "daybarr.com-kmluploader-0.1"
def __init__(self, email, passwd):
self.email = email
self.passwd = passwd
self._conn = None
self._auth_token = None
def _get_connection(self):
if not self._auth_token:
conn = httplib.HTTPSConnection("www.google.com")
params = urllib.urlencode({
"accountType": "HOSTED_OR_GOOGLE",
"Email": self.email,
"Passwd": self.passwd,
"service": "local",
"source": self.source,
})
headers = {
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain",
}
conn.request("POST", "/accounts/ClientLogin", params, headers)
response = conn.getresponse()
if response.status != 200:
raise Exception("Failed to login: %s %s" % (
response.status,
response.reason))
body = response.read()
for line in body.splitlines():
if line.startswith("Auth="):
self._auth_token = line[5:]
break
if not self._auth_token:
raise Exception("Cannot find auth token in response %s" % body)
if not self._conn:
self._conn = httplib.HTTPConnection("maps.google.com")
return self._conn
connection = property(_get_connection)
def upload(self, kml_data):
conn = self.connection
headers = {
"GData-Version": "2.0",
"Authorization": 'GoogleLogin auth=%s' % (self._auth_token,),
"Content-Type": "application/vnd.google-earth.kml+xml",
}
conn.request("POST", "/maps/feeds/maps/default/full", kml_data, headers)
response = conn.getresponse()
if response.status != 200:
raise Exception("Failed to upload kml: %s %s" % (
response.status,
response.reason))
return response.read()
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-e", "--email", help="Email address for login")
parser.add_option("-p", "--passwd", help="Password for login")
options, args = parser.parse_args()
if not (options.email and options.passwd):
parser.error("email and passwd required")
if args:
kml_file = open(args[0], "r")
else:
kml_file = sys.stdin
maps = GoogleMaps(options.email, options.passwd)
print maps.upload(kml_file.read())
Unfortunately, even when using valid login credentials to obtain a valid authorization token and using a valid KML file containing exactly the example as given in the documentation, the API responds to the KML post with a 400 Bad Request. Apparently this is a known issue (2590 reported July 22nd 2010) so please vote for and comment on that if you'd like Google to fix.
In the meantime, without that bug fixed, you could try
Create the map without uploading KML, and then upload KML features as appropriate, as suggested in comment #9 on the issue from Google, when they confirmed that the bug exists.
uploading XML or uploading CSV instead of KML if these methods support what you need to get done
fiddling with the format of your KML data. This post in the Google Group for the API suggests that this might help, but it looks complicated.
Good luck
| how can I upload a kml file with a script to google maps? | I have a python script, that generates kml files. Now I want to upload this kml file within the script (not per hand) to the "my maps" section of google maps. Does anybody have a python or other script/code to do so?
| [
"Summary: You can't until issue 2590 is fixed, which may be a while because Google have closed this issue as WontFix. There are workarounds you can try to achieve the same end result, but as it stands you cannot simply upload a KML file using the Google Maps Data API.\nLong version:\nI don't didn't have any Python ... | [
1
] | [] | [] | [
"gdata",
"gdata_python_client",
"google_maps",
"python"
] | stackoverflow_0003816541_gdata_gdata_python_client_google_maps_python.txt |
Q:
Something similar to ParallelPython for C++?
I need to do some extensive searching and string comparisons and for this I figure that a compiled program is much better than an interpreted ones especially after seeing some comparison studies. I came across ParallelPython which was beautiful. It has autodiscovery for clusters and can pretty much do all the load balancing for me as well.
My first question is, is it a good idea to just go ahead with Python on a cluster having 20 nodes or do I switch to C++? If I need to switch then is there a good alternative to ParallelPython for C++ that provides features like load balancing and autodiscovery for node?
A:
I would suggest OpenMPI. I do not know what ParallelPython does exactly, but OpenMPI is an open API for cluster computing, and I imagine it will provide the requested functionality.
A:
You can always use ParallelPython for your high level work, and call into C++ code for the "hard-core" processing, as needed.
That being said, there are options in the C++ world. The most common cluster-based technology is MPI. Some implementations provide load balancing and auto-discovery, though it's not in the core spec.
| Something similar to ParallelPython for C++? | I need to do some extensive searching and string comparisons and for this I figure that a compiled program is much better than an interpreted ones especially after seeing some comparison studies. I came across ParallelPython which was beautiful. It has autodiscovery for clusters and can pretty much do all the load balancing for me as well.
My first question is, is it a good idea to just go ahead with Python on a cluster having 20 nodes or do I switch to C++? If I need to switch then is there a good alternative to ParallelPython for C++ that provides features like load balancing and autodiscovery for node?
| [
"I would suggest OpenMPI. I do not know what ParallelPython does exactly, but OpenMPI is an open API for cluster computing, and I imagine it will provide the requested functionality.\n",
"You can always use ParallelPython for your high level work, and call into C++ code for the \"hard-core\" processing, as needed... | [
1,
1
] | [] | [] | [
"c++",
"cluster_computing",
"distributed",
"python"
] | stackoverflow_0003816680_c++_cluster_computing_distributed_python.txt |
Q:
Using lists and dictionaries to store temporary information
I will have alot of similar objects with similar parameters. Example of an object parameters would be something like :
name, boolean, number and list.
The name must be unique value among all the objects while values for boolean, number and list parameters must not.
I could store the data as list of dictionaries i guess. Like that:
list = [
{'name':'a', 'bool':true, 'number':123, 'list':[1, 2, 3]},
{'name':'b', 'bool':false, 'number':143, 'list':[1, 3, 5]},
{'name':'c', 'bool':false, 'number':123, 'list':[1, 4, 5, 18]},
]
What would be the fastest way to check if the unique name exists in the list of dictionaries, before i create another dictionary in that list? Do i have to loop through the list and check what is the value of list[i][name]? What would be fastest and least memory conserving to hold and process that information, assuming, that different similar lists might be simultanously processed in different threads/tasks and that their size could be anywhere between 100 to 100 000 dictionaries per list. Should i store those lists in database instead of memory?
I understand that perhaps i should not be thinking about optimizing (storing the info and threads) before the project is working, so please, answer the unique name lookup question first :)
Thanks,
Alan
A:
If the name is the actual (unique) identifier of each inner data, you could just use a dictionary for the outer data as well:
data = {
'a' : { 'bool':true, 'number':123, 'list':[1, 2, 3] },
'b' : { 'bool':false, 'number':143, 'list':[1, 3, 5] },
'c' : { 'bool':false, 'number':123, 'list':[1, 4, 5, 18] },
}
Then you could easily check if the key exists or not.
Btw. don't name your variables list or dict as that will overwrite the built-in objects.
A:
once you come around to using a dict instead of a list, the fastest way to perform the check that you want is:
if 'newkey' not in items:
# create a new record
since you want to be able to access these records from multiple threads, I would keep a collection of locks. BTW, this is the sort of thing that you design in the beginning as it's part of the application design and not an optimization.
class DictLock(dict):
def __init__(self):
self._lock = threading.Lock()
def __getitem__(self, key):
# lock to prevent two threads trying to create the same
# entry at the same time. Then they would get different locks and
# both think that they could access the key guarded by that lock
with self._lock:
if key not in self.iterkeys():
self[key] = threading.Lock()
return super(DictLock, self).__getitem__(key)
now if you want to modify your items, you can use the locks to keep it safe.
locks = DictLock()
with locks['a']:
# modify a.
or to insert a new element
with locks['z']:
#we are now the only ones (playing by the rules) accessing the 'z' key
items['z'] = create_new_item()
A:
Store the objects in a dictionary with the name as the key:
objects = {'a' : {'bool':true, 'number':123, 'list':[1, 2, 3]},
'b' : {'bool':false, 'number':143, 'list':[1, 3, 5]},
'c' : {'bool':false, 'number':123, 'list':[1, 4, 5, 18]}}
This way you ensure that the names are unique since all the keys in the dictionary are unique. Checking is a name is in the dictionary is also easy:
name in objects
A:
What you want is an "intrusive" dictionary - something that looks for keys inside values. Unfortunately, I don't know of any implementation in Python. Boost's multi_index comes close.
A:
If you don't want to change the data structure you have, then you can use the following. Otherwise, poke's answer is the way to go.
>>> my_list = [
... {'name':'a', 'bool':True, 'number':123, 'list':[1, 2, 3]},
... {'name':'b', 'bool':False, 'number':143, 'list':[1, 3, 5]},
... {'name':'c', 'bool':False, 'number':123, 'list':[1, 4, 5, 18]},
... ]
>>> def is_present(data, name):
... return any(name == d["name"] for d in data)
...
>>> is_present(my_list, "a")
True
>>> is_present(my_list, "b")
True
>>> is_present(my_list, "c")
True
>>> is_present(my_list, "d")
False
If you pass any an iterable, it returns True if any one of its elements are True.
(name == d["name"] for d in data) creates a generator. Each time somebody (in this case, any) requests the next element, it does so by getting the next element, d, from data and transforms it by the expression name == d["name"]. Since generators are lazy i.e. the transformation is done when the next element is requested, this should use relatively little memory (and should use the same amount of memory regardless of the size of the list).
| Using lists and dictionaries to store temporary information | I will have alot of similar objects with similar parameters. Example of an object parameters would be something like :
name, boolean, number and list.
The name must be unique value among all the objects while values for boolean, number and list parameters must not.
I could store the data as list of dictionaries i guess. Like that:
list = [
{'name':'a', 'bool':true, 'number':123, 'list':[1, 2, 3]},
{'name':'b', 'bool':false, 'number':143, 'list':[1, 3, 5]},
{'name':'c', 'bool':false, 'number':123, 'list':[1, 4, 5, 18]},
]
What would be the fastest way to check if the unique name exists in the list of dictionaries, before i create another dictionary in that list? Do i have to loop through the list and check what is the value of list[i][name]? What would be fastest and least memory conserving to hold and process that information, assuming, that different similar lists might be simultanously processed in different threads/tasks and that their size could be anywhere between 100 to 100 000 dictionaries per list. Should i store those lists in database instead of memory?
I understand that perhaps i should not be thinking about optimizing (storing the info and threads) before the project is working, so please, answer the unique name lookup question first :)
Thanks,
Alan
| [
"If the name is the actual (unique) identifier of each inner data, you could just use a dictionary for the outer data as well:\ndata = {\n 'a' : { 'bool':true, 'number':123, 'list':[1, 2, 3] },\n 'b' : { 'bool':false, 'number':143, 'list':[1, 3, 5] },\n 'c' : { 'bool':false, 'number':123, 'list':[1, 4, 5, 18] },... | [
6,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003816669_python.txt |
Q:
Python: Convert from buffer of Structure object to unsiged integer
I'm new to Python, so I was wondering how would I extract buffer to convert the whole buffer into one integer from a Structure object with the code defined below
g = 12463
h = 65342
i = 94854731
j = 9000
class Blah(Structure):
_fields_ = [
("a", ctypes.c_int32, 17),
("b", ctypes.c_int32, 19),
("c", ctypes.c_int64, 54),
("d", ctypes.c_int64, 33)]
x = Blah(g, h, i, j)
y = [an unsigned python integer from x]
Now, how do I get an integer for y when the size of Blah object's bytes buffer is natively larger than 64 bit?
A:
Instead of using a ctypes structure, use bit shift operations to assemble the integer.
y = g << 160 + h << 128 + i << 64 + j
| Python: Convert from buffer of Structure object to unsiged integer | I'm new to Python, so I was wondering how would I extract buffer to convert the whole buffer into one integer from a Structure object with the code defined below
g = 12463
h = 65342
i = 94854731
j = 9000
class Blah(Structure):
_fields_ = [
("a", ctypes.c_int32, 17),
("b", ctypes.c_int32, 19),
("c", ctypes.c_int64, 54),
("d", ctypes.c_int64, 33)]
x = Blah(g, h, i, j)
y = [an unsigned python integer from x]
Now, how do I get an integer for y when the size of Blah object's bytes buffer is natively larger than 64 bit?
| [
"Instead of using a ctypes structure, use bit shift operations to assemble the integer.\ny = g << 160 + h << 128 + i << 64 + j\n\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003817100_python.txt |
Q:
Regular expression isn't found in line: execution just hangs
I am new to python (and this site); I am trying to write a script that will use a regular expression to search through a given file to find a name. I have to print out the different ways the name was capitalized and how many times the name was found. My current code will just print out my first flag and then hang. I don't know if my for loop or my reg exp is wrong. Thanks for your time!
import re
import sys
if __name__ == '__main__':
print "flag"
for line in sys.stdin:
print(line)
name_count = re.search("[snyder]", line, re.I)
variation = set(re.search(r"([snyder])", line, re.I))
print "flag2"
print len(name_count), variation
A:
First I would say to take a look at this thread for a bit of information about reading from stdin (if that's really what you want to do).
Second, I would consider just opening the file instead of reading from sys.stdin, either using a library like fileinput or a with statement or other file handle.
Next, I would add that your regular expression probably isn't going to do what you expect it to. The expression [snyder] is a character class, which will match one repetition of any character in the class. In other words, this will match the individual letters s, n, y, d, e, or r. If you want to match the literal string snyder then you should just use that as your expression: re.search("snyder", line, re.I). Or, if you don't want substring matches (cases where snyder might appear within another string), you can try the regex \bsnyder\b.
Edit re: your comment - Two things I'll point out here:
1) While [s][n][y][d][e][r] is semantically equivalent to snyder, you might want to consider using the latter for the sake of readability. A character class of one character is equivalent to that one character alone (as long as it's properly escaped and so forth if necessary). Yours will work, so that's just a suggestion/heads-up.
2) Try using re.findall() in place of re.search(). I think you'll get what you want with something like:
variations = []
for line in fileinput.input():
found = re.findall(r"""snyder""", line, re.I)
if len(found) > 0:
variations += found
var_set = set(variations)
print var_set
print len(var_set)
An example of what this will do:
>>> print sl
['blah', 'blah', 'what', 'is', 'this', 'BLAh', 'some', 'random', 'bLah', 'text', 'a longer BlaH string', 'a BLAH string with blAH two']
>>> li = []
>>> for line in sl:
... m = re.findall("blah", line, re.I)
... if len(m) > 0:
... li += m
...
>>>
>>> print li #Contains all matches
['blah', 'blah', 'BLAh', 'bLah', 'BlaH', 'BLAH', 'blAH']
>>> st = set(li)
>>> print st #Contains only *unique* matches
set(['bLah', 'BLAH', 'BLAh', 'BlaH', 'blah', 'blAH'])
>>> print len(st)
6
>>> print len(li)
7 #1 greater than len(st) because st drops a non-unique match
A:
Its not hanging, its waiting for input on stdin! replace for line in sys.stdin by something like:
import fileinput
for line in fileinput.input("sample.txt"):
A:
While you're at it, change that to:
pattern = re.compile('(snyder)')
[...]
name_count = pattern.search(line, re.I)
so that you're not re-compiling the regexp for each line in the input file.
| Regular expression isn't found in line: execution just hangs | I am new to python (and this site); I am trying to write a script that will use a regular expression to search through a given file to find a name. I have to print out the different ways the name was capitalized and how many times the name was found. My current code will just print out my first flag and then hang. I don't know if my for loop or my reg exp is wrong. Thanks for your time!
import re
import sys
if __name__ == '__main__':
print "flag"
for line in sys.stdin:
print(line)
name_count = re.search("[snyder]", line, re.I)
variation = set(re.search(r"([snyder])", line, re.I))
print "flag2"
print len(name_count), variation
| [
"First I would say to take a look at this thread for a bit of information about reading from stdin (if that's really what you want to do).\nSecond, I would consider just opening the file instead of reading from sys.stdin, either using a library like fileinput or a with statement or other file handle.\nNext, I would... | [
4,
3,
0
] | [] | [] | [
"file_io",
"python",
"regex"
] | stackoverflow_0003816825_file_io_python_regex.txt |
Q:
Design question on Python network programming
I'm currently writing a project in Python which has a client and a server part. I have troubles with the network communication, so I need to explain some things...
The client mainly does operations the server tells him to and sends the results of the operations back to the server. I need a way to communicate bidirectional on a TCP socket.
Current Situation
I currently use a LineReceiver of the Twisted framework on the server side, and a plain Python socket (and ssl) on client side (because I was unable to correctly implement a Twisted PushProducer). There is a Queue on the client side which gets filled with data which should be sent to the server; a subprocess continuously pulls data from the queue and sends it to the server (see code below).
This scenario works well, if only the client pushes its results to the manager. There is no possibility the server can send data to the client. More accurate, there is no way for the client to receive data the server has sent.
The Problem
I need a way to send commands from the server to the client.
I thought about listening for incoming data in the client loop I use to send data from the queue:
def run(self):
while True:
data = self.queue.get()
logger.debug("Sending: %s", repr(data))
data = cPickle.dumps(data)
self.socket.write(data + "\r\n")
# Here would be a good place to listen on the socket
But there are several problems with this solution:
the SSLSocket.read() method is a blocking one
if there is no data in the queue, the client will never receive any data
Yes, I could use Queue.get_nowait() instead of Queue.get(), but all in all it's not a good solution, I think.
The Question
Is there a good way to achieve this requirements with Twisted? I really do not have that much skills on Twisted to find my way round in there. I don't even know if using the LineReceiver is a good idea for this kind of problem, because it cannot send any data, if it does not receive data from the client. There is only a lineReceived event.
Is Twisted (or more general any event driven framework) able to solve this problem? I don't even have real event on the communication side. If the server decides to send data, it should be able to send it; there should not be a need to wait for any event on the communication side, as possible.
A:
"I don't even know if using the LineReceiver is a good idea for this kind of problem, because it cannot send any data, if it does not receive data from the client. There is only a lineReceived event."
You can send data using protocol.transport.write from anywhere, not just in lineReceived.
A:
"I need a way to send commands from the server to the client."
Don't do this. It inverts the usual meaning of "client" and "server". Clients take the active role and send stuff or request stuff from the server.
Is Twisted (or more general any event driven framework) able to solve this problem?
It shouldn't. You're inverting the role of client and server.
If the server decides to send data, it should be able to send it;
False, actually.
The server is constrained to wait for clients to request data. That's generally the accepted meaning of "client" and "server".
"One to send commands to the client and one to transmit the results to the server. Does this solution sound more like a standard client-server communication for you?"
No.
If a client sent messages to a server and received responses from the server, it would meet more usual definitions.
Sometimes, this sort of thing is described as having "Agents" which are -- each -- a kind of server and a "Controller" which is a single client of all these servers.
The controller dispatches work to the agents. The agents are servers -- they listen on a port, accept work from the controller, and do work. Each Agent must do two concurrent things (usually via the select API):
Monitor a well-known socket on which it will receive work from the one-and-only client.
Do the work (in the background).
This is what Client-Server usually means.
If each Agent is a Server, you'll find lots of libraries will support this. This is the way everyone does it.
| Design question on Python network programming | I'm currently writing a project in Python which has a client and a server part. I have troubles with the network communication, so I need to explain some things...
The client mainly does operations the server tells him to and sends the results of the operations back to the server. I need a way to communicate bidirectional on a TCP socket.
Current Situation
I currently use a LineReceiver of the Twisted framework on the server side, and a plain Python socket (and ssl) on client side (because I was unable to correctly implement a Twisted PushProducer). There is a Queue on the client side which gets filled with data which should be sent to the server; a subprocess continuously pulls data from the queue and sends it to the server (see code below).
This scenario works well, if only the client pushes its results to the manager. There is no possibility the server can send data to the client. More accurate, there is no way for the client to receive data the server has sent.
The Problem
I need a way to send commands from the server to the client.
I thought about listening for incoming data in the client loop I use to send data from the queue:
def run(self):
while True:
data = self.queue.get()
logger.debug("Sending: %s", repr(data))
data = cPickle.dumps(data)
self.socket.write(data + "\r\n")
# Here would be a good place to listen on the socket
But there are several problems with this solution:
the SSLSocket.read() method is a blocking one
if there is no data in the queue, the client will never receive any data
Yes, I could use Queue.get_nowait() instead of Queue.get(), but all in all it's not a good solution, I think.
The Question
Is there a good way to achieve this requirements with Twisted? I really do not have that much skills on Twisted to find my way round in there. I don't even know if using the LineReceiver is a good idea for this kind of problem, because it cannot send any data, if it does not receive data from the client. There is only a lineReceived event.
Is Twisted (or more general any event driven framework) able to solve this problem? I don't even have real event on the communication side. If the server decides to send data, it should be able to send it; there should not be a need to wait for any event on the communication side, as possible.
| [
"\"I don't even know if using the LineReceiver is a good idea for this kind of problem, because it cannot send any data, if it does not receive data from the client. There is only a lineReceived event.\"\nYou can send data using protocol.transport.write from anywhere, not just in lineReceived.\n",
"\n\"I need a w... | [
2,
-1
] | [] | [] | [
"event_driven_design",
"network_programming",
"python",
"twisted"
] | stackoverflow_0003772719_event_driven_design_network_programming_python_twisted.txt |
Q:
Generating SHA-256 hash in Python 2.4 using M2Crypto
Is it possible to generate a SHA-256 hash using M2Crypto? Python 2.4's SHA module doesn't support 256, so I started using PyCrypto, only to find out that PyCrypto doesn't support PKCS#5 (needed elsewhere in my project.) I switched to M2Crypto as a result and now I would like to replace my PyCrypto SHA-256 call with an M2Crypto equivalent... I tried looking in the unit tests, but didn't see anything.
A:
You could download the hashlib module of Python 2.5 (supports SHA256) for usage on older Pythons (e.g. Python 2.4).
| Generating SHA-256 hash in Python 2.4 using M2Crypto | Is it possible to generate a SHA-256 hash using M2Crypto? Python 2.4's SHA module doesn't support 256, so I started using PyCrypto, only to find out that PyCrypto doesn't support PKCS#5 (needed elsewhere in my project.) I switched to M2Crypto as a result and now I would like to replace my PyCrypto SHA-256 call with an M2Crypto equivalent... I tried looking in the unit tests, but didn't see anything.
| [
"You could download the hashlib module of Python 2.5 (supports SHA256) for usage on older Pythons (e.g. Python 2.4).\n"
] | [
6
] | [] | [] | [
"cryptography",
"hash",
"m2crypto",
"python",
"sha256"
] | stackoverflow_0003817303_cryptography_hash_m2crypto_python_sha256.txt |
Q:
argparse missing in python 3
does somebody know, why the argparse module didn't make it in python 3? it's new in python 2.7, but the 2.x branch is running out with 2.7. it makes no sense to me not to support it in the actual python 3 branch.
A:
It will be in Python 3.2. It was just added in Python 2.7, which was released just this July; Python 3.2 will be the next 3.x release after that date.
A:
argparse is in Python 3, 3.2 to be specific. See also: http://www.python.org/dev/peps/pep-0389/
| argparse missing in python 3 |
does somebody know, why the argparse module didn't make it in python 3? it's new in python 2.7, but the 2.x branch is running out with 2.7. it makes no sense to me not to support it in the actual python 3 branch.
| [
"It will be in Python 3.2. It was just added in Python 2.7, which was released just this July; Python 3.2 will be the next 3.x release after that date.\n",
"argparse is in Python 3, 3.2 to be specific. See also: http://www.python.org/dev/peps/pep-0389/\n"
] | [
12,
4
] | [] | [] | [
"argparse",
"command_line",
"python",
"python_3.x"
] | stackoverflow_0003817481_argparse_command_line_python_python_3.x.txt |
Q:
How to import function handlers from other file to a Python/GTK Builder program?
I have a Python script which uses a glade file to define its UI, and has a lot of repetitive widgets, each one to adjust a different numerical attribute of a certain active object. Since it is repetitive, I decided to define all the handlers in a separate file for encapsulation and readability. Here are some code excerpts:
The main file:
import pygtk
pygtk.require('2.0')
import gtk, gobject, cairo, gtk.glade
from Handlers import Handlers
from FramesetParameters import FramesetParameters
from GeometricRules import GeometricRules
from BikeDrawing import BikeDrawing
p=FramesetParameters("fitting", "handling", "construction")
builder = gtk.Builder()
builder.add_from_file("FramesetDesignerUI.glade")
Handlers(p)
builder.connect_signals(Handlers.__dict__)
mainWindow = builder.get_object("mainWindow")
mainWindow.show_all()
gtk.main()
The Handlers.py file:
class Handlers:
def adjustbottomBracketHeight(widget):
obj.bottomBracketHeight = widget.get_value()
def adjustseatTubeAngle(widget):
obj.seatTubeAngle = widget.get_value()
def adjustseatTubeLength(widget):
obj.seatTubeLength = widget.get_value()
def adjusttopTubeLength(widget):
obj.topTubeLength = widget.get_value()
def adjustheadTubeAngle(widget):
obj.headTubeAngle = widget.get_value()
def adjustheadTubeTopHeight(widget):
obj.headTubeTopHeight = widget.get_value()
def adjustrearAxlePosition(widget):
obj.rearAxlePosition = widget.get_value()
def adjusttrail(widget):
obj.trail = widget.get_value()
def adjustseatTubeExtension(widget):
obj.seatTubeExtension = widget.get_value()
def adjustheadTubeUpperExtension(widget):
obj.headTubeUpperExtension = widget.get_value()
def adjustheadTubeLowerExtension(widget):
obj.headTubeLowerExtension = widget.get_value()
def adjustforkCrownBulk(widget):
obj.forkCrownBulk = widget.get_value()
When I run the program, the GUI shows up properly, but when I move a slider I get this error:
Traceback (most recent call last):
File "/home/helton/Dropbox/Profilez/00Computacional/00REFACTORY97/Handlers.py", line 6, in adjustseatTubeAngle
obj.seatTubeAngle = widget.get_value()
NameError: global name 'obj' is not defined
I know a little about namespaces and scope, but I am very noob on Python and Object orienting in general, so I do not know exactely what I should do. Any help would be much appreciated.
A:
the obj arguments or names are missing. perhaps you need to import something and assign it, or add it to the arguments for the handler functions? what exactly is the obj supposed to be?
A:
I think you've forgotten the self argument all over the place.
i.e. change this:
class Handlers:
def adjustbottomBracketHeight(widget):
obj.bottomBracketHeight = widget.get_value()
to
class Handlers:
def adjustbottomBracketHeight(obj, widget):
obj.bottomBracketHeight = widget.get_value()
| How to import function handlers from other file to a Python/GTK Builder program? | I have a Python script which uses a glade file to define its UI, and has a lot of repetitive widgets, each one to adjust a different numerical attribute of a certain active object. Since it is repetitive, I decided to define all the handlers in a separate file for encapsulation and readability. Here are some code excerpts:
The main file:
import pygtk
pygtk.require('2.0')
import gtk, gobject, cairo, gtk.glade
from Handlers import Handlers
from FramesetParameters import FramesetParameters
from GeometricRules import GeometricRules
from BikeDrawing import BikeDrawing
p=FramesetParameters("fitting", "handling", "construction")
builder = gtk.Builder()
builder.add_from_file("FramesetDesignerUI.glade")
Handlers(p)
builder.connect_signals(Handlers.__dict__)
mainWindow = builder.get_object("mainWindow")
mainWindow.show_all()
gtk.main()
The Handlers.py file:
class Handlers:
def adjustbottomBracketHeight(widget):
obj.bottomBracketHeight = widget.get_value()
def adjustseatTubeAngle(widget):
obj.seatTubeAngle = widget.get_value()
def adjustseatTubeLength(widget):
obj.seatTubeLength = widget.get_value()
def adjusttopTubeLength(widget):
obj.topTubeLength = widget.get_value()
def adjustheadTubeAngle(widget):
obj.headTubeAngle = widget.get_value()
def adjustheadTubeTopHeight(widget):
obj.headTubeTopHeight = widget.get_value()
def adjustrearAxlePosition(widget):
obj.rearAxlePosition = widget.get_value()
def adjusttrail(widget):
obj.trail = widget.get_value()
def adjustseatTubeExtension(widget):
obj.seatTubeExtension = widget.get_value()
def adjustheadTubeUpperExtension(widget):
obj.headTubeUpperExtension = widget.get_value()
def adjustheadTubeLowerExtension(widget):
obj.headTubeLowerExtension = widget.get_value()
def adjustforkCrownBulk(widget):
obj.forkCrownBulk = widget.get_value()
When I run the program, the GUI shows up properly, but when I move a slider I get this error:
Traceback (most recent call last):
File "/home/helton/Dropbox/Profilez/00Computacional/00REFACTORY97/Handlers.py", line 6, in adjustseatTubeAngle
obj.seatTubeAngle = widget.get_value()
NameError: global name 'obj' is not defined
I know a little about namespaces and scope, but I am very noob on Python and Object orienting in general, so I do not know exactely what I should do. Any help would be much appreciated.
| [
"the obj arguments or names are missing. perhaps you need to import something and assign it, or add it to the arguments for the handler functions? what exactly is the obj supposed to be?\n",
"I think you've forgotten the self argument all over the place.\ni.e. change this:\nclass Handlers:\n def adjustbottomBr... | [
0,
0
] | [] | [] | [
"builder",
"glade",
"pygtk",
"python"
] | stackoverflow_0003817758_builder_glade_pygtk_python.txt |
Q:
syntax for creating a dictionary into another dictionary in python
Possible Duplicate:
syntax to insert one list into another list in python
How could be the syntax for creating a dictionary into another dictionary in python
A:
You can declare a dictionary inside a dictionary by nesting the {} containers:
d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}
And then you can access the elements using the [] syntax:
print d['dict1'] # {'foo': 1, 'bar': 2}
print d['dict1']['foo'] # 1
print d['dict2']['quux'] # 4
Given the above, if you want to add another dictionary to the dictionary, it can be done like so:
d['dict3'] = {'spam': 5, 'ham': 6}
or if you prefer to add items to the internal dictionary one by one:
d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8
A:
dict1 = {}
dict1['dict2'] = {}
print dict1
>>> {'dict2': {},}
this is commonly known as nesting iterators into other iterators I think
A:
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
To re-reference the values of one dictionary into another, you can use dict.update:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']
| syntax for creating a dictionary into another dictionary in python |
Possible Duplicate:
syntax to insert one list into another list in python
How could be the syntax for creating a dictionary into another dictionary in python
| [
"You can declare a dictionary inside a dictionary by nesting the {} containers:\nd = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}\n\nAnd then you can access the elements using the [] syntax:\nprint d['dict1'] # {'foo': 1, 'bar': 2}\nprint d['dict1']['foo'] # 1\nprint d['dict2']['quux... | [
106,
9,
3
] | [] | [] | [
"python"
] | stackoverflow_0003817529_python.txt |
Q:
Join list of string in python with string %s replacement
I have a list of ints that I want to join into a string
ids = [1,2,3,4,5]
that looks like 'Id = 1 or Id = 2 or Id = 3 or Id = 4 or ID = 5'
I have an answer now but I thought it may be good to get the panel's opinion
Edit: More information to the nay sayers...
This not generating SQL directly, this is dynamic expression that is being sent to a Ado.net data services layer that uses Entity Framework underneath. The IN clause which is what is preferred is currently not supported by the dynamic expression handler/EF4 adapter in the service yet and I have to resort to multiple equals statements for the time being.
A:
" or ".join("id = %d" % id for id in ids)
A:
mystring = 'id =' + 'or id ='.join(str(i) for i in ids)
If you want to generate dynamic sql as those in the comments have pointed out (don't know how I missed it), you should be doing this as
mystring = ' or '.join(['id = ?']*len(ids))
where ? is meant to be replaced with the appropriate escape sequence for your database library. For sqlite3, that's ?. for MySQLdb, it uses the printf codes, IIRC. You can then pass the list of id's to the cursor as the second argument (usually) after the sql string and it will put them in there in a secure way. This is always the right thing.
| Join list of string in python with string %s replacement | I have a list of ints that I want to join into a string
ids = [1,2,3,4,5]
that looks like 'Id = 1 or Id = 2 or Id = 3 or Id = 4 or ID = 5'
I have an answer now but I thought it may be good to get the panel's opinion
Edit: More information to the nay sayers...
This not generating SQL directly, this is dynamic expression that is being sent to a Ado.net data services layer that uses Entity Framework underneath. The IN clause which is what is preferred is currently not supported by the dynamic expression handler/EF4 adapter in the service yet and I have to resort to multiple equals statements for the time being.
| [
"\" or \".join(\"id = %d\" % id for id in ids)\n\n",
"mystring = 'id =' + 'or id ='.join(str(i) for i in ids)\n\nIf you want to generate dynamic sql as those in the comments have pointed out (don't know how I missed it), you should be doing this as\nmystring = ' or '.join(['id = ?']*len(ids)) \n\nwhere ? is mean... | [
5,
1
] | [] | [] | [
"python",
"string_concatenation"
] | stackoverflow_0003818362_python_string_concatenation.txt |
Q:
Are there any keyboard shortcuts for formatting in Python?
After we write a code in Matlab we can use ctrl+A+ctrl+I and ctrl+A+ctrl+J to format our code (comments, loops alignment etc). Is there something similar or any helpful keyboard shortcuts in Python?
Also, just like we can use upward arrow to copy our previous command window history in Matlab, is it possible or some keyboard shortcut to do that in Python?
Thanks!
A:
Python is a programming language, not an integrated development environment (IDE), therefore it has no "keyboard shortcuts" or the like. Each given development environment may offer different facilities or the like. You appear to consider GNU Readline (typically used in the simple text-mode interpreter environment that many Python executables bundle) as "part of Python" -- but that's a misconception; readline is a perfectly general library for interactive input in command-line environments, and Python only one of the many programs using it. Another environment usually bundled with Python is IDLE, a GUI one, and of course the editing facilities are completely and drastically different. There are many third-party environments such as "Wing IDE" and each offers a drastically different set of editing features and facilities from all the others.
To summarize: your question makes no more sense about Python per se than it would about (say) C, or Java, or any other programming languages. Don't let (usually proprietary) programming languages that come with bundled IDEs confuse you on this subject!
A:
If you use emacs, then
you can press tab anywhere on a line and it will properly indent that line relative to the preceding line (making the assumption that the current block is continuing).
you can mark selections of text and press C-c < and C-c > to move blocks of text left and right.
These are the two that I actually use with any regularity. I'm sure that anything that any other editor can do, emacs can do too ;)
on the whole, formatting python code is difficult for a program to do because the indentation drastically affects semantics.
consider
for i, item in enumerate(lst):
if i % 2:
sum += i * int(item)
return sum
and
for i, item in enumerate(lst):
if i % 2:
sum += i * int(item)
return sum
Do you really want your editor deciding which one you mean?
A:
If you use the Python IDLE (comes with Python on Windows, readily available on Linux and Unix flavors), most of the formatting work is done for you. For instance, IDLE automatically indents loops and any other code block after a :. This is far better than writing Python scripts in a standard text editor like gedit, emacs, vim, or Notepad, especially since you can simply press F5 to run the script.
As for previous commands, the biggest disadvantage to the Python shell is that you cannot press the up arrow to get the last command. However, if you use the non-GUI shell (in the Windows command prompt or a Unix terminal, the command is python), you can use the shell's command recall to get the last command.
| Are there any keyboard shortcuts for formatting in Python? | After we write a code in Matlab we can use ctrl+A+ctrl+I and ctrl+A+ctrl+J to format our code (comments, loops alignment etc). Is there something similar or any helpful keyboard shortcuts in Python?
Also, just like we can use upward arrow to copy our previous command window history in Matlab, is it possible or some keyboard shortcut to do that in Python?
Thanks!
| [
"Python is a programming language, not an integrated development environment (IDE), therefore it has no \"keyboard shortcuts\" or the like. Each given development environment may offer different facilities or the like. You appear to consider GNU Readline (typically used in the simple text-mode interpreter environ... | [
7,
1,
1
] | [] | [] | [
"formatting",
"keyboard_shortcuts",
"matlab",
"python"
] | stackoverflow_0003818405_formatting_keyboard_shortcuts_matlab_python.txt |
Q:
Jobs are getting lost in ParallelPython?
I am submitting about 234 jobs (but my example contains only 50 for demonstration purpose) to my 20 node cluster using ParallelPython. I was expecting that it would queue and execute them but it seems to "lose" jobs and I am not understand where things are going wrong. When the script finishes, I am not able to see 50 files i.e. info_1, info_2 .... info_50 but rather I am seeing some random behavior. Any suggestions?
def readChecklist():
f = open('/home/username/twisted/pp-1.6.0/checklist', 'r')
checklist = [line.strip() for line in f]
return checklist
def processFile(num):
bl = readChecklist()
# pick a filename to write to
outfile = "info_" + str(num)
FILE = open(outfile, "a")
for i in range(num):
FILE.write(str(i)+"\n")
FILE.flush()
FILE.close()
return num
ppservers=("*",)
job_server = pp.Server(ppservers=ppservers)
inputs = range(50)
jobs = [(input, job_server.submit(processFile,(input,), (readCheckList,), ("os","math","time","sys","subprocess",))) for input in inputs]
for input, job in jobs:
print "Job: ", input, " is", job()
job_server.print_stats()
Output:
Job: 0 is True
Job: 1 is True
Job: 2 is True
Job: 3 is True
Job: 4 is True
Job: 5 is True
Job: 6 is True
Job: 7 is True
Job: 8 is True
Job: 9 is True
Job: 10 is True
Job: 11 is True
Job: 12 is True
Job: 13 is True
Job: 14 is True
Job: 15 is True
Job: 16 is True
Job: 17 is True
Job: 18 is True
Job: 19 is True
Job: 20 is True
Job: 21 is True
Job: 22 is True
Job: 23 is True
Job: 24 is True
Job: 25 is True
Job: 26 is True
Job: 27 is True
Job: 28 is True
Job: 29 is True
Job: 30 is True
Job: 31 is True
Job: 32 is True
Job: 33 is True
Job: 34 is True
Job: 35 is True
Job: 36 is True
Job: 37 is True
Job: 38 is True
Job: 39 is True
Job: 40 is True
Job: 41 is True
Job: 42 is True
Job: 43 is True
Job: 44 is True
Job: 45 is True
Job: 46 is True
Job: 47 is True
Job: 48 is True
Job: 49 is True
Time elapsed: 0.592607975006 s
Job execution statistics:
job count | % of all jobs | job time sum | time per job | job server
3 | 6.00 | 0.3226 | 0.107546 | x.x.x.x:abcd
3 | 6.00 | 0.2849 | 0.094970 | x.x.x.x:abcd
2 | 4.00 | 0.2420 | 0.121004 | x.x.x.x:abcd
3 | 6.00 | 0.3328 | 0.110927 | x.x.x.x:abcd
2 | 4.00 | 0.2314 | 0.115687 | x.x.x.x:abcd
2 | 4.00 | 0.2634 | 0.131683 | x.x.x.x:abcd
3 | 6.00 | 0.2827 | 0.094223 | x.x.x.x:abcd
2 | 4.00 | 0.2496 | 0.124812 | x.x.x.x:abcd
1 | 2.00 | 0.1701 | 0.170140 | x.x.x.x:abcd
3 | 6.00 | 0.3053 | 0.101758 | x.x.x.x:abcd
1 | 2.00 | 0.1334 | 0.133415 | x.x.x.x:abcd
3 | 6.00 | 0.2777 | 0.092561 | x.x.x.x:abcd
1 | 2.00 | 0.1152 | 0.115169 | x.x.x.x:abcd
1 | 2.00 | 0.1273 | 0.127294 | x.x.x.x:abcd
3 | 6.00 | 0.3345 | 0.111503 | x.x.x.x:abcd
1 | 2.00 | 0.1128 | 0.112782 | x.x.x.x:abcd
2 | 4.00 | 0.2636 | 0.131819 | x.x.x.x:abcd
8 | 16.00 | 0.4413 | 0.055163 | local
1 | 2.00 | 0.1905 | 0.190510 | x.x.x.x:abcd
3 | 6.00 | 0.2774 | 0.092473 | x.x.x.x:abcd
2 | 4.00 | 0.2197 | 0.109835 | x.x.x.x:abcd
Time elapsed since server creation 0.592818021774
List of files created: (One per job)
0
1
10
11
12
13
14
15
16
17
18
19
2
20
21
22
3
4
5
6
7
8
9
A:
Ok my mistake! Just in case anyone else faces this issue, make sure your directory paths are absolute whether you are reading from a file or writing into a file... 5 hours of debugging :( but I learnt my lesson :)
| Jobs are getting lost in ParallelPython? | I am submitting about 234 jobs (but my example contains only 50 for demonstration purpose) to my 20 node cluster using ParallelPython. I was expecting that it would queue and execute them but it seems to "lose" jobs and I am not understand where things are going wrong. When the script finishes, I am not able to see 50 files i.e. info_1, info_2 .... info_50 but rather I am seeing some random behavior. Any suggestions?
def readChecklist():
f = open('/home/username/twisted/pp-1.6.0/checklist', 'r')
checklist = [line.strip() for line in f]
return checklist
def processFile(num):
bl = readChecklist()
# pick a filename to write to
outfile = "info_" + str(num)
FILE = open(outfile, "a")
for i in range(num):
FILE.write(str(i)+"\n")
FILE.flush()
FILE.close()
return num
ppservers=("*",)
job_server = pp.Server(ppservers=ppservers)
inputs = range(50)
jobs = [(input, job_server.submit(processFile,(input,), (readCheckList,), ("os","math","time","sys","subprocess",))) for input in inputs]
for input, job in jobs:
print "Job: ", input, " is", job()
job_server.print_stats()
Output:
Job: 0 is True
Job: 1 is True
Job: 2 is True
Job: 3 is True
Job: 4 is True
Job: 5 is True
Job: 6 is True
Job: 7 is True
Job: 8 is True
Job: 9 is True
Job: 10 is True
Job: 11 is True
Job: 12 is True
Job: 13 is True
Job: 14 is True
Job: 15 is True
Job: 16 is True
Job: 17 is True
Job: 18 is True
Job: 19 is True
Job: 20 is True
Job: 21 is True
Job: 22 is True
Job: 23 is True
Job: 24 is True
Job: 25 is True
Job: 26 is True
Job: 27 is True
Job: 28 is True
Job: 29 is True
Job: 30 is True
Job: 31 is True
Job: 32 is True
Job: 33 is True
Job: 34 is True
Job: 35 is True
Job: 36 is True
Job: 37 is True
Job: 38 is True
Job: 39 is True
Job: 40 is True
Job: 41 is True
Job: 42 is True
Job: 43 is True
Job: 44 is True
Job: 45 is True
Job: 46 is True
Job: 47 is True
Job: 48 is True
Job: 49 is True
Time elapsed: 0.592607975006 s
Job execution statistics:
job count | % of all jobs | job time sum | time per job | job server
3 | 6.00 | 0.3226 | 0.107546 | x.x.x.x:abcd
3 | 6.00 | 0.2849 | 0.094970 | x.x.x.x:abcd
2 | 4.00 | 0.2420 | 0.121004 | x.x.x.x:abcd
3 | 6.00 | 0.3328 | 0.110927 | x.x.x.x:abcd
2 | 4.00 | 0.2314 | 0.115687 | x.x.x.x:abcd
2 | 4.00 | 0.2634 | 0.131683 | x.x.x.x:abcd
3 | 6.00 | 0.2827 | 0.094223 | x.x.x.x:abcd
2 | 4.00 | 0.2496 | 0.124812 | x.x.x.x:abcd
1 | 2.00 | 0.1701 | 0.170140 | x.x.x.x:abcd
3 | 6.00 | 0.3053 | 0.101758 | x.x.x.x:abcd
1 | 2.00 | 0.1334 | 0.133415 | x.x.x.x:abcd
3 | 6.00 | 0.2777 | 0.092561 | x.x.x.x:abcd
1 | 2.00 | 0.1152 | 0.115169 | x.x.x.x:abcd
1 | 2.00 | 0.1273 | 0.127294 | x.x.x.x:abcd
3 | 6.00 | 0.3345 | 0.111503 | x.x.x.x:abcd
1 | 2.00 | 0.1128 | 0.112782 | x.x.x.x:abcd
2 | 4.00 | 0.2636 | 0.131819 | x.x.x.x:abcd
8 | 16.00 | 0.4413 | 0.055163 | local
1 | 2.00 | 0.1905 | 0.190510 | x.x.x.x:abcd
3 | 6.00 | 0.2774 | 0.092473 | x.x.x.x:abcd
2 | 4.00 | 0.2197 | 0.109835 | x.x.x.x:abcd
Time elapsed since server creation 0.592818021774
List of files created: (One per job)
0
1
10
11
12
13
14
15
16
17
18
19
2
20
21
22
3
4
5
6
7
8
9
| [
"Ok my mistake! Just in case anyone else faces this issue, make sure your directory paths are absolute whether you are reading from a file or writing into a file... 5 hours of debugging :( but I learnt my lesson :)\n"
] | [
0
] | [] | [] | [
"cluster_computing",
"debugging",
"parallel_processing",
"python"
] | stackoverflow_0003818252_cluster_computing_debugging_parallel_processing_python.txt |
Q:
Assignment raises exception for list.index
How could this code fragment...
def subInPath(origPath, subPath):
origSplit = split(origPath, '/')
subSplit = split(subPath, '/')
subRoot = subSplit[0]
origSplit.reverse()
print origSplit.index(subRoot)
rootIndex = origSplit.index(subRoot)
origSplit[:rootIndex+1] = []
origSplit.reverse()
newPath = join(origSplit, sep)
newPath += (sep + subPath)
if not exists(newPath):
raise Exception, "Path subbed in not found."
return newPath
with the arguments ("C:/Users/MyName/Desktop/second_stage/Kickle_Pack/GardenLand_D.xml", "Kickle_Pack/Animations/TileAnims_48x48.xml")...
Output 2 at the print statement, but throw a ValueError at the statement below it. I'm baffled.
A:
Always use os.path module when working with directories or paths. It's got all the methods needed to work with directories, plus it has the advantage of being compatible in multiples operating system.
It's just better software engineering.
| Assignment raises exception for list.index | How could this code fragment...
def subInPath(origPath, subPath):
origSplit = split(origPath, '/')
subSplit = split(subPath, '/')
subRoot = subSplit[0]
origSplit.reverse()
print origSplit.index(subRoot)
rootIndex = origSplit.index(subRoot)
origSplit[:rootIndex+1] = []
origSplit.reverse()
newPath = join(origSplit, sep)
newPath += (sep + subPath)
if not exists(newPath):
raise Exception, "Path subbed in not found."
return newPath
with the arguments ("C:/Users/MyName/Desktop/second_stage/Kickle_Pack/GardenLand_D.xml", "Kickle_Pack/Animations/TileAnims_48x48.xml")...
Output 2 at the print statement, but throw a ValueError at the statement below it. I'm baffled.
| [
"Always use os.path module when working with directories or paths. It's got all the methods needed to work with directories, plus it has the advantage of being compatible in multiples operating system.\nIt's just better software engineering.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003818923_python.txt |
Q:
How to replace all the characters with * using Regular Expression
I am having a text like
s = bluesky
I want to get it as s = ******* (equal no of * as no of characters)
I am searching for a regular expression for Python.
Edit 1 :
b = '*'*len(s)
How can we do it in Django Template?
A:
You don't need a regex for this:
s = 'bluesky'
b = '*'*len(s)
print b
output :
>>> s = 'bluesky'
>>> b = '*'*len(s)
>>> print b
*******
A:
No need for regexp, just text.replace('bluesky','*'*len('bluesky'))
e.g:
>>> text = "s = bluesky"
>>> text.replace('bluesky','*'*len('bluesky'))
's = *******'
A:
How can we do it in Django Template
In a Django template? Dead easy.
{% for char in s %}*{% endfor %}
Where s is the template variable whose value is bluesky.
A:
>>> import re
>>> re.sub("(\w+)\s*=\s*(\w+)", lambda m: "%s = %s" % (m.group(1), '*'*len(m.group(2))), "s = bluesky")
's = *******'
>>> re.sub("(\w+)\s*=\s*(\w+)", lambda m: "%s = %s" % (m.group(1), '*'*len(m.group(2))), "cat=dog")
'cat = ***'
Assuming your string is literally s = bluesky
| How to replace all the characters with * using Regular Expression | I am having a text like
s = bluesky
I want to get it as s = ******* (equal no of * as no of characters)
I am searching for a regular expression for Python.
Edit 1 :
b = '*'*len(s)
How can we do it in Django Template?
| [
"You don't need a regex for this:\ns = 'bluesky'\nb = '*'*len(s)\nprint b\n\noutput : \n>>> s = 'bluesky'\n>>> b = '*'*len(s)\n>>> print b\n*******\n\n",
"No need for regexp, just text.replace('bluesky','*'*len('bluesky'))\ne.g:\n>>> text = \"s = bluesky\"\n>>> text.replace('bluesky','*'*len('bluesky'))\n's = ***... | [
6,
2,
2,
0
] | [] | [] | [
"django",
"django_templates",
"html",
"python",
"regex"
] | stackoverflow_0003819097_django_django_templates_html_python_regex.txt |
Q:
django: can we do loader.get_template('my_template.txt')?
I want to use django template to process plain text file, and tried this:
from django.template import loader, Context
t = loader.get_template('my_template.txt')
however, it works for this:
from django.template import loader, Context
t = loader.get_template('my_template.html')
Can we load txt files using django template loader? how?
thanks.
A:
As @Seth commented I don't see any reason why this shouldn't work. Django doesn't care about the extension of the file. You can very well load my_template.foo.
Check the following:
The file is indeed present where it should be. If it is in a subdirectory then you'll have to use loader.get_template('<subdirectory>/my_template.txt') where subdirectory is the name of the directory.
Check if you have an app name. It is common to locate all templates for an app in a directory with the app's name.
As @Seth said double check your TEMPLATE_DIRS setting. The template should be inside one the directories in this list.
| django: can we do loader.get_template('my_template.txt')? | I want to use django template to process plain text file, and tried this:
from django.template import loader, Context
t = loader.get_template('my_template.txt')
however, it works for this:
from django.template import loader, Context
t = loader.get_template('my_template.html')
Can we load txt files using django template loader? how?
thanks.
| [
"As @Seth commented I don't see any reason why this shouldn't work. Django doesn't care about the extension of the file. You can very well load my_template.foo. \nCheck the following:\n\nThe file is indeed present where it should be. If it is in a subdirectory then you'll have to use loader.get_template('<subdirect... | [
3
] | [
"I would leave this for some one else to answer as I am not very comfortable with Django.\nHow ever, if you are interested in templates and plain text processing, why don't you look at slew of other products available within python.\n\nhttps://stackoverflow.com/questions/98245/what-is-your-single-favorite-python-te... | [
-7
] | [
"django",
"django_templates",
"python"
] | stackoverflow_0003817926_django_django_templates_python.txt |
Q:
Is there any filter in Django to display asterisks (*) instead of text
I am eager to know whether any filter is available for displaying all the text as * like this
mytext = 'raja'
{{ mytext|password }} should show ****
How can we do this?
A:
Easy. Do this:
{% for char in mytext %}*{% endfor %}
That said, can I ask you where you are displaying the password? Usually passwords are not displayed on screen. If you want to display it in a form you can use a PasswordInput widget.
As @Ars said it is a bad idea to reveal the length of the password. You might want to display a random number of asterisks instead.
A:
is this really a password? Then it seems like a bad idea -- do you want to reveal that the password is 4 characters long? Just print 4 (or 5 or whatever) asterisks straight in the template always.
Otherwise, I wouldn't bother with a filter. Simply pass in a string of asterisks through the context:
mytext = 'raja'
ctx = Context({'mytext': '*' * len(mytext)})
t = Template('password: {{ mytext }}')
s = t.render(ctx)
| Is there any filter in Django to display asterisks (*) instead of text | I am eager to know whether any filter is available for displaying all the text as * like this
mytext = 'raja'
{{ mytext|password }} should show ****
How can we do this?
| [
"Easy. Do this:\n{% for char in mytext %}*{% endfor %}\n\nThat said, can I ask you where you are displaying the password? Usually passwords are not displayed on screen. If you want to display it in a form you can use a PasswordInput widget. \nAs @Ars said it is a bad idea to reveal the length of the password. You m... | [
3,
2
] | [] | [] | [
"django",
"django_templates",
"html",
"python"
] | stackoverflow_0003819260_django_django_templates_html_python.txt |
Q:
Python: How to do break up array processing (using multiple queued functions) in timed chunks (600ms)
I was wondering what would be the best approach to split up array processing using multiple queued functions into small time chunks?
So say I have an multi dimensional array, and I want to run a function(s) over it, but only in small timed chunks, say 500ms each time I trigger the processing to occur.
What would be the best approach?
One way I can think of is using psuedo code
#get time
#loop_marker:
#if current function_to_run is None
# pop function to run off queue store
#
#run function_to_run once
#increment start_index (in array) for next time or set function_to_run to None if finished array
#check time_diff
#if time_diff < limit - time_diff (i.e. if we can run this function again before hitting the limit)
# goto loop_marker
#else
# yield
Obviously this is not very Pythonic. So any ideas? Any cleaner ways?
I cannot install anything on the machine its processing on apart from python 2.5
A:
You could set up a queue of functions to run as a generator that would yield each run, then have a small loop that looked like this:
time_elapsed = 0
for func in function_queue_generator:
if time_elapsed > time_limit:
yield
time_elapsed = 0
func()
Such a generator could be implemented like so, perhaps:
def run_func_on_args(input_arg_sets, func):
for argset in input_arg_sets:
yield lambda: func(argset)
There are many possible ways you could create such a generator; the above is just a simple example. You could create generators to run functions across multidimensional arrays, et cetera.
| Python: How to do break up array processing (using multiple queued functions) in timed chunks (600ms) | I was wondering what would be the best approach to split up array processing using multiple queued functions into small time chunks?
So say I have an multi dimensional array, and I want to run a function(s) over it, but only in small timed chunks, say 500ms each time I trigger the processing to occur.
What would be the best approach?
One way I can think of is using psuedo code
#get time
#loop_marker:
#if current function_to_run is None
# pop function to run off queue store
#
#run function_to_run once
#increment start_index (in array) for next time or set function_to_run to None if finished array
#check time_diff
#if time_diff < limit - time_diff (i.e. if we can run this function again before hitting the limit)
# goto loop_marker
#else
# yield
Obviously this is not very Pythonic. So any ideas? Any cleaner ways?
I cannot install anything on the machine its processing on apart from python 2.5
| [
"You could set up a queue of functions to run as a generator that would yield each run, then have a small loop that looked like this:\ntime_elapsed = 0\nfor func in function_queue_generator:\n if time_elapsed > time_limit:\n yield\n time_elapsed = 0\n func()\n\nSuch a generator could be implemen... | [
1
] | [] | [] | [
"multidimensional_array",
"python"
] | stackoverflow_0003819387_multidimensional_array_python.txt |
Q:
Flex networking: How to read multiple AMF Objects
I'm trying to write a very plain game client to get some practice with Actionscript 3 and the Flex Framework.
I have some problems with following code:
private function readResponse():void {
var r:ByteArray = new ByteArray();
readBytes(r);
while (r.bytesAvailable != 0)
{
try
{
var d:Object = r.readObject();
protocol.execute(d); // do something with the object
}
catch (RangeError)
{
trace("Ouch, packet dismissed? Restlength:" + r.bytesAvailable);
}
}
}
It seems to work well in the client most of the time, but sometimes i got strange a behavior that shouldn't occure. If i look in the console output, there are many of "dismissed" packets.
Once i logged the discarded rest of the package, it very looks like a broken, uncomplete packet. It starts in the middle of a string e.g.
It often occurs if data is send rapidly from the server. On serverside, each of the packets are send by calling the related client.send() function.
Is this the wrong way to try handling more than one object incoming?
Could this be a serverside issue, causing the packets to be send malformed/incomplete?
I would be very happy if someone can help me out.
Little update, maybe this helps:
I logged the length of data send over the network.
The logged looks like this (server | client):
208 | 208
92 | 92
208 | 208
214 | 214 & Ouch, packet dismissed? Restlength:: 212
148 | r.bytesAvailable: 388
27 | 388 & Ouch, packet dismissed? Restlength:: 384
etc...
This looks like the server bursts data and the client is messing up with this.
What could i post more to get some help with this issue? Do i have to flush data manualy on the python server to get things work right? I'm not really sure what is happening. I just know that this happens mostly if I'm doig a lot of client.send() very very fast, like it get buffered and then send in the size of the buffer, so it cuts the packet into a few not readable for the client (because obviously it doesn't expect this). I'm really stuck with this :(
PS: The server is written in Python with an usual tutorial-like TCP socket and client threads.
A:
If you are using AMF, I do not understand why you would read bytes from a binary array?
Try using RemoteObject, and a response-handler ( and eventually also an error handler )
There is an example here: http://pyamf.org/tutorials/actionscript/simple.html#actionscript
(which I have not tried as I am not python savvy)
Other than that, remember that commands are fire and forget. The major part of issues encountered in dealing with server side traffic in Flex is caused by not registering event listeners etc. pr. server call.
Hope it helps
| Flex networking: How to read multiple AMF Objects | I'm trying to write a very plain game client to get some practice with Actionscript 3 and the Flex Framework.
I have some problems with following code:
private function readResponse():void {
var r:ByteArray = new ByteArray();
readBytes(r);
while (r.bytesAvailable != 0)
{
try
{
var d:Object = r.readObject();
protocol.execute(d); // do something with the object
}
catch (RangeError)
{
trace("Ouch, packet dismissed? Restlength:" + r.bytesAvailable);
}
}
}
It seems to work well in the client most of the time, but sometimes i got strange a behavior that shouldn't occure. If i look in the console output, there are many of "dismissed" packets.
Once i logged the discarded rest of the package, it very looks like a broken, uncomplete packet. It starts in the middle of a string e.g.
It often occurs if data is send rapidly from the server. On serverside, each of the packets are send by calling the related client.send() function.
Is this the wrong way to try handling more than one object incoming?
Could this be a serverside issue, causing the packets to be send malformed/incomplete?
I would be very happy if someone can help me out.
Little update, maybe this helps:
I logged the length of data send over the network.
The logged looks like this (server | client):
208 | 208
92 | 92
208 | 208
214 | 214 & Ouch, packet dismissed? Restlength:: 212
148 | r.bytesAvailable: 388
27 | 388 & Ouch, packet dismissed? Restlength:: 384
etc...
This looks like the server bursts data and the client is messing up with this.
What could i post more to get some help with this issue? Do i have to flush data manualy on the python server to get things work right? I'm not really sure what is happening. I just know that this happens mostly if I'm doig a lot of client.send() very very fast, like it get buffered and then send in the size of the buffer, so it cuts the packet into a few not readable for the client (because obviously it doesn't expect this). I'm really stuck with this :(
PS: The server is written in Python with an usual tutorial-like TCP socket and client threads.
| [
"If you are using AMF, I do not understand why you would read bytes from a binary array?\nTry using RemoteObject, and a response-handler ( and eventually also an error handler )\nThere is an example here: http://pyamf.org/tutorials/actionscript/simple.html#actionscript\n(which I have not tried as I am not python sa... | [
0
] | [] | [] | [
"actionscript_3",
"apache_flex",
"flex4",
"python"
] | stackoverflow_0003814140_actionscript_3_apache_flex_flex4_python.txt |
Q:
Lua or Python binding with C++
I have used Lua.NET on .NET platform and I could call the .NET class/object from Lua and I could call the Lua from .NET Lua API interface. I did the same with the IronPython. I knew the how the .NET binding works.
Now I have a C++ project and I want to use the dynamic capabilities. I want to call C++ object which may not be possible from Lua so I may need to call some C API which makes call to C++. Meantime I want to call the Lua from C++.
We have configuration data which is best described in table like format in Lua or List & Dict like in Python. We need to enumerate these data structures defined in Lua/Python in C++.
When considering Lua to Python in C++ for two way calling, is Python have upper hand with Boost Python library? I don't have experience in Python/C++ binding. I don't have equal experience of using Python in C++ and calling Python from C++.
A:
When considering Lua to Python in C++ for two way calling, is Python have upper hand with Boost Python library?
There are a few libraries that simplify the communication between C++ and Lua. One of them, luabind, is inspired by boost.python and is quite powerful and fairly easy to use.
Other C++ <-> Lua libraries to consider: toLua++, SWIG
A:
If you are planning to just use windows you could use C++/CLI a managed variant of C++. With C++/CLI you can easily mix managed and unmanaged code. You could call the managed classes from any .net language and the unmanaged (exported) functions from C.
| Lua or Python binding with C++ | I have used Lua.NET on .NET platform and I could call the .NET class/object from Lua and I could call the Lua from .NET Lua API interface. I did the same with the IronPython. I knew the how the .NET binding works.
Now I have a C++ project and I want to use the dynamic capabilities. I want to call C++ object which may not be possible from Lua so I may need to call some C API which makes call to C++. Meantime I want to call the Lua from C++.
We have configuration data which is best described in table like format in Lua or List & Dict like in Python. We need to enumerate these data structures defined in Lua/Python in C++.
When considering Lua to Python in C++ for two way calling, is Python have upper hand with Boost Python library? I don't have experience in Python/C++ binding. I don't have equal experience of using Python in C++ and calling Python from C++.
| [
"\nWhen considering Lua to Python in C++ for two way calling, is Python have upper hand with Boost Python library?\n\nThere are a few libraries that simplify the communication between C++ and Lua. One of them, luabind, is inspired by boost.python and is quite powerful and fairly easy to use. \nOther C++ <-> Lua lib... | [
4,
0
] | [] | [] | [
"boost",
"c++",
"embedding",
"lua",
"python"
] | stackoverflow_0003818703_boost_c++_embedding_lua_python.txt |
Q:
Google appengine blobstore debugging
I'm having an issue with blobstore uploads, but because of the way gae handles all of that, actually figuring out what the error was is giving me some trouble. I'm using django, which unfortunately tries very hard to prevent exceptions from reaching the user without formatting. It looks like the uploads are successful, there are __BlobInfo__ entities in the database, but then something is happening thats causing a 500 response.
Here's what the log says:
INFO 2010-09-29 03:54:33,236 dev_appserver.py:529] Internal redirection to /img/imup/aglwaGFzZS10d29yDQsSB1Byb2plY3QYAgw
INFO 2010-09-29 03:54:33,654 dev_appserver_blobstore.py:328] Upload handler returned 500
ERROR 2010-09-29 03:54:33,654 dev_appserver_blobstore.py:341] Invalid upload handler response. Only 301, 302 and 303 statuses are permitted and it may not have a content body.
INFO 2010-09-29 03:54:33,736 dev_appserver.py:3275] "POST /_ah/upload/aglwaGFzZS10d29yGwsSFV9fQmxvYlVwbG9hZFNlc3Npb25fXxgPDA HTTP/1.1" 500 -
Is there some way to get more useful debug information out of the SDK?
A:
The exception your code is raising should be output immediately above the log lines you pasted - scroll up! If it's not, something in your framework is catching exceptions and not reporting them - possibly it's returning them to the user, which is not much use in this scenario.
A:
Well, here's how i'm now making progress. It's kind of icky:
try:
# something that might not work
except Exception, e:
return http.httpResponseRedirect('/%s'%repr(e))
and then I can read the error that occured in the URL.
I hope I can accept someone elses (much better) answer, because this is a terrible hack and it's no fun!
| Google appengine blobstore debugging | I'm having an issue with blobstore uploads, but because of the way gae handles all of that, actually figuring out what the error was is giving me some trouble. I'm using django, which unfortunately tries very hard to prevent exceptions from reaching the user without formatting. It looks like the uploads are successful, there are __BlobInfo__ entities in the database, but then something is happening thats causing a 500 response.
Here's what the log says:
INFO 2010-09-29 03:54:33,236 dev_appserver.py:529] Internal redirection to /img/imup/aglwaGFzZS10d29yDQsSB1Byb2plY3QYAgw
INFO 2010-09-29 03:54:33,654 dev_appserver_blobstore.py:328] Upload handler returned 500
ERROR 2010-09-29 03:54:33,654 dev_appserver_blobstore.py:341] Invalid upload handler response. Only 301, 302 and 303 statuses are permitted and it may not have a content body.
INFO 2010-09-29 03:54:33,736 dev_appserver.py:3275] "POST /_ah/upload/aglwaGFzZS10d29yGwsSFV9fQmxvYlVwbG9hZFNlc3Npb25fXxgPDA HTTP/1.1" 500 -
Is there some way to get more useful debug information out of the SDK?
| [
"The exception your code is raising should be output immediately above the log lines you pasted - scroll up! If it's not, something in your framework is catching exceptions and not reporting them - possibly it's returning them to the user, which is not much use in this scenario.\n",
"Well, here's how i'm now maki... | [
2,
0
] | [] | [] | [
"blobstore",
"django",
"google_app_engine",
"python"
] | stackoverflow_0003818754_blobstore_django_google_app_engine_python.txt |
Q:
Distinct in many-to-many relation
class Order(models.Model):
...
class OrderItem(models.Model)
order = models.ForeignKey(Order)
product = models.ForeignKey(Product)
quantity = models.PositiveIntegerField()
What I need to do is to get the Order(s) which has only one order item. How can I write it using the QuerySet objects (without writing SQL)?
A:
The easiest way to do this would be to use the Count aggregation:
from django.db.models import Count
Order.objects.annotate(count = Count('orderitem__id')).filter(count = 1)
| Distinct in many-to-many relation | class Order(models.Model):
...
class OrderItem(models.Model)
order = models.ForeignKey(Order)
product = models.ForeignKey(Product)
quantity = models.PositiveIntegerField()
What I need to do is to get the Order(s) which has only one order item. How can I write it using the QuerySet objects (without writing SQL)?
| [
"The easiest way to do this would be to use the Count aggregation:\nfrom django.db.models import Count\nOrder.objects.annotate(count = Count('orderitem__id')).filter(count = 1)\n\n"
] | [
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003819677_django_django_models_python.txt |
Q:
Improving text extraction routine from XML
I've an XML file which contains no. of <TEXT> </TEXT> tags enclosing text.
<TEXT>
<!-- PJG STAG 4703 -->
<!-- PJG ITAG l=94 g=1 f=1 -->
<!-- PJG /ITAG -->
<!-- PJG ITAG l=69 g=1 f=1 -->
<!-- PJG /ITAG -->
<!-- PJG ITAG l=50 g=1 f=1 -->
<USDEPT>DEPARTMENT OF AGRICULTURE</USDEPT>
<!-- PJG /ITAG -->
<!-- PJG ITAG l=18 g=1 f=1 -->
<USBUREAU>Packers and Stockyards Administration</USBUREAU>
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
<!-- PJG ITAG l=55 g=1 f=1 -->
Amendment to Certification of Central Filing System_Oklahoma
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
<!-- PJG ITAG l=11 g=1 f=1 -->
The Statewide central filing system of Oklahoma has been previously certified, pursuant to section 1324 of the Food
Security Act of 1985, on the basis of information submitted by Hannah D. Atkins, Secretary of State, for farm products
produced in that State (52 FR 49056, December 29, 1987).
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
The certification is hereby amended on the basis of information submitted by John Kennedy, Secretary of State, for
additional farm products produced in that State as follows: Cattle semen, cattle embryos, milo.
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
This is issued pursuant to authority delegated by the Secretary of Agriculture.
<!-- PJG /ITAG -->
<!-- PJG QTAG 04 -->
<!-- PJG /QTAG -->
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG ITAG l=21 g=1 f=1 -->
<!-- PJG /ITAG -->
<!-- PJG ITAG l=21 g=1 f=4 -->
Authority:
<!-- PJG /ITAG -->
<!-- PJG ITAG l=21 g=1 f=1 -->
Sec. 1324(c)(2), Pub. L. 99-198, 99 Stat. 1535, 7 U.S.C. 1631(c)(2); 7 CFR 2.18(e)(3), 2.56(a)(3), 55 FR 22795.
<!-- PJG /ITAG -->
<!-- PJG QTAG 02 -->
<!-- PJG /QTAG -->
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG ITAG l=21 g=1 f=1 -->
Dated: January 21, 1994
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
<SIGNER>
<!-- PJG ITAG l=06 g=1 f=1 -->
Calvin W. Watkins, Acting Administrator,
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
</SIGNER>
<SIGNJOB>
<!-- PJG ITAG l=04 g=1 f=1 -->
Packers and Stockyards Administration.
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
</SIGNJOB>
<FRFILING>
<!-- PJG ITAG l=40 g=1 f=1 -->
[FR Doc. 94-1847 Filed 1-27-94; 8:45 am]
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
</FRFILING>
<BILLING>
<!-- PJG ITAG l=68 g=1 f=1 -->
BILLING CODE 3410-KD-P
<!-- PJG /ITAG -->
</BILLING>
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG /STAG -->
</TEXT>
My task is to extract text out of each of these TEXT nodes. This is what I'm doing:
def getTextFromXML():
global Text, xmlDoc
TextNodes = xmlDoc.getElementsByTagName("TEXT")
docstr = ''
#Text = [TextFromNode(textNode) for textNode in TextNodes]
for textNode in TextNodes:
for cNode in textNode.childNodes:
if cNode.nodeType == Node.TEXT_NODE:
docstr+=cNode.data
else:
for ccNode in cNode.childNodes:
if ccNode.nodeType == Node.TEXT_NODE:
docstr+=ccNode.data
Text.append(docstr)
Problem is that it is taking hell lot of time. I guess my function is not efficient. Can any one kindly advise me how this can be improved?
EDIT: The file I'm dealing with contains around 6000+ <TEXT> text elements.
A:
lxml is much easier to use than the xml libraries included in the standard python library. It's a binding for the C libxml2 library, so I'm assuming it's also faster.
I'd do something like this (using your variable names):
from lxml import etree
with open('some-file.xml') as f:
xmlDoc = etree.parse(f)
root = xmlDoc.getroot()
Text = []
for textNode in root.xpath('TEXT'):
docstr = '\n'.join(text.strip() for text in textNode.xpath('*/text() | text()') if text.strip())
Text.append(docstr)
A:
If you use lxml (or xml.etree in Python 2.7), you can use the .itertext() method on an element, eg.:
s = ''.join(elem.itertext())
With lxml, you could probably also use the string() xpath function (may be faster because all the work is done by libxml2 itself, and not in python):
s = elem.xpath('string()')
| Improving text extraction routine from XML | I've an XML file which contains no. of <TEXT> </TEXT> tags enclosing text.
<TEXT>
<!-- PJG STAG 4703 -->
<!-- PJG ITAG l=94 g=1 f=1 -->
<!-- PJG /ITAG -->
<!-- PJG ITAG l=69 g=1 f=1 -->
<!-- PJG /ITAG -->
<!-- PJG ITAG l=50 g=1 f=1 -->
<USDEPT>DEPARTMENT OF AGRICULTURE</USDEPT>
<!-- PJG /ITAG -->
<!-- PJG ITAG l=18 g=1 f=1 -->
<USBUREAU>Packers and Stockyards Administration</USBUREAU>
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
<!-- PJG ITAG l=55 g=1 f=1 -->
Amendment to Certification of Central Filing System_Oklahoma
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
<!-- PJG ITAG l=11 g=1 f=1 -->
The Statewide central filing system of Oklahoma has been previously certified, pursuant to section 1324 of the Food
Security Act of 1985, on the basis of information submitted by Hannah D. Atkins, Secretary of State, for farm products
produced in that State (52 FR 49056, December 29, 1987).
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
The certification is hereby amended on the basis of information submitted by John Kennedy, Secretary of State, for
additional farm products produced in that State as follows: Cattle semen, cattle embryos, milo.
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
This is issued pursuant to authority delegated by the Secretary of Agriculture.
<!-- PJG /ITAG -->
<!-- PJG QTAG 04 -->
<!-- PJG /QTAG -->
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG ITAG l=21 g=1 f=1 -->
<!-- PJG /ITAG -->
<!-- PJG ITAG l=21 g=1 f=4 -->
Authority:
<!-- PJG /ITAG -->
<!-- PJG ITAG l=21 g=1 f=1 -->
Sec. 1324(c)(2), Pub. L. 99-198, 99 Stat. 1535, 7 U.S.C. 1631(c)(2); 7 CFR 2.18(e)(3), 2.56(a)(3), 55 FR 22795.
<!-- PJG /ITAG -->
<!-- PJG QTAG 02 -->
<!-- PJG /QTAG -->
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG ITAG l=21 g=1 f=1 -->
Dated: January 21, 1994
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
<SIGNER>
<!-- PJG ITAG l=06 g=1 f=1 -->
Calvin W. Watkins, Acting Administrator,
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
</SIGNER>
<SIGNJOB>
<!-- PJG ITAG l=04 g=1 f=1 -->
Packers and Stockyards Administration.
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
</SIGNJOB>
<FRFILING>
<!-- PJG ITAG l=40 g=1 f=1 -->
[FR Doc. 94-1847 Filed 1-27-94; 8:45 am]
<!-- PJG 0012 frnewline -->
<!-- PJG /ITAG -->
</FRFILING>
<BILLING>
<!-- PJG ITAG l=68 g=1 f=1 -->
BILLING CODE 3410-KD-P
<!-- PJG /ITAG -->
</BILLING>
<!-- PJG 0012 frnewline -->
<!-- PJG 0012 frnewline -->
<!-- PJG /STAG -->
</TEXT>
My task is to extract text out of each of these TEXT nodes. This is what I'm doing:
def getTextFromXML():
global Text, xmlDoc
TextNodes = xmlDoc.getElementsByTagName("TEXT")
docstr = ''
#Text = [TextFromNode(textNode) for textNode in TextNodes]
for textNode in TextNodes:
for cNode in textNode.childNodes:
if cNode.nodeType == Node.TEXT_NODE:
docstr+=cNode.data
else:
for ccNode in cNode.childNodes:
if ccNode.nodeType == Node.TEXT_NODE:
docstr+=ccNode.data
Text.append(docstr)
Problem is that it is taking hell lot of time. I guess my function is not efficient. Can any one kindly advise me how this can be improved?
EDIT: The file I'm dealing with contains around 6000+ <TEXT> text elements.
| [
"lxml is much easier to use than the xml libraries included in the standard python library. It's a binding for the C libxml2 library, so I'm assuming it's also faster.\nI'd do something like this (using your variable names):\nfrom lxml import etree\nwith open('some-file.xml') as f:\n xmlDoc = etree.parse(f)\n ... | [
1,
0
] | [] | [] | [
"python",
"xml",
"xml_parsing"
] | stackoverflow_0003818711_python_xml_xml_parsing.txt |
Q:
Testing for extra_context in django
I'm trying to test if the extra_context provided by the user was correctly processed
in the view.
Here is my test approach:
# tests.py (of course it's a part of TestCase class)
def test_should_use_definied_extra_context(self):
response = self.client.get(reverse('contact_question_create'), {
'extra_context': {'foo': 'bar', 'callable': lambda: 'called'}
})
eq_(response.context['foo'], 'bar')
eq_(response.context['callable'], 'called')
And here is my view function:
# views.py (my view function)
def contact_question_create(request, success_url=None, form_class=None,
template_name="contact/contact_form.html",
extra_context=None, **kwargs):
if form_class is None:
form_class = forms.DefaultContactForm
if request.method == 'POST':
form = form_class(data=request.POST, files=request.FILES)
if form.is_valid():
signals.question_posted.send(sender='contact_question_create_view',
form_data=form.cleaned_data)
if success_url is None:
pass # TODO: implement this case
else:
return redirect(sucess_url)
else:
form = form_class()
if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{'form':form},
context_instance=context)
When running the test I'm getting following KeyError exception:
======================================================================
ERROR: test_should_use_definied_extra_context (mpozyczka.apps.contact.tests.ContactViewShouldUseRequestedValues)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py",
line 279, in run testMethod()
File "/Users/bx2/Dropbox/Projekty/mpozyczka/src/mpozyczka/apps/contact/tests.py",
line 56, in test_should_use_definied_extra_context
eq_(response.context['foo'], 'bar')
File "/Users/bx2/Dropbox/Projekty/mpozyczka/parts/django/django/test/utils.py",
line 35, in __getitem__ raise KeyError(key)
KeyError: 'foo'
I think I'm too tired and I don't see the problem - any clues about what am I missing?
A:
You need to use following solution:
def contact_question_create(request, success_url=None, form_class=None,
template_name="contact/contact_form.html",
extra_context=None, **kwargs):
# your view code here
context = {'defult':'foo'}
if extra_context:
context.update(extra_context)
return render_to_response(template_name,
context,
context_instance=RequestContext(request, context))
When testing it you need to pass extra_context either in url.py or in view that calls your view.
def my_view(reuest):
return contact_question_create(extra_context={'foo':'bar'})
| Testing for extra_context in django | I'm trying to test if the extra_context provided by the user was correctly processed
in the view.
Here is my test approach:
# tests.py (of course it's a part of TestCase class)
def test_should_use_definied_extra_context(self):
response = self.client.get(reverse('contact_question_create'), {
'extra_context': {'foo': 'bar', 'callable': lambda: 'called'}
})
eq_(response.context['foo'], 'bar')
eq_(response.context['callable'], 'called')
And here is my view function:
# views.py (my view function)
def contact_question_create(request, success_url=None, form_class=None,
template_name="contact/contact_form.html",
extra_context=None, **kwargs):
if form_class is None:
form_class = forms.DefaultContactForm
if request.method == 'POST':
form = form_class(data=request.POST, files=request.FILES)
if form.is_valid():
signals.question_posted.send(sender='contact_question_create_view',
form_data=form.cleaned_data)
if success_url is None:
pass # TODO: implement this case
else:
return redirect(sucess_url)
else:
form = form_class()
if extra_context is None:
extra_context = {}
context = RequestContext(request)
for key, value in extra_context.items():
context[key] = callable(value) and value() or value
return render_to_response(template_name,
{'form':form},
context_instance=context)
When running the test I'm getting following KeyError exception:
======================================================================
ERROR: test_should_use_definied_extra_context (mpozyczka.apps.contact.tests.ContactViewShouldUseRequestedValues)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py",
line 279, in run testMethod()
File "/Users/bx2/Dropbox/Projekty/mpozyczka/src/mpozyczka/apps/contact/tests.py",
line 56, in test_should_use_definied_extra_context
eq_(response.context['foo'], 'bar')
File "/Users/bx2/Dropbox/Projekty/mpozyczka/parts/django/django/test/utils.py",
line 35, in __getitem__ raise KeyError(key)
KeyError: 'foo'
I think I'm too tired and I don't see the problem - any clues about what am I missing?
| [
"You need to use following solution:\ndef contact_question_create(request, success_url=None, form_class=None,\n template_name=\"contact/contact_form.html\",\n extra_context=None, **kwargs):\n\n # your view code here\n\n context = {'defult':'foo'}\n\n if extra_c... | [
3
] | [] | [] | [
"django",
"python",
"tdd",
"unit_testing"
] | stackoverflow_0003817199_django_python_tdd_unit_testing.txt |
Q:
List of combinations
I have a list with length N and each element of this list are 0 or 1.
I need to get all possible combinations of this list. Here is my code:
def some(lst):
result = []
for element in lst:
c1 = copy.copy(element)
c2 = copy.copy(element)
c1.append(0)
c2.append(1)
result.append(c1)
result.append(c2)
return result
def generate(n):
if(n == 1):
return [[0], [1]]
else:
return some(generate(n - 1))
print generate(4)
I think there is a more pythonic solution of this task.
Thanks in advance.
A:
Don't they look like bit patterns (0000 ....1111 ) i.e binary bits.
And all possible combination of n binary bits will range from 0 to 2**n -1
noOfBits = 5
for n in range(2**noOfBits):
binVal = bin(n)[2:].zfill(noOfBits)
b = [ x for x in binVal]
print b
Do we need combinatorics for this purpose?
Output:
['0', '0', '0', '0', '0']
['0', '0', '0', '0', '1']
['0', '0', '0', '1', '0']
['0', '0', '0', '1', '1']
['0', '0', '1', '0', '0']
['0', '0', '1', '0', '1']
.......
A:
The itertools module has ready generators for many combinatoric tasks. For your task:
list(itertools.product(*noOfBits * ((0, 1),)))
| List of combinations | I have a list with length N and each element of this list are 0 or 1.
I need to get all possible combinations of this list. Here is my code:
def some(lst):
result = []
for element in lst:
c1 = copy.copy(element)
c2 = copy.copy(element)
c1.append(0)
c2.append(1)
result.append(c1)
result.append(c2)
return result
def generate(n):
if(n == 1):
return [[0], [1]]
else:
return some(generate(n - 1))
print generate(4)
I think there is a more pythonic solution of this task.
Thanks in advance.
| [
"Don't they look like bit patterns (0000 ....1111 ) i.e binary bits.\nAnd all possible combination of n binary bits will range from 0 to 2**n -1 \nnoOfBits = 5\nfor n in range(2**noOfBits):\n binVal = bin(n)[2:].zfill(noOfBits)\n b = [ x for x in binVal]\n print b\n\nDo we need combinatorics for this purpo... | [
5,
3
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0003819658_algorithm_python.txt |
Q:
Telnet performance in windows xp and Linux
I has a Library impelmented based on Python's telnetlib.
And recently, i noticed that the performance in windows xp and Linux is so different.
below script, i design three operations, "get units", "just press enter", "get units with options"
"get units" has long string return, "get units with options" return shorter string, and "just press enter" will return shortest string.
let's guess, which will spend more time, seems it's order should be "get units", "get units with options", then "just press enter".
but actual result in windows xp is:
get units: 3.67200016975 s
get units with options: 10.0319998264 s
just press enter: 10.0 s
same test in Ubuntu:
get units: 3.91432785988
get units with options: 2.86995506287
just press enter: 2.05337381363
it seems that windows xp has good performance on large IP packet, but for small packet, it is so bad.
i have tested it manually, using windows's telnet client, putty. Using wireshark to capture telnet data. And find that for small packet, packet delay is so long, about 0.2s
i have tried to change tcp window, but haven't help.
can anyone give some suggestions?
try:
begin_g = time.time()
for i in range(50):
connection.write('ZUSI:OMU;')
ret = connection.read_until('<')
ret = connection.read_until('<')
end_g = time.time()
elapse_g = end_g-begin_g
clean_begin_t = time.time()
for i in range(50):
ret = ipa.get_units()
clean_end_t = time.time()
elapse_c = clean_end_t-clean_begin_t
begin_wu = time.time()
for i in range(50):
connection.write('')
ret = connection.read_until_prompt()
end_wu = time.time()
elapse_wu = end_wu-begin_wu
A:
Maybe it's delaying sending a short packet because of Nagle's algorithm.
You could test that by disabling the Nagle algorithm on the XP machine (Google for how to do that).
A:
Thank you all. I have solve this problems. There are two algorithm: The Nagle algorithm, The delayed ACK algorithm. My problem is caused by "The delayed ACK algorithm". Unfortunately, it can not be set in Python. I have to modify register, set value to 1, and it works at all. But i think it is not good enough. Linux support TCP_QUICKACK. But Windows do not.
[HKEY_LOCAL_MACHINE \SYSTEM \CurrentControlSet \Services \Tcpip \Parameters \Interfaces \{Adapter-id}]
TcpAckFrequency = 2 (Default=2, 1=Disables delayed ACK, 2-n = If n outstanding ACKs before timed interval, sent ACK)
More Info MS KB Q328890
More Info MS KB 815230 (XP/2003 needs hotfix or SP2 for it to work)
More Info MS KB 935458 (Vista needs hotfix or SP1 for it to work)
| Telnet performance in windows xp and Linux | I has a Library impelmented based on Python's telnetlib.
And recently, i noticed that the performance in windows xp and Linux is so different.
below script, i design three operations, "get units", "just press enter", "get units with options"
"get units" has long string return, "get units with options" return shorter string, and "just press enter" will return shortest string.
let's guess, which will spend more time, seems it's order should be "get units", "get units with options", then "just press enter".
but actual result in windows xp is:
get units: 3.67200016975 s
get units with options: 10.0319998264 s
just press enter: 10.0 s
same test in Ubuntu:
get units: 3.91432785988
get units with options: 2.86995506287
just press enter: 2.05337381363
it seems that windows xp has good performance on large IP packet, but for small packet, it is so bad.
i have tested it manually, using windows's telnet client, putty. Using wireshark to capture telnet data. And find that for small packet, packet delay is so long, about 0.2s
i have tried to change tcp window, but haven't help.
can anyone give some suggestions?
try:
begin_g = time.time()
for i in range(50):
connection.write('ZUSI:OMU;')
ret = connection.read_until('<')
ret = connection.read_until('<')
end_g = time.time()
elapse_g = end_g-begin_g
clean_begin_t = time.time()
for i in range(50):
ret = ipa.get_units()
clean_end_t = time.time()
elapse_c = clean_end_t-clean_begin_t
begin_wu = time.time()
for i in range(50):
connection.write('')
ret = connection.read_until_prompt()
end_wu = time.time()
elapse_wu = end_wu-begin_wu
| [
"Maybe it's delaying sending a short packet because of Nagle's algorithm.\nYou could test that by disabling the Nagle algorithm on the XP machine (Google for how to do that).\n",
"Thank you all. I have solve this problems. There are two algorithm: The Nagle algorithm, The delayed ACK algorithm. My problem is caus... | [
0,
0
] | [] | [] | [
"linux",
"python",
"sockets",
"telnet",
"windows"
] | stackoverflow_0003818345_linux_python_sockets_telnet_windows.txt |
Q:
Accessing Yahoo Contacts through OAuth on App Engine (Python)
I have an existing webapp, running in Python on App Engine, in which users can login through open-id using a Yahoo account. Now, once they're signed in, I'd like them to be able to access their Yahoo contacts, through OAuth. I'm working though the Yahoo Python SDK and am just stuck.
I have the consumer key, consumer secret, app ID, and the callback URL is the same page, the use leaves from. Going to the Yahoo login pages seems to work fine and the user comes back to my site with an auth_token and auth_verifier. What do I do with those? Which strings do I need to store for future requests? Is there good sample code anywhere for these kinds of requests? Thanks.
A:
You should look for OpenID+Oauth Hybrid protocol.
OpenID+OAuth Hybrid protocol lets web developers combine an OpenID request with an OAuth authentication request.
This extension is useful for web developers who use both OpenID and OAuth, particularly in that it simplifies the process for users by requesting their approval once instead of twice.
The goal of OAuth is to acquire an
access token from Google, which can
then be used to exchange user-specific
data with a Google service (such as
calendar information or an address
book). The regular OAuth process is a
four-step sequence: (1) ask for a
"request" token, (2) ask for the token
to be authorized, which triggers user
approval, (3) exchange the authorized
request token for an "access" token,
and (4) use the access token to
interact with the user's Google
service data. For a more detailed
description, see OAuth for Web
Applications.
With OpenID+OAuth, this sequence
remains essentially the same. The
difference is that getting an
authorized OAuth request token (steps
1 and 2) is wrapped up in the OpenID
authentication request. In this way,
the user can approve login and service
access at the same time.
Here a demo and source code (php) of Hybrid protocol using Google.
Here and here the Yahoo documentation to combine an OpenID authentication request with the approval of an OAuth request token.
| Accessing Yahoo Contacts through OAuth on App Engine (Python) | I have an existing webapp, running in Python on App Engine, in which users can login through open-id using a Yahoo account. Now, once they're signed in, I'd like them to be able to access their Yahoo contacts, through OAuth. I'm working though the Yahoo Python SDK and am just stuck.
I have the consumer key, consumer secret, app ID, and the callback URL is the same page, the use leaves from. Going to the Yahoo login pages seems to work fine and the user comes back to my site with an auth_token and auth_verifier. What do I do with those? Which strings do I need to store for future requests? Is there good sample code anywhere for these kinds of requests? Thanks.
| [
"You should look for OpenID+Oauth Hybrid protocol.\nOpenID+OAuth Hybrid protocol lets web developers combine an OpenID request with an OAuth authentication request.\nThis extension is useful for web developers who use both OpenID and OAuth, particularly in that it simplifies the process for users by requesting thei... | [
0
] | [] | [] | [
"google_app_engine",
"oauth",
"python",
"yahoo_oauth"
] | stackoverflow_0003818046_google_app_engine_oauth_python_yahoo_oauth.txt |
Q:
How to get server reply after sending a mail using smtplib SMTP.sendmail
I have a program to send mail using python smtplib. I have the mail sending part working fine, but I also need to capture the server return message after a mail has been sent. For example postfix returns the following message after a mail has been queueed:
reply: '250 2.0.0 Ok: queued as EB83821273B\r\n'
reply: retcode (250); Msg: 2.0.0 Ok: queued as EB83821273B
data: (250, '2.0.0 Ok: queued as EB83821273B')
What I am really interested is the error code (250) and the queue id (EB83821273B). I can print these if I set set_debuglevel(1), but I need to capture this in a variable for further logging and processing.
thanks and regards,
raj
A:
If you are using the sendmail method on an SMTP instance, then it will return
a dictionary, with one entry for each
recipient that was refused. Each entry
contains a tuple of the SMTP error
code and the accompanying error
message sent by the server.
if you use the docmd method on the same class, the it will return
a 2-tuple composed of a numeric response code and the actual response line (multiline responses are joined into one long line.)
| How to get server reply after sending a mail using smtplib SMTP.sendmail | I have a program to send mail using python smtplib. I have the mail sending part working fine, but I also need to capture the server return message after a mail has been sent. For example postfix returns the following message after a mail has been queueed:
reply: '250 2.0.0 Ok: queued as EB83821273B\r\n'
reply: retcode (250); Msg: 2.0.0 Ok: queued as EB83821273B
data: (250, '2.0.0 Ok: queued as EB83821273B')
What I am really interested is the error code (250) and the queue id (EB83821273B). I can print these if I set set_debuglevel(1), but I need to capture this in a variable for further logging and processing.
thanks and regards,
raj
| [
"If you are using the sendmail method on an SMTP instance, then it will return\n\na dictionary, with one entry for each\n recipient that was refused. Each entry\n contains a tuple of the SMTP error\n code and the accompanying error\n message sent by the server.\n\nif you use the docmd method on the same class, ... | [
5
] | [] | [] | [
"python",
"smtplib"
] | stackoverflow_0003820603_python_smtplib.txt |
Q:
How to perform this sql in django model?
SELECT *, SUM( cardtype.price - cardtype.cost ) AS profit
FROM user
LEFT OUTER JOIN card ON ( user.id = card.buyer_id )
LEFT OUTER JOIN cardtype ON ( card.cardtype_id = cardtype.id )
GROUP BY user.id
ORDER BY profit DESC
I tried this:
User.objects.extra(select=dict(profit='SUM(cardtype.price-cardtype.cost)')).annotate(sum=Sum('card__cardtype__price')).order_by('-profit')
But Django automatically added SUM( cardtype.price ) to the GROUP BY clause, and the SQL doesn't run.
Can this be done without raw SQLs?
Provide the model, never mind these Chinese characters :)
class User(models.Model):
class Meta:
verbose_name = "用户"
verbose_name_plural = "用户"
ordering = ['-regtime']
user_status= (
("normal", "正常"),
("deregistered", "注销"),
("locked", "锁定"),
)
name = models.CharField("姓名", max_length=20, db_index=True)
spec_class = models.ForeignKey(SpecClass, verbose_name="专业班级")
idcard = models.CharField("身份证号", max_length=18)
mobileno = models.CharField("手机号", max_length=11)
password = models.CharField("密码", max_length=50) # plain
address = models.CharField("住址", max_length=100)
comment = models.TextField("备注")
certserial = models.CharField("客户证书序列号", max_length=100)
regtime = models.DateTimeField("注册时间", default=datetime.datetime.now)
lastpaytime = models.DateTimeField("上次付款时间", default=datetime.datetime.now)
credit = models.FloatField("信用额度", default=100)
money = models.FloatField("余额", default=0)
use_password = models.BooleanField("使用密码")
use_fetion = models.BooleanField("接收飞信提示")
status = models.CharField("账户状态", choices = user_status, default="normal", max_length=20, db_index=True)
def __unicode__(self):
return self.name
class CardType(models.Model):
class Meta:
verbose_name = "点卡类型"
verbose_name_plural = "点卡类型"
ordering = ['name']
name = models.CharField("类型名称", max_length=20, db_index=True)
note = models.CharField("说明", max_length=100)
offcial = models.BooleanField("官方卡", default=True)
available = models.BooleanField("可用", default=True, db_index=True)
payurl = models.CharField("充值地址", max_length=200)
price = models.FloatField("价格")
cost = models.FloatField("进货价格")
def __unicode__(self):
return u"%s(%.2f元%s)" % (self.name, self.price, u", 平台卡" if not self.offcial else "")
def profit(self):
return self.price - self.cost
profit.short_description = "利润"
class Card(models.Model):
class Meta:
verbose_name = "点卡"
verbose_name_plural = "点卡"
ordering = ['-createtime']
card_status = (
("instock", "未上架"),
("available", "可用"),
("sold", "已购买"),
("invalid", "作废"),
("returned", "退卡"), # sell to the same person !
("reselled", "退卡重新售出"),
)
cardtype = models.ForeignKey(CardType, verbose_name="点卡类型")
serial = models.CharField("卡号", max_length=40)
password = models.CharField("卡密", max_length=20)
status = models.CharField("状态", choices = card_status, default="instock", max_length=20, db_index=True)
createtime = models.DateTimeField("入库时间")
buytime = models.DateTimeField("购买时间", blank=True, null=True)
buyer = models.ForeignKey(User, blank=True, null=True, verbose_name="买家")
def __unicode__(self):
return u'%s[%s]' % (self.cardtype.name, self.serial)
A:
First, one of the outer joins appears to be a bad idea for this kind of thing. Since you provided no information on your model, I can only guess.
Are you saying that you may not have a CARD for each user? That makes some sense.
Are you also saying that some cards don't have card types? That doesn't often make sense. You haven't provided any details. However, if a Card doesn't have a Card Type, I'll bet you have either problems elsewhere in your application, or you've chosen really poor names that don't provide the least clue as to what these things mean. You should fix the other parts of your application to assure that each card actually does have a card type. Or you should fix your names to be meaningful.
Clearly, the ORM statement uses inner joins and your SQL uses outer joins. What's the real question? How to do outer joins correctly?
If you take the time to search for [Django] and Left Outer Join, you'll see that the Raw SQL is a terrible idea.
Or is the real question how to do the sum correctly? From your own answer it appears that the SQL is wrong and you're really having trouble with the sum. If so, please clean up the SQL to be correct.
If the outer joins are part of the problem -- not just visual noise -- then you have to do something like this for an outer join with a sum.
def user_profit():
for u in User.objects.all():
profit = sum[ t.price - t.cost
for c in u.card_set.all()
for t in c.cardtype_set.all() ]
yield user, profit
In your view function, you can then provide the value of function to the template to render the report. Since it's a generator, no huge list is created in memory. If you need to paginate, you can provide the generator to the paginator and everything works out reasonably well.
This is often of comparable speed to a complex raw SQL query with a lot of outer joins.
If, indeed, the card to card-type relationship is not actually optional, then you can shorten this, somewhat. You still have an outer join to think about.
def user_profit():
for u in User.objects.all():
profit = sum[ c.cardtype.price - c.cardtype.cost
for c in u.card_set.all() ]
yield user, profit
| How to perform this sql in django model? | SELECT *, SUM( cardtype.price - cardtype.cost ) AS profit
FROM user
LEFT OUTER JOIN card ON ( user.id = card.buyer_id )
LEFT OUTER JOIN cardtype ON ( card.cardtype_id = cardtype.id )
GROUP BY user.id
ORDER BY profit DESC
I tried this:
User.objects.extra(select=dict(profit='SUM(cardtype.price-cardtype.cost)')).annotate(sum=Sum('card__cardtype__price')).order_by('-profit')
But Django automatically added SUM( cardtype.price ) to the GROUP BY clause, and the SQL doesn't run.
Can this be done without raw SQLs?
Provide the model, never mind these Chinese characters :)
class User(models.Model):
class Meta:
verbose_name = "用户"
verbose_name_plural = "用户"
ordering = ['-regtime']
user_status= (
("normal", "正常"),
("deregistered", "注销"),
("locked", "锁定"),
)
name = models.CharField("姓名", max_length=20, db_index=True)
spec_class = models.ForeignKey(SpecClass, verbose_name="专业班级")
idcard = models.CharField("身份证号", max_length=18)
mobileno = models.CharField("手机号", max_length=11)
password = models.CharField("密码", max_length=50) # plain
address = models.CharField("住址", max_length=100)
comment = models.TextField("备注")
certserial = models.CharField("客户证书序列号", max_length=100)
regtime = models.DateTimeField("注册时间", default=datetime.datetime.now)
lastpaytime = models.DateTimeField("上次付款时间", default=datetime.datetime.now)
credit = models.FloatField("信用额度", default=100)
money = models.FloatField("余额", default=0)
use_password = models.BooleanField("使用密码")
use_fetion = models.BooleanField("接收飞信提示")
status = models.CharField("账户状态", choices = user_status, default="normal", max_length=20, db_index=True)
def __unicode__(self):
return self.name
class CardType(models.Model):
class Meta:
verbose_name = "点卡类型"
verbose_name_plural = "点卡类型"
ordering = ['name']
name = models.CharField("类型名称", max_length=20, db_index=True)
note = models.CharField("说明", max_length=100)
offcial = models.BooleanField("官方卡", default=True)
available = models.BooleanField("可用", default=True, db_index=True)
payurl = models.CharField("充值地址", max_length=200)
price = models.FloatField("价格")
cost = models.FloatField("进货价格")
def __unicode__(self):
return u"%s(%.2f元%s)" % (self.name, self.price, u", 平台卡" if not self.offcial else "")
def profit(self):
return self.price - self.cost
profit.short_description = "利润"
class Card(models.Model):
class Meta:
verbose_name = "点卡"
verbose_name_plural = "点卡"
ordering = ['-createtime']
card_status = (
("instock", "未上架"),
("available", "可用"),
("sold", "已购买"),
("invalid", "作废"),
("returned", "退卡"), # sell to the same person !
("reselled", "退卡重新售出"),
)
cardtype = models.ForeignKey(CardType, verbose_name="点卡类型")
serial = models.CharField("卡号", max_length=40)
password = models.CharField("卡密", max_length=20)
status = models.CharField("状态", choices = card_status, default="instock", max_length=20, db_index=True)
createtime = models.DateTimeField("入库时间")
buytime = models.DateTimeField("购买时间", blank=True, null=True)
buyer = models.ForeignKey(User, blank=True, null=True, verbose_name="买家")
def __unicode__(self):
return u'%s[%s]' % (self.cardtype.name, self.serial)
| [
"First, one of the outer joins appears to be a bad idea for this kind of thing. Since you provided no information on your model, I can only guess. \nAre you saying that you may not have a CARD for each user? That makes some sense.\nAre you also saying that some cards don't have card types? That doesn't often mak... | [
1
] | [
"Well, I found this\nSum computed column in Django QuerySet\nHave to use raw SQL now...\nThank you two!\n"
] | [
-1
] | [
"django",
"django_models",
"python"
] | stackoverflow_0003819984_django_django_models_python.txt |
Q:
linux "more" like code in python for very big tuple/file/db records/numpy.darray?
I am in looking for a buffer code for process huge records in tuple / csv file / sqlite db records / numpy.darray, the buffer may just like linux command "more".
The request came from processing huge data records(100000000 rows maybe), the records may look like this:
0.12313 0.231312 0.23123 0.152432
0.22569 0.311312 0.54549 0.224654
0.33326 0.654685 0.67968 0.168749
...
0.42315 0.574575 0.68646 0.689596
I want process them in numpy.darray. For example, find special data process it and store them back, or process 2 cols. However it is too big then if numpy read the file directly it will give me a Memory Error.
Then, I think an adapter like mem cache page or linux "more file" command may save the memory when processing.
Because those raw data may presents as different format - csv / sqlite_db / hdf5 / xml. I want this adapter be more normalized, then, use the "[]" as a "row" may be a more common way because I think each records can be represented as a [].
So the adapter what I want may looks like this:
fd = "a opend big file" # or a tuple of objects, whatever, it is an iterable object can access all the raw rows
page = pager(fd)
page.page_buffer_size = 100 # buffer 100 line or 100 object in tuple
page.seek_to(0) # move to start
page.seek_to(120) # move to line #120
page.seek_to(-10) # seek back to #120
page.next_page()
page.prev_page()
page1 = page.copy()
page.remove(0)
page.sync()
Can someone show me some hints to prevent reinvent the wheel?
By the way, ATpy, http://atpy.sourceforge.net/ is a module can sync the numpy.array with raw datasource in different format, however, it also read all the data in-a-go into memory.
And the pytable is not suitable for me so far because SQL is not supported by it and the HDF5 file may not as popular as sqlite db(forgive me if this is wrong).
My plan is write this tools in this way:
1. helper.py <-- define all the house-keeping works for different file format
|- load_file()
|- seek_backword()
|- seek_forward()
| ...
2. adapter.py <-- define all the interface and import the helper to interact
with raw data and get a way to interact with numpy.darray in somehow.
|- load()
|- seek_to()
|- next_page()
|- prev_page()
|- sync()
|- self.page_buffer_size
|- self.abs_index_in_raw_for_this_page = []
|- self.index_for_this_page = []
|- self.buffered_rows = []
Thanks,
Rgs,
KC
A:
The linecache module may be helpful — you can call getline(filename, lineno) to efficiently retrieve lines from the given file.
You'll still have to figure out how high and wide the screen is. A quick googlance suggests that there are about 14 different ways to do this, some of which are probably outdated. The curses module may be your best bet, and will I think be necessary if you want to be able to scroll backwards smoothly.
A:
Ummmm.... You're not really talking about anything more than a list.
fd = open( "some file", "r" )
data = fd.readlines()
page_size = 100
data[0:0+page_size] # move to start
data[120:120+page_size] # move to line 120
here= 120
data[here-10:here-10+page_size] # move back 10 from here
here -= 10
data[here:here+page_size]
here += page_size
data[here:here+page_size]
I'm not sure that you actually need to invent anything.
| linux "more" like code in python for very big tuple/file/db records/numpy.darray? | I am in looking for a buffer code for process huge records in tuple / csv file / sqlite db records / numpy.darray, the buffer may just like linux command "more".
The request came from processing huge data records(100000000 rows maybe), the records may look like this:
0.12313 0.231312 0.23123 0.152432
0.22569 0.311312 0.54549 0.224654
0.33326 0.654685 0.67968 0.168749
...
0.42315 0.574575 0.68646 0.689596
I want process them in numpy.darray. For example, find special data process it and store them back, or process 2 cols. However it is too big then if numpy read the file directly it will give me a Memory Error.
Then, I think an adapter like mem cache page or linux "more file" command may save the memory when processing.
Because those raw data may presents as different format - csv / sqlite_db / hdf5 / xml. I want this adapter be more normalized, then, use the "[]" as a "row" may be a more common way because I think each records can be represented as a [].
So the adapter what I want may looks like this:
fd = "a opend big file" # or a tuple of objects, whatever, it is an iterable object can access all the raw rows
page = pager(fd)
page.page_buffer_size = 100 # buffer 100 line or 100 object in tuple
page.seek_to(0) # move to start
page.seek_to(120) # move to line #120
page.seek_to(-10) # seek back to #120
page.next_page()
page.prev_page()
page1 = page.copy()
page.remove(0)
page.sync()
Can someone show me some hints to prevent reinvent the wheel?
By the way, ATpy, http://atpy.sourceforge.net/ is a module can sync the numpy.array with raw datasource in different format, however, it also read all the data in-a-go into memory.
And the pytable is not suitable for me so far because SQL is not supported by it and the HDF5 file may not as popular as sqlite db(forgive me if this is wrong).
My plan is write this tools in this way:
1. helper.py <-- define all the house-keeping works for different file format
|- load_file()
|- seek_backword()
|- seek_forward()
| ...
2. adapter.py <-- define all the interface and import the helper to interact
with raw data and get a way to interact with numpy.darray in somehow.
|- load()
|- seek_to()
|- next_page()
|- prev_page()
|- sync()
|- self.page_buffer_size
|- self.abs_index_in_raw_for_this_page = []
|- self.index_for_this_page = []
|- self.buffered_rows = []
Thanks,
Rgs,
KC
| [
"The linecache module may be helpful — you can call getline(filename, lineno) to efficiently retrieve lines from the given file.\nYou'll still have to figure out how high and wide the screen is. A quick googlance suggests that there are about 14 different ways to do this, some of which are probably outdated. The ... | [
0,
0
] | [] | [] | [
"buffer",
"object",
"pager",
"python",
"tuples"
] | stackoverflow_0003820503_buffer_object_pager_python_tuples.txt |
Q:
does python gives interactivity as javascript?
I want to add interactivity like clicks, hover, onpage load() to a webpage, if i use python for generating xhtml, will python give essential flavors like javascript??
I'm bit confused and starter in python for web development, so is there need to include old javascript into python or the python only can handle interactivity, events as javascript?
A:
When you use Python for web development, you use it server-side (like PHP). It's not for client-side programming in the same way that JavaScript is. The vast majority of browsers only support JavaScript for client-side programming.
If you want client-side code on a site that's using Python on the server, it still has to use JavaScript on the client.
(For completeness, there is (or used to be) a way to use Python on the client side by installing PyWin32, but then your site would only work for people with that software installed and configured. I'd also be very dubious about its security.)
| does python gives interactivity as javascript? | I want to add interactivity like clicks, hover, onpage load() to a webpage, if i use python for generating xhtml, will python give essential flavors like javascript??
I'm bit confused and starter in python for web development, so is there need to include old javascript into python or the python only can handle interactivity, events as javascript?
| [
"When you use Python for web development, you use it server-side (like PHP). It's not for client-side programming in the same way that JavaScript is. The vast majority of browsers only support JavaScript for client-side programming.\nIf you want client-side code on a site that's using Python on the server, it sti... | [
5
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0003821305_javascript_python.txt |
Q:
Django ManyToMany relationship with abstract base - not possible, but is there a better way?
Given the following models:
class BaseMachine(models.Model)
fqdn = models.CharField(max_length=150)
cpus = models.IntegerField()
memory = models.IntegerField()
class Meta:
abstract = True
class PhysicalMachine(BaseMachine)
location = models.CharField(max_length=150)
class VirtualMachine(BaseMachine)
hypervisor = models.CharField(max_length=5)
class Sysadmin(models.Model):
name = models.CharField(max_length=100)
admin_of = models.ManyToManyField...
In this example I would like to relate 1 sysadmin to many machines - be them either an instance or PhysicalMachine or VirtualMachine. I know I can't have a ManyToMany with an abstract base, but I was wondering if there was a better way of achieving this than just having a separate ManyToMany field on sysadmin for each of the models? In this small example that could be tolerable, but if you have more than 2 subclasses, or if there are other models which you need to relate with the 'base' class, it becomes something more to manage.
Thanks :)
A:
EDIT: I have updated the soultion, so one admin can have many machines and one machine can have many admins:
class Sysadmin(models.Model):
name = models.CharField(max_length=100)
class BaseMachine(models.Model):
fqdn = models.CharField(max_length=150)
cpus = models.IntegerField()
memory = models.IntegerField()
admins = models.ManyToManyField(Sysadmin)
class Meta:
abstract = True
class PhysicalMachine(BaseMachine):
location = models.CharField(max_length=150)
class VirtualMachine(BaseMachine):
hypervisor = models.CharField(max_length=5)
In [1]: s1 = Sysadmin(name='mike')
In [2]: s1.save()
In [3]: m1 = PhysicalMachine(fqdn='test', cpus=1, memory=20, location='test')
In [4]: m1.save()
In [5]: m1.admins.add(s1)
In [6]: m1.save()
In [7]: m2 = VirtualMachine(fqdn='test', cpus=1, memory=20, hypervisor='test')
In [8]: m2.save()
In [9]: m2.admins.add(s1)
In [10]: m2.save()
In [11]: m1.admins.all()
Out[11]: [<Sysadmin: Sysadmin object>]
In [12]: m2.admins.all()
Out[12]: [<Sysadmin: Sysadmin object>]
A:
Have you considered a generic relationship using the contenttypes framework?
| Django ManyToMany relationship with abstract base - not possible, but is there a better way? | Given the following models:
class BaseMachine(models.Model)
fqdn = models.CharField(max_length=150)
cpus = models.IntegerField()
memory = models.IntegerField()
class Meta:
abstract = True
class PhysicalMachine(BaseMachine)
location = models.CharField(max_length=150)
class VirtualMachine(BaseMachine)
hypervisor = models.CharField(max_length=5)
class Sysadmin(models.Model):
name = models.CharField(max_length=100)
admin_of = models.ManyToManyField...
In this example I would like to relate 1 sysadmin to many machines - be them either an instance or PhysicalMachine or VirtualMachine. I know I can't have a ManyToMany with an abstract base, but I was wondering if there was a better way of achieving this than just having a separate ManyToMany field on sysadmin for each of the models? In this small example that could be tolerable, but if you have more than 2 subclasses, or if there are other models which you need to relate with the 'base' class, it becomes something more to manage.
Thanks :)
| [
"EDIT: I have updated the soultion, so one admin can have many machines and one machine can have many admins:\nclass Sysadmin(models.Model):\n name = models.CharField(max_length=100)\n\n\nclass BaseMachine(models.Model):\n fqdn = models.CharField(max_length=150)\n cpus = models.IntegerField()\n memory =... | [
3,
2
] | [] | [] | [
"django",
"orm",
"python"
] | stackoverflow_0003821116_django_orm_python.txt |
Q:
Python: plot data from a txt file
How do I plot a histogram of this kind of data,
10 apples
3 oranges
6 tomatoes
10 pears
from a text file?
thanks
A:
Here's one way you can assign different colors to the bars. It works with even a variable number of bars.
import numpy as np
import pylab
import matplotlib.cm as cm
arr = np.genfromtxt('data', dtype=None)
n = len(arr)
centers = np.arange(n)
colors = cm.RdYlBu(np.linspace(0, 1, n))
pylab.bar(centers, arr['f0'], color=colors, align='center')
ax = pylab.gca()
ax.set_xticks(centers)
ax.set_xticklabels(arr['f1'], rotation=0)
pylab.show()
A:
As the others suggest, Matplotlib is your friend. Something like
import numpy as np
import matplotlib.pyplot as plt
plt.figure()
indices = np.arange(4)
width = 0.5
plt.bar(indices, [10, 3, 6, 10], width=width)
plt.xticks(indices + width/2, ('Apples', 'Oranges', 'Tomatoes', 'Pears'))
plt.show()
will get you started. Loading the data from a textfile is straight forward.
A:
Felix is right.
Matplotlib is one of the tolls available. Take a look, it has lot of examples. If you're not able to draw a histogram then you could ask another question and I'm sure there will be lots of people to help.
Here are some examples:
http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_demo_extended.html
| Python: plot data from a txt file | How do I plot a histogram of this kind of data,
10 apples
3 oranges
6 tomatoes
10 pears
from a text file?
thanks
| [
"Here's one way you can assign different colors to the bars. It works with even a variable number of bars.\nimport numpy as np\nimport pylab\nimport matplotlib.cm as cm\n\narr = np.genfromtxt('data', dtype=None)\nn = len(arr)\ncenters = np.arange(n)\ncolors = cm.RdYlBu(np.linspace(0, 1, n))\npylab.bar(centers, arr[... | [
6,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003821362_python.txt |
Q:
Are pyc files independent of the interpreter architecture?
From the tests I've done, with the same version of python (same magic number), a 64 bit interpreter can load pyc files made with a 32 bit version of python. And reciprocally I assume.
But is it totally safe? Can this lead to unexpected behavior?
A:
pyc files are stored in the python marshal format.
http://daeken.com/python-marshal-format
it seems that the only issue is with encoded integers which are automatically downgraded to 32 bit integers when you read the pyc on a 32 bit machine.
However the pyc format doesn't include 64bit addresses/offset inside it so the same pyc should run on both 64bit and 32bit interpreters.
| Are pyc files independent of the interpreter architecture? | From the tests I've done, with the same version of python (same magic number), a 64 bit interpreter can load pyc files made with a 32 bit version of python. And reciprocally I assume.
But is it totally safe? Can this lead to unexpected behavior?
| [
"pyc files are stored in the python marshal format.\nhttp://daeken.com/python-marshal-format\nit seems that the only issue is with encoded integers which are automatically downgraded to 32 bit integers when you read the pyc on a 32 bit machine.\nHowever the pyc format doesn't include 64bit addresses/offset inside i... | [
2
] | [] | [] | [
"32_bit",
"64_bit",
"pyc",
"python"
] | stackoverflow_0003821728_32_bit_64_bit_pyc_python.txt |
Q:
Python: create fixed point decimal from two 32-bit ints (one for int portion, one for decimal)
I have a 64-bit timestamp unpacked from a file with binary data, where the top 32 bits are the number of seconds and the bottom 32 bits are the fraction of the second. I'm stuck with how to actually convert the bottom 32 bits into a fraction without looping through it bit-by-bit.
Any suggestions?
For reference, the number 4ca1f350 9481ef80 translates to 1285682000.580107659
Edit:
For context: the data comes from a packet capture device and the documentation I've seen says that it the fractional part has roughly nano-second precision (specifically it outputs 29 of the 32 bits, giving ~2ns).
A:
You can just divide the hex number by the maximum possible to get the correct ratio:
>>> float(0x9481ef80) / 0x100000000
0.58010765910148621
A:
To represent the sum of integral and fractional part with enough precision (32 + 29 = 61 bits), you need a Decimal (28 decimal digits by default, which is enough for 93 bits),
>>> from decimal import Decimal
>>> Decimal(0x9481ef80) / Decimal(2**32) + Decimal(0x4ca1f350)
Decimal('1285682000.580107659101486206')
or Fraction (exact),
>>> from fractions import Fraction
>>> Fraction(0x9481ef80, 2**32) + Fraction(0x4ca1f350)
Fraction(43140329262089183, 33554432)
>>> float(_)
1285682000.5801077
Note that a float uses "IEEE double format" so it can only hold 53 bits of precision:
>>> a = 0x9481ef80 / 2**32 + 0x4ca1f350
>>> b = 0x9481ef90 / 2**32 + 0x4ca1f350
>>> a == b
It is fine if you store the fractional part as its own variable, but if that's the case, why not just keep it as-is?
>>> 0x9481ef80 / 2**32
0.5801076591014862
>>> 0x9481ef90 / 2**32
0.5801076628267765
A:
You didn't say seconds since when. It looks like it's since 1970-01-01. You can calculate a fudge factor that is the number of seconds between the epoch (1970-01-01) and your expected lowest value. Then you adjust each value ... vadj = float(hi32 - fudge) + lo32 / 2.0 ** 32
If the difference between max(hi32) and min(lo32) is less than about 6 days worth (should be enough for a packet capture exercise (?)), then you need only 19 bits for hi32 - fudge. 19 bits + 32 bits is 51 bits -- within the precision of a Python float IIRC.
It's late here so I'm not going to do a detailed analysis but the above should give you the picture.
Edit: why @unwind's answer doesn't work:
>>> a = 0x00000001/4294967296.0 + 0x4ca1f350
>>> b = 0x00000002/4294967296.0 + 0x4ca1f350
>>> b - a
0.0
>>>
Edit 2: What operations do you want to do on a timestamp apart from str(), repr(), timestamp_from_str()? Difference is about all that comes to mind. You can use something like this:
>>> class TS64(object):
... def __init__(self, hi, lo):
... self.hi = hi
... self.lo = lo
... def float_delta(self, other):
... hi_delta = self.hi - other.hi
... # check that abs(hi_delta) is not too large, if you must
... return hi_delta + (self.lo - other.lo) / 4294967296.0
...
>>> a = TS64(0x4ca1f350, 1)
>>> b = TS64(0x4ca1f350, 2)
>>> b.float_delta(a)
2.3283064365386963e-10
>>> repr(_)
'2.3283064365386963e-10'
>>>
About my "if you must" comment: If the observations are more than 6 days apart, do you really need accuracy down to the last (second / 2 ** 32)??? IMHO, if you do float(difference(ts1, ts2)) instead of float(ts1) - float(ts2), you should be OK.
Edit 3: Ambiguity/inconsistency alert
Please edit your question to address the following issues:
You say in a comment that """the documentation I'm looking at says that it the fractional part has nano-second precision (specifically it outputs 29 of the 32 bits)""". Please provide a URL for that documentation.
There are 1000000000 (10**9) nanoseconds in a second. One would expect the fractional part to require math.log(10**9, 2) rounded up (i.e. 29.897352853986263 rounded up i.e. 30) bits, not 29. Please explain.
Please answer: Of the 32 bits available, which 29 or 30 bits contain the fractional part and which 3 or 2 bits are always zero?
Secondly one would expect to convert the nanoseconds to seconds by dividing by 10**9. However your statement in your question """the number 4ca1f350 9481ef80 translates to 1285682000.580107659""" is consistent with dividing by 2**32. In fact 0x9481ef80 is 2,491,543,424 which is greater than twice 10**9. Please explain. What is the source of the "translates to" statement? Do you have any other examples?
| Python: create fixed point decimal from two 32-bit ints (one for int portion, one for decimal) | I have a 64-bit timestamp unpacked from a file with binary data, where the top 32 bits are the number of seconds and the bottom 32 bits are the fraction of the second. I'm stuck with how to actually convert the bottom 32 bits into a fraction without looping through it bit-by-bit.
Any suggestions?
For reference, the number 4ca1f350 9481ef80 translates to 1285682000.580107659
Edit:
For context: the data comes from a packet capture device and the documentation I've seen says that it the fractional part has roughly nano-second precision (specifically it outputs 29 of the 32 bits, giving ~2ns).
| [
"You can just divide the hex number by the maximum possible to get the correct ratio:\n>>> float(0x9481ef80) / 0x100000000\n0.58010765910148621\n\n",
"To represent the sum of integral and fractional part with enough precision (32 + 29 = 61 bits), you need a Decimal (28 decimal digits by default, which is enough f... | [
3,
2,
1
] | [] | [] | [
"fixed_point",
"python"
] | stackoverflow_0003813990_fixed_point_python.txt |
Q:
access a file in python that is created from SunGridEngine
i have a python script, that submits an job to the SGE (Sun Grid Engine).
When the job is done i want to access the output file, generated from the SGE job.
i see with "ls" in the directory that the file is already existing and the job is done, but python needs about 20-30 seconds to get access to that file...
is there a way to detect new created files faster ??
my problem is to differ between "need time to access the file" or "file is not existing"
i tried:
os.path.exist(path)
os.access(path,os.R_OK)
does not solve my problem =(
A:
created a sleep timer which checks every second for access..
after some time (~15s), access is granted and file is usable!
| access a file in python that is created from SunGridEngine | i have a python script, that submits an job to the SGE (Sun Grid Engine).
When the job is done i want to access the output file, generated from the SGE job.
i see with "ls" in the directory that the file is already existing and the job is done, but python needs about 20-30 seconds to get access to that file...
is there a way to detect new created files faster ??
my problem is to differ between "need time to access the file" or "file is not existing"
i tried:
os.path.exist(path)
os.access(path,os.R_OK)
does not solve my problem =(
| [
"created a sleep timer which checks every second for access..\nafter some time (~15s), access is granted and file is usable!\n"
] | [
0
] | [] | [] | [
"python",
"sungridengine"
] | stackoverflow_0002738290_python_sungridengine.txt |
Q:
Are pyc files independent of the minor version of python?
Is it possible and safe to load pyc files made with a different minor version of python?
For instance 2.5.1 with 2.5.5?
My guess is that the magic number does not change with minor versions.
If I refer to this file import.c
the magic number corresponds to the variable pyc_magic ( equals MAGIC or MAGIC+1 )
The file comments say:
Magic word to reject .pyc files generated by other Python versions.
It should change for each incompatible change to the bytecode.
I don't see different number for python minor versions, but can we assume it won't change in the future?
A:
You can't assume that it won't change. Whenever I've needed to distribute .pyc files instead of readable .py files, I've ended up shipping a Python binary too.
| Are pyc files independent of the minor version of python? | Is it possible and safe to load pyc files made with a different minor version of python?
For instance 2.5.1 with 2.5.5?
My guess is that the magic number does not change with minor versions.
If I refer to this file import.c
the magic number corresponds to the variable pyc_magic ( equals MAGIC or MAGIC+1 )
The file comments say:
Magic word to reject .pyc files generated by other Python versions.
It should change for each incompatible change to the bytecode.
I don't see different number for python minor versions, but can we assume it won't change in the future?
| [
"You can't assume that it won't change. Whenever I've needed to distribute .pyc files instead of readable .py files, I've ended up shipping a Python binary too.\n"
] | [
1
] | [] | [] | [
"pyc",
"python",
"version"
] | stackoverflow_0003821926_pyc_python_version.txt |
Q:
using file/db as the buffer for very big numpy array to yield data prevent overflow?
In using the numpy.darray, I met a memory overflow problem due to the size of data,for example:
Suppose I have a 100000000 * 100000000 * 100000000 float64 array data source, when I want to read data and process it in memory with np. It will raise a Memoray Error because it works out all memory for storing such a big array in memory.
Then maybe using a disk file / database as a buffer to store the array is a solution, when I want to use data, it will get the necessary data from the file / database, otherwise, it is just a python object take few memory.
Is it possible write such a adapter?
Thanks.
Rgs,
KC
A:
Take a look at pytables or numpy.memmap, maybe they fit your needs.
best, Peter
A:
If You have matrices with lots of zeros use scipy.sparse.csc_matrix.
It's possible to write everything, for example You can override numarray array class.
| using file/db as the buffer for very big numpy array to yield data prevent overflow? | In using the numpy.darray, I met a memory overflow problem due to the size of data,for example:
Suppose I have a 100000000 * 100000000 * 100000000 float64 array data source, when I want to read data and process it in memory with np. It will raise a Memoray Error because it works out all memory for storing such a big array in memory.
Then maybe using a disk file / database as a buffer to store the array is a solution, when I want to use data, it will get the necessary data from the file / database, otherwise, it is just a python object take few memory.
Is it possible write such a adapter?
Thanks.
Rgs,
KC
| [
"Take a look at pytables or numpy.memmap, maybe they fit your needs. \nbest, Peter\n",
"If You have matrices with lots of zeros use scipy.sparse.csc_matrix. \nIt's possible to write everything, for example You can override numarray array class.\n"
] | [
1,
0
] | [] | [] | [
"memory_management",
"numpy",
"python"
] | stackoverflow_0003818881_memory_management_numpy_python.txt |
Q:
How to format integers greater than 999 in python to look more readable?
I have a bunch of numbers that I want to print to the user. Each number is greater than one million so I want to print it as 1.000.000 or 1,000,000 (any of these forms is valid to me). I want to know if is it possible to format integer numbers this way in python using the built-in formating utilities.
A:
Use locale.format. You will need to setlocale first, since the formatting style is dependent on location (European countries typically use . instead of , for separating the digits, for instance).
>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'English_United Kingdom.1252'
>>> locale.format("%d", 1000000000, grouping=True)
'1,000,000,000'
LC_ALL sets the locale to the default, usually in the LANG environment variable.
A:
In python 3.1 you can use the thousands format specifier:
>>> ',.2f'.format(1234567.89)
'1,234,567.89'
| How to format integers greater than 999 in python to look more readable? | I have a bunch of numbers that I want to print to the user. Each number is greater than one million so I want to print it as 1.000.000 or 1,000,000 (any of these forms is valid to me). I want to know if is it possible to format integer numbers this way in python using the built-in formating utilities.
| [
"Use locale.format. You will need to setlocale first, since the formatting style is dependent on location (European countries typically use . instead of , for separating the digits, for instance).\n>>> import locale\n>>> locale.setlocale(locale.LC_ALL, '')\n'English_United Kingdom.1252'\n>>> locale.format(\"%d\", 1... | [
7,
2
] | [] | [] | [
"python"
] | stackoverflow_0003822006_python.txt |
Q:
when we need chmod +x file.py
i wrote a py script to fetch page from web,it just read write permission enough,so my question is when we need execute permission?
A:
Read/write is enough if you want to run it by typing python file.py. If you want to run it directly as if it were a compiled program, e.g. ./file.py, then you need execute permission (and the appropriate hash-bang line at the top).
A:
It's required to do so if you need to run the script in this way: ./file.py. Keep in mind though, you need to put the path of python at the very top of the script: #!/usr/bin/python.
But wait, you need to make sure you have the proper path, to do that execute: which python.
A:
If you want to be able to run it directly with $ file.py then you'll need the execute bit set. Otherwise you can run it with $ python file.py.
| when we need chmod +x file.py | i wrote a py script to fetch page from web,it just read write permission enough,so my question is when we need execute permission?
| [
"Read/write is enough if you want to run it by typing python file.py. If you want to run it directly as if it were a compiled program, e.g. ./file.py, then you need execute permission (and the appropriate hash-bang line at the top).\n",
"It's required to do so if you need to run the script in this way: ./file.py... | [
6,
5,
0
] | [] | [] | [
"chmod",
"permissions",
"python"
] | stackoverflow_0003822336_chmod_permissions_python.txt |
Q:
Python: interrupt execution with key and run again
how can I interrupt python execution with a key and continue to run when the key is pressed again ?
thanks
A:
If you're using pygame, you can check for the key event and use a boolean switch.
def check_pause(self):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
self.pause = not self.pause
Something like that, attached to
while True:
self.check_pause()
if self.pause:
continue
# Main loop of program goes here.
| Python: interrupt execution with key and run again | how can I interrupt python execution with a key and continue to run when the key is pressed again ?
thanks
| [
"If you're using pygame, you can check for the key event and use a boolean switch.\ndef check_pause(self):\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_p:\n self.pause = not self.pause\n\nSomething like that, attached to\nwhile ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003822485_python.txt |
Q:
Why must I use Qt Designer 2.7 with Python 2.7?
Why can't I use other Qt series with different Python releases?
A:
You can. If you have a specific version of Qt you would like to use, you can either download a matching PyQt version from Riverbank's download site or you can compile your own version of PyQt. I've had to build them from scratch a few times when the provided binaries didn't match the Qt/Python versions I wanted to use. It's a bit of a hassle to compile but it's definitely possible.
Also, note that the up-and-coming PySide library is an alternative Qt binding for Python that looks like it has a good chance of supplanting PyQt (due to looser licensing constraints).
Generally speaking, Qt Designer is an optional and independent component from PyQt. You can use it to create your .ui files but after that, it's up to the developer to determine how to use them... either generate Python code from them with pyuic4 or load them dynamically. As long as the format of the resulting .ui files are compatible with your version of PyQt, it shouldn't matter which Designer version you're using (though I would strongly recommend you use the version matching the Qt version PyQt is linked against).
| Why must I use Qt Designer 2.7 with Python 2.7? | Why can't I use other Qt series with different Python releases?
| [
"You can. If you have a specific version of Qt you would like to use, you can either download a matching PyQt version from Riverbank's download site or you can compile your own version of PyQt. I've had to build them from scratch a few times when the provided binaries didn't match the Qt/Python versions I wanted to... | [
0
] | [] | [] | [
"python",
"qt",
"qt_creator"
] | stackoverflow_0003820343_python_qt_qt_creator.txt |
Q:
Pyqt tabs like in Google Chrome
I would like to have my pyqt aplication have tabs in the menu bar like Google Chrome :)
Any suggestions or a simple example on how to do it?
I did find these relevant link:
- http://ivan.fomentgroup.org/blog/2009/03/29/instant-chrome/
A:
You have to use the Qt.FramelessWindowHint for that, and then create your own Max, Min, Close buttons as Widgets and add them there. I have a good working toolkit for these types of softwares: http://traipse.assembla.com/spaces/ghostqt
In your case you should reclass the resizeEvent so you can change the flags. If the window is maximized you will not need to worry about moving it around, but if it is not maximized you can remove the Qt.FramelessWindowHint flag and get your title bar back; just like Chrome does.
Is that what you are looking for?
A:
If I understand correctly, just create a QWindow that contains a QTabBar widget(and not a QMenuBar, or simply use a QTabWidget as your main program widget.
A:
you need to do the following:
remove window border (FramelessWindowHint)
Implement your own window moving and resizing code
Insert tabbar on the top, and add buttons for close etc. to it (or create a frame that will contain the tabbar and buttons)
And that's all that was done in Webbie (the link you provided) :)
| Pyqt tabs like in Google Chrome | I would like to have my pyqt aplication have tabs in the menu bar like Google Chrome :)
Any suggestions or a simple example on how to do it?
I did find these relevant link:
- http://ivan.fomentgroup.org/blog/2009/03/29/instant-chrome/
| [
"You have to use the Qt.FramelessWindowHint for that, and then create your own Max, Min, Close buttons as Widgets and add them there. I have a good working toolkit for these types of softwares: http://traipse.assembla.com/spaces/ghostqt\nIn your case you should reclass the resizeEvent so you can change the flags. I... | [
3,
2,
2
] | [] | [] | [
"pyqt",
"python",
"qt",
"tabs",
"user_interface"
] | stackoverflow_0003630851_pyqt_python_qt_tabs_user_interface.txt |
Q:
Assigning to a dict
Forgive me if this has been asked before. I did not know how to search for it.
I'm quite familiar with the following idiom:
def foo():
return [1,2,3]
[a,b,c] = foo()
(d,e,f) = foo()
wherein the values contained within the left hand side will be assigned based upon the values returned from the function on the right.
I also know you can do
def bar():
return {'a':1,'b':2,'c':3}
(one, two, three) = bar()
[four, five, six] = bar()
wherein the keys returned from the right hand side will be assigned to the containers on the left hand side.
However, I'm curious, is there a way to do the following in Python 2.6 or earlier:
{letterA:one, letterB:two, letterC:three} = bar()
and have it work in the same manner that it works for sequences to sequences? If not, why? Naively attempting to do this as I've written it will fail.
A:
Dictionary items do not have an order, so while this works:
>>> def bar():
... return dict(a=1,b=2,c=3)
>>> bar()
{'a': 1, 'c': 3, 'b': 2}
>>> (lettera,one),(letterb,two),(letterc,three) = bar().items()
>>> lettera,one,letterb,two,letterc,three
('a', 1, 'c', 3, 'b', 2)
You can see that you can't necessarily predict how the variables will be assigned. You could use collections.OrderedDict in Python 3 to control this.
A:
If you modify bar() to return a dict (as suggested by @mikerobi), you might want to still preserve keyed items that are in your existing dict. In this case, use update:
mydict = {}
mydict['existing_key'] = 100
def bar_that_says_dict():
return { 'new_key': 101 }
mydict.update(bar_that_says_dict())
print mydict
This should output a dict with both existing_key and new_key. If mydict had a key of new_key, then the update would overwrite it with the value returned from bar_that_says_dict.
| Assigning to a dict | Forgive me if this has been asked before. I did not know how to search for it.
I'm quite familiar with the following idiom:
def foo():
return [1,2,3]
[a,b,c] = foo()
(d,e,f) = foo()
wherein the values contained within the left hand side will be assigned based upon the values returned from the function on the right.
I also know you can do
def bar():
return {'a':1,'b':2,'c':3}
(one, two, three) = bar()
[four, five, six] = bar()
wherein the keys returned from the right hand side will be assigned to the containers on the left hand side.
However, I'm curious, is there a way to do the following in Python 2.6 or earlier:
{letterA:one, letterB:two, letterC:three} = bar()
and have it work in the same manner that it works for sequences to sequences? If not, why? Naively attempting to do this as I've written it will fail.
| [
"Dictionary items do not have an order, so while this works:\n>>> def bar():\n... return dict(a=1,b=2,c=3)\n>>> bar()\n{'a': 1, 'c': 3, 'b': 2}\n>>> (lettera,one),(letterb,two),(letterc,three) = bar().items()\n>>> lettera,one,letterb,two,letterc,three\n('a', 1, 'c', 3, 'b', 2)\n\nYou can see that you can't nece... | [
4,
1
] | [
"No, if you can not change bar function, you could create a dict from the output pretty easily.\nThis is the most compact solution. But I would prefer to modify the bar function to return a dict.\ndict(zip(['one', 'two', 'three'], bar()))\n\n"
] | [
-1
] | [
"dictionary",
"python"
] | stackoverflow_0003822519_dictionary_python.txt |
Q:
"chunksize" parameter in multiprocessing.Pool.map
If I have a pool object with 2 processors for example:
p=multiprocessing.Pool(2)
and I want to iterate over a list of files on directory and use the map function
could someone explain what is the chunksize of this function:
p.map(func, iterable[, chunksize])
If I set the chunksize for example to 10 does that means every 10 files should be processed with one processor?
A:
Looking at the documentation for Pool.map it seems you're almost correct: the chunksize parameter will cause the iterable to be split into pieces of approximately that size, and each piece is submitted as a separate task.
So in your example, yes, map will take the first 10 (approximately), submit it as a task for a single processor... then the next 10 will be submitted as another task, and so on. Note that it doesn't mean that this will make the processors alternate every 10 files, it's quite possible that processor #1 ends up getting 1-10 AND 11-20, and processor #2 gets 21-30 and 31-40.
| "chunksize" parameter in multiprocessing.Pool.map | If I have a pool object with 2 processors for example:
p=multiprocessing.Pool(2)
and I want to iterate over a list of files on directory and use the map function
could someone explain what is the chunksize of this function:
p.map(func, iterable[, chunksize])
If I set the chunksize for example to 10 does that means every 10 files should be processed with one processor?
| [
"Looking at the documentation for Pool.map it seems you're almost correct: the chunksize parameter will cause the iterable to be split into pieces of approximately that size, and each piece is submitted as a separate task.\nSo in your example, yes, map will take the first 10 (approximately), submit it as a task for... | [
52
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0003822512_multiprocessing_python.txt |
Q:
Python, convert a number to a string 'as is'
Using Python 2.6
I want to be able to convert numbers such as 00000, 000.00004 and 001 to strings. Such that each string is '00000', '000.00004' and '001' respectively.
It is also necessary that the way to do this is the same with all numbers, and also copes when letters are fed into it. E.g. foo should become 'foo', 2bar should be become '2bar' but 001 should still be '001'.
Using str([object]) the above numbers would go to '0', '4e-05' and '1' respectively.
Any ideas?
EDIT:
@unholysampler (and everyone else) you are of course right.
I was simply getting confused because Sqlite3 was taking strings and then converting them to integers or floating point numbers when putting them into it's database, despite it being declared as a string column. But this is another issue entirely.
SECOND EDIT:
If anybody was curious why Sqlite3 was doing that, it was because I had actually set the column to be of type 'STRING' in the schema, where it should have been type 'TEXT' (see http://www.sqlite.org/datatype3.html) - this was combined with Sqlite's "dynamic typing" (see http://www.sqlite.org/faq.html#q3) and was enough to make me confused :-)
Thank you for giving nice answers anyway :D
A:
There is no number 0000 or 001. There is only 0 and 1. If you want to produce a string representation of a number, you can use string formatting to pad zeros.
n = 1
print '%03d' % n //001
A:
The first step would be: however you are getting a number that you think should be 00000 instead of 0 ... don't actually convert it to a number. Just keep it as a string.
| Python, convert a number to a string 'as is' | Using Python 2.6
I want to be able to convert numbers such as 00000, 000.00004 and 001 to strings. Such that each string is '00000', '000.00004' and '001' respectively.
It is also necessary that the way to do this is the same with all numbers, and also copes when letters are fed into it. E.g. foo should become 'foo', 2bar should be become '2bar' but 001 should still be '001'.
Using str([object]) the above numbers would go to '0', '4e-05' and '1' respectively.
Any ideas?
EDIT:
@unholysampler (and everyone else) you are of course right.
I was simply getting confused because Sqlite3 was taking strings and then converting them to integers or floating point numbers when putting them into it's database, despite it being declared as a string column. But this is another issue entirely.
SECOND EDIT:
If anybody was curious why Sqlite3 was doing that, it was because I had actually set the column to be of type 'STRING' in the schema, where it should have been type 'TEXT' (see http://www.sqlite.org/datatype3.html) - this was combined with Sqlite's "dynamic typing" (see http://www.sqlite.org/faq.html#q3) and was enough to make me confused :-)
Thank you for giving nice answers anyway :D
| [
"There is no number 0000 or 001. There is only 0 and 1. If you want to produce a string representation of a number, you can use string formatting to pad zeros.\nn = 1\nprint '%03d' % n //001\n\n",
"The first step would be: however you are getting a number that you think should be 00000 instead of 0 ... don't actu... | [
8,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003822858_python_sqlite.txt |
Q:
Python App Engine: Task Queues
I need to import some data to show it for user but page execution time exceeds 30 second limit. So I decided to split my big code into several tasks and try Task Queues. I add about 10-20 tasks to queue and app engine executes tasks in parallel while user is waiting for data. How can I determine that my tasks are completed to show user data ASAP? Can I somehow iterate over active tasks?
A:
I've solved this in the past by keeping the status for the tasks in memcached, and polling (via Ajax) to determine when the tasks are finished.
If you go this way, it's best if you can always "manually" determine the status of the tasks without looking in memcached, since there's always the (slim) chance that memcache will go down or will get cleared or something as a task is running.
| Python App Engine: Task Queues | I need to import some data to show it for user but page execution time exceeds 30 second limit. So I decided to split my big code into several tasks and try Task Queues. I add about 10-20 tasks to queue and app engine executes tasks in parallel while user is waiting for data. How can I determine that my tasks are completed to show user data ASAP? Can I somehow iterate over active tasks?
| [
"I've solved this in the past by keeping the status for the tasks in memcached, and polling (via Ajax) to determine when the tasks are finished. \nIf you go this way, it's best if you can always \"manually\" determine the status of the tasks without looking in memcached, since there's always the (slim) chance that... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003821636_google_app_engine_python.txt |
Q:
What do we call this (new?) higher-order function?
I am trying to name what I think is a new idea for a higher-order function. To the important part, here is the code in Python and Haskell to demonstrate the concept, which will be explained afterward.
Python:
>>> def pleat(f, l):
return map(lambda t: f(*t), zip(l, l[1:]))
>>> pleat(operator.add, [0, 1, 2, 3])
[1, 3, 5]
Haskell:
Prelude> let pleatWith f xs = zipWith f xs (drop 1 xs)
Prelude> pleatWith (+) [0,1,2,3]
[1,3,5]
As you may be able to infer, the sequence is being iterated through, utilizing adjacent elements as the parameters for the function you pass it, projecting the results into a new sequence. So, has anyone seen the functionality we've created? Is this familiar at all to those in the functional community? If not, what do we name it?
---- Update ----
Pleat wins!
Prelude> let pleat xs = zip xs (drop 1 xs)
Prelude> pleat [1..4]
[(1,2),(2,3),(3,4)]
Prelude> let pleatWith f xs = zipWith f xs (drop 1 xs)
Prelude> pleatWith (+) [1..4]
[3,5,7]
A:
Hmm... a counterpoint.
(`ap` tail) . zipWith
doesn't deserve a name.
BTW, quicksilver says:
zip`ap`tail
The Aztec god of consecutive numbers
A:
Since it's similar to "fold" but doesn't collapse the list into a single value, how about "crease"? If you keep "creasing", you end up "folding" (sort of).
We could go with a cooking metaphor and call it "pinch", like pinching the crust of a pie, though this might suggest a circular zipping, where the last element of the list is paired with the first.
def pinch(f, l):
return map(lambda t: f(*t), zip(l, l[1:]+l[:1]))
(If you only like one of "crease" or "pinch", please note so as a comment. Should these be separate suggestions?)
A:
In Python the meld equivalent is in the itertools receipes and called pairwise.
from itertools import starmap, izp, tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
So I would call it:
def pairwith(func, seq):
return starmap(func, pairwise(seq))
I think this makes sense because when you call it with the identity function, it simply returns pairs.
A:
Here's another implementation for Python which works if l is a generator too
import itertools as it
def apply_pairwise(f, l):
left, right = it.tee(l)
next(right)
return it.starmap(f, it.izip(left, right))
I think apply_pairwise is a better name
A:
I really can't see any codified names for this anywhere in Python, that's for sure. "Merge" is good but spoken for in a variety of other contexts. "Plow" tends to be unused and supplies a great visual of pushing steadily through a line of soil. Maybe I've just spent too much time gardening.
I also expanded the principle to allow functions that receive any number of parameters.
You might also consider: Pleat. It describes well the way you're taking a list (like a long strand of fabric) and bunching segments of it together.
import operator
def stagger(l, w):
if len(l)>=w:
return [tuple(l[0:w])]+stagger(l[1:], w)
return []
def pleat(f, l, w=2):
return map(lambda p: f(*p), stagger(l, w))
print pleat(operator.add, range(10))
print pleat(lambda x, y, z: x*y/z, range(3, 13), 3)
print pleat(lambda x: "~%s~"%(x), range(10), 1)
print pleat(lambda a, b, x, y: a+b==x+y, [3, 2, 4, 1, 5, 0, 9, 9, 0], 4)
A:
zipWithTail or adjacentPairs.
A:
I vote for smearWith or smudgeWith because it's like you are smearing/smudging the operation across the list.
A:
this seems like ruby's each_cons
ruby-1.9.2-p0 > (1..10).each_cons(2).to_a
=> [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10]]
A:
This reminds me of convolution from image processing. But not sure if this is mathematically correct.
A:
The generalized variant of the plain zip version of this is what I would think of as window. Not at a ghci terminal right now, but I think window n = take n . tails. Then your function is zipWith (\[x,yj -> f x y) . window 2. This sort of style naturally works better when f is of type [a] -> b.
A:
in C++ Standard Template Library, it is called adjacent_difference (though the operator can be any operation, not just subtraction)
A:
So because there seems to be no name for this I suggest 'merger' or simple 'merge' because you are merging adjacent values together.
So merge is already taken so I now suggest 'meld' (or 'merger' still but that may be too close to 'merge')
For example:
meld :: (a -> a -> b) -> [a] -> [b]
meld _ [] = []
meld f xs = zipWith f (init xs) (tail xs)
Which can be used as:
> meld (+) [1..10]
[3,5,7,9,11,13,15,17,19]
> meld compare "hello world"
[GT,LT,EQ,LT,GT,LT,GT,LT,GT,GT]
Where the second example makes no real sense but makes a cool example.
A:
Using Mathematica
Plus @@@ Partition[{0, 1, 2, 3}, 2, 1]
or either of these more verbose alternatives
Apply[Plus, Partition[{0, 1, 2, 3}, 2, 1], {1}]
Map[Apply[Plus, #] &, Partition[{0, 1, 2, 3}, 2, 1]]
I have used and enjoyed this higher order function in many languages but I have enjoyed it the most in Mathematica; it seems succinct and flexible broken down into Partition and Apply with levelspec option.
A:
I'd be tempted to call it contour as I've used it for "contour" processing in music software - at the time I called it twomap or something silly like that.
There are also two specific named 'contours' in music processing one is gross contour - does the pitch go up or down. The other is refined contour where the the contour is either up, down, leap up or leap down, though I can't seem to find a reference for how large the semitone difference has to be to make a leap.
A:
Nice idiom! I just needed to use this in Perl to determine the time between sequential events. Here's what I ended up with.
sub pinch(&@) {
my ( $f, @list ) = @_;
no strict "refs";
use vars qw( $a $b );
my $caller = caller;
local( *{$caller . "::a"} ) = \my $a;
local( *{$caller . "::b"} ) = \my $b;
my @res;
for ( my $i = 0; $i < @list - 1; ++$i ) {
$a = $list[$i];
$b = $list[$i + 1];
push( @res, $f->() );
}
wantarray ? @res : \@res;
}
print join( ",", pinch { $b - $a } qw( 1 2 3 4 5 6 7 ) ), $/;
# ==> 1,1,1,1,1,1
The implementation could probably be prettier if I'd made it dependent on List::Util, but... meh!
A:
BinaryOperate or BinaryMerge
| What do we call this (new?) higher-order function? | I am trying to name what I think is a new idea for a higher-order function. To the important part, here is the code in Python and Haskell to demonstrate the concept, which will be explained afterward.
Python:
>>> def pleat(f, l):
return map(lambda t: f(*t), zip(l, l[1:]))
>>> pleat(operator.add, [0, 1, 2, 3])
[1, 3, 5]
Haskell:
Prelude> let pleatWith f xs = zipWith f xs (drop 1 xs)
Prelude> pleatWith (+) [0,1,2,3]
[1,3,5]
As you may be able to infer, the sequence is being iterated through, utilizing adjacent elements as the parameters for the function you pass it, projecting the results into a new sequence. So, has anyone seen the functionality we've created? Is this familiar at all to those in the functional community? If not, what do we name it?
---- Update ----
Pleat wins!
Prelude> let pleat xs = zip xs (drop 1 xs)
Prelude> pleat [1..4]
[(1,2),(2,3),(3,4)]
Prelude> let pleatWith f xs = zipWith f xs (drop 1 xs)
Prelude> pleatWith (+) [1..4]
[3,5,7]
| [
"Hmm... a counterpoint.\n(`ap` tail) . zipWith\n\ndoesn't deserve a name.\nBTW, quicksilver says:\n zip`ap`tail\n\nThe Aztec god of consecutive numbers\n",
"Since it's similar to \"fold\" but doesn't collapse the list into a single value, how about \"crease\"? If you keep \"creasing\", you end up \"folding\" (sor... | [
17,
6,
6,
5,
4,
2,
2,
2,
2,
2,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"functional_programming",
"haskell",
"higher_order_functions",
"python",
"theory"
] | stackoverflow_0003774247_functional_programming_haskell_higher_order_functions_python_theory.txt |
Q:
Python ranking algorithm with 30 levels
I trying find a simple python-based algorithmic ranking system.
Here's the scenario:
There will be 30 levels, level 1 starts at 0 points. 2000 points are required to achieve level 30.
More points will be required as the levels progress.
For example, to go from level 1 to 2 might take 3 points. Level 2 to 3 might take 5 additional points.
Level 29-30 might take 1200 additional points.
Since the score will be calculated on the fly, I also need a way to determine which level the player is at. For example, what level is a person with 358 points?
I could set the points manually but the 2000 point cap will fluctuate from day to day so that is not an idealistic option.
I was thinking something similar to Google's Pagerank (1-10) where it's easy to get from 0 to 4 but 9-10 is a very hard accomplishment.
Any simple snippets or tippets?
Thanks
A:
The usual solution is to use a logarithmic scale. If you use log base 2, then each level needs twice as many points. If you use a log base 10, each level needs 10 times the points. This way, you can "bend" the curve. See the Wikipedia page for the math.
A:
Use a logarithmic scale. If you want a code example:
base = 2 # change to change the rate at which you go through the levels
levels = 30
finalPoints = 2000
scale = levels/math.log(finalPoints, base)
level = math.floor(scale*math.log(points, base))
| Python ranking algorithm with 30 levels | I trying find a simple python-based algorithmic ranking system.
Here's the scenario:
There will be 30 levels, level 1 starts at 0 points. 2000 points are required to achieve level 30.
More points will be required as the levels progress.
For example, to go from level 1 to 2 might take 3 points. Level 2 to 3 might take 5 additional points.
Level 29-30 might take 1200 additional points.
Since the score will be calculated on the fly, I also need a way to determine which level the player is at. For example, what level is a person with 358 points?
I could set the points manually but the 2000 point cap will fluctuate from day to day so that is not an idealistic option.
I was thinking something similar to Google's Pagerank (1-10) where it's easy to get from 0 to 4 but 9-10 is a very hard accomplishment.
Any simple snippets or tippets?
Thanks
| [
"The usual solution is to use a logarithmic scale. If you use log base 2, then each level needs twice as many points. If you use a log base 10, each level needs 10 times the points. This way, you can \"bend\" the curve. See the Wikipedia page for the math.\n",
"Use a logarithmic scale. If you want a code example:... | [
3,
3
] | [] | [] | [
"algorithm",
"python",
"ranking"
] | stackoverflow_0003823243_algorithm_python_ranking.txt |
Q:
Filtering a String for a Set of Characters
this is from the 'python cookbook' but isn't explained that well.
allchars = string.maketrans('','')
def makefilter(keep):
delchars = allchars.translate(allchars, keep)
def thefilter(s):
return s.translate(allchars,delchars)
return thefilter
if __name__ == '__main__':
just_vowels = makefilter('aeiou')
print just_vowels('four score and seven years ago')
print just_vowels('tigere, igers, bigers')
my question is, how does thefilters 's' get passed in as a parameter?
A:
makefilter returns a function.
In the example code:
just_vowels = makefilter('aeiou')
the variable just_vowels now refers to a function based on thefilter.
The code:
print just_vowels('tigere, igers, bigers')
is calling that function, and setting its s parameter to the string 'tigere, igers, bigers'.
A:
It's possible to simplify that cookbook code using a list comprehension or generator expression:
def make_filter(keep):
def the_filter(string):
return ''.join(char for char in string if char in keep)
return the_filter
This will work the same way as the provided makefilter.
>>> just_vowels = make_filter('aeiou')
>>> just_vowels('four score and seven years ago')
'ouoeaeeeaao'
>>> just_vowels('tigere, igers, bigers')
'ieeieie'
Like Richie explained, it will dynamically create a function, which you can later call on a string. The (char for char in string if char in keep) bit of code creates a generator which will iterate over the characters of the original string and perform the filtering. ''.join(...) then combines those characters back into a string.
Personally, I find that level of abstraction (writing a function to return a function) to be overkill for this sort of problem. It's a question of taste, but I think your code would be clearer if you just call the significant line directly:
>>> string = 'tigere, igers, bigers'
>>> keep = 'aeiou'
>>> ''.join(char for char in string if char in keep)
'ieeieie'
| Filtering a String for a Set of Characters | this is from the 'python cookbook' but isn't explained that well.
allchars = string.maketrans('','')
def makefilter(keep):
delchars = allchars.translate(allchars, keep)
def thefilter(s):
return s.translate(allchars,delchars)
return thefilter
if __name__ == '__main__':
just_vowels = makefilter('aeiou')
print just_vowels('four score and seven years ago')
print just_vowels('tigere, igers, bigers')
my question is, how does thefilters 's' get passed in as a parameter?
| [
"makefilter returns a function.\nIn the example code:\njust_vowels = makefilter('aeiou')\n\nthe variable just_vowels now refers to a function based on thefilter.\nThe code:\nprint just_vowels('tigere, igers, bigers')\n\nis calling that function, and setting its s parameter to the string 'tigere, igers, bigers'.\n",... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003822919_python.txt |
Q:
Django, Python calling Python code without waiting for response?
I am using Django and am making some long running processes that I am just interacting with through my web user interface. Such as, they would be running all the time, checking a database value every few minutes and stopping only if this has changed (would be boolean true false). So, I want to be able to use Django to interact with these, however am unsure of the way to do this. When I used to use PHP I had some method of doing this, figure it would be even easier to do in Python but am not able to find anything on this with my searches.
Basically, all I want to be able to do is to execute python code without waiting for it to finish, so it just begins execute then goes on to do whatever else it needs for django, quickly returning a new page to the user.
I know that there are ways to call an external program, so I suppose that may be the only way to go? Is there a way to do this with just calling other python code?
Thanks for any advice.
A:
Can't vouch for it because I haven't used it yet, but "Celery" does pretty much what you're asking for and was originally built specifically for Django.
http://celeryproject.org/
Their example showing a simple task adding two numbers:
from celery.decorators import task
@task
def add(x, y):
return x + y
You can execute the task in the background, or wait for it to finish:
>>> result = add.delay(8, 8)
>>> result.wait() # wait for and return the result
16
You'll probably need to install RabbitMQ also to get it working, so it might be more complicated of a solution than you're looking for, but it will achieve your goals.
A:
You want an asynchronous message manager. I've got a tutorial on integrating Gearman with Django. Any pickleable Python object can be sent to Gearman, which will do all the work and post the results wherever you want; the tutorial includes examples of posting back to the Django database (it also shows how to use the ORM outside of Django).
| Django, Python calling Python code without waiting for response? | I am using Django and am making some long running processes that I am just interacting with through my web user interface. Such as, they would be running all the time, checking a database value every few minutes and stopping only if this has changed (would be boolean true false). So, I want to be able to use Django to interact with these, however am unsure of the way to do this. When I used to use PHP I had some method of doing this, figure it would be even easier to do in Python but am not able to find anything on this with my searches.
Basically, all I want to be able to do is to execute python code without waiting for it to finish, so it just begins execute then goes on to do whatever else it needs for django, quickly returning a new page to the user.
I know that there are ways to call an external program, so I suppose that may be the only way to go? Is there a way to do this with just calling other python code?
Thanks for any advice.
| [
"Can't vouch for it because I haven't used it yet, but \"Celery\" does pretty much what you're asking for and was originally built specifically for Django.\nhttp://celeryproject.org/\nTheir example showing a simple task adding two numbers:\nfrom celery.decorators import task\n\n@task\ndef add(x, y):\n return x +... | [
6,
0
] | [] | [] | [
"django",
"long_running_processes",
"python"
] | stackoverflow_0003806574_django_long_running_processes_python.txt |
Q:
Python & C#: Is IronPython absolutely necessary?
I'm primarily a C# programmer, but have been left with a project that leaves me with 2 options:
Call out to a python script (saved as a .py file) and process the return value, OR...
Rewrite the whole python script (involving 6 .py files in total) in C#.
Naturally, Option 2 is a MAJOR waste of time if I can simply implement Option 1. Moreover, Option 1 is a learning opportunity, while Option 2 is a total geek copout.
So, my question is this: Is there a way to build a C# Process object to trigger the .py file's script AND catch the script's return value without using IronPython? I don't have anything against possibly using IronPython, I just need a solution as soon as possible, so if I can sidestep the I.P. learning curve until I have less urgent work to do, that would be optimal.
Thanks.
A:
Use Process.Start to run the Python script. In the ProcessStartInfo object, you specify:
FileName = the path and file name of the Python script.
Arguments = any arguments that you want to pass to the script.
RedirectStandardOutput = true (and RedirectStandardError if needed)
UseShellExecute = false
Then you get a Process object on which you can do some things, in particular:
Use Process.StandardOutput to read the Python script’s output. You could, for example, call ReadToEnd() on this to get a single string containing the entire output, or call ReadLine() in a loop.
Use Process.ExitCode to read the return code of the script.
Use Process.WaitForExit to wait for the script to finish.
A:
Use System.Diagnostics.Process to run the Python script and then use Process.ExitCode to retrieve the return value of the script once it's done:
// Start the script
var process = System.Diagnostics.Process.Start("python MyScript.py");
// Wait for the script to run
process.WaitForExit();
int returnVal = process.ExitCode;
A:
You can do something like:
Process py = new Process();
py.StartInfo.FileName = "python.exe";
py.StartInfo.Arguments = "c:\\python\\script.py";
py.StartInfo.UseShellExecute = false;
py.StartInfo.CreateNoWindow = true;
py.StartInfo.RedirectStandardOutput = true;
py.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
py.Start();
py.BeginOutputReadLine();
py.WaitForExit();
py.Close();
But, I must say that you can have multiple systems, based in different languages, since they can understand what each one says. I mean, there're some standards that can be thought to glue the whole thing. The python system can feed the C# system with JSON, XML, or some other standard, in a webservice built in Python, for example. Sometimes it's better to review your architecture.
| Python & C#: Is IronPython absolutely necessary? | I'm primarily a C# programmer, but have been left with a project that leaves me with 2 options:
Call out to a python script (saved as a .py file) and process the return value, OR...
Rewrite the whole python script (involving 6 .py files in total) in C#.
Naturally, Option 2 is a MAJOR waste of time if I can simply implement Option 1. Moreover, Option 1 is a learning opportunity, while Option 2 is a total geek copout.
So, my question is this: Is there a way to build a C# Process object to trigger the .py file's script AND catch the script's return value without using IronPython? I don't have anything against possibly using IronPython, I just need a solution as soon as possible, so if I can sidestep the I.P. learning curve until I have less urgent work to do, that would be optimal.
Thanks.
| [
"Use Process.Start to run the Python script. In the ProcessStartInfo object, you specify:\n\nFileName = the path and file name of the Python script.\nArguments = any arguments that you want to pass to the script.\nRedirectStandardOutput = true (and RedirectStandardError if needed)\nUseShellExecute = false\n\nThen y... | [
6,
2,
2
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0003823880_c#_python.txt |
Q:
More pythonic way to write this?
I have this code here:
import re
def get_attr(str, attr):
m = re.search(attr + r'=(\w+)', str)
return None if not m else m.group(1)
str = 'type=greeting hello=world'
print get_attr(str, 'type') # greeting
print get_attr(str, 'hello') # world
print get_attr(str, 'attr') # None
Which works, but I am not particularly fond of this line:
return None if not m else m.group(1)
In my opinion this would look cleaner if we could use a ternary operator:
return (m ? m.group(1) : None)
But that of course isn't there. What do you suggest?
A:
Python has a ternary operator. You're using it. It's just in the X if Y else Z form.
That said, I'm prone to writing these things out. Fitting things on one line isn't so great if you sacrifice clarity.
def get_attr(str, attr):
m = re.search(attr + r'=(\w+)', str)
if m:
return m.group(1)
return None
A:
Another option is to use:
return m.group(1) if m else m
It's explicit, and you don't have to do any logic puzzles to understand it :)
A:
return m and m.group(1)
would be one Pythonic way to do it.
If m is None (or something else that evaluates "falsely"), it returns m, but if m is "true-ish", then it returns m.group(1).
A:
What you have there is python's conditional operator. IMO it's perfectly pythonic as-is and needs no change. Remember, explicit is better than implicit. What you have now is readable and instantly understandable.
| More pythonic way to write this? | I have this code here:
import re
def get_attr(str, attr):
m = re.search(attr + r'=(\w+)', str)
return None if not m else m.group(1)
str = 'type=greeting hello=world'
print get_attr(str, 'type') # greeting
print get_attr(str, 'hello') # world
print get_attr(str, 'attr') # None
Which works, but I am not particularly fond of this line:
return None if not m else m.group(1)
In my opinion this would look cleaner if we could use a ternary operator:
return (m ? m.group(1) : None)
But that of course isn't there. What do you suggest?
| [
"Python has a ternary operator. You're using it. It's just in the X if Y else Z form.\nThat said, I'm prone to writing these things out. Fitting things on one line isn't so great if you sacrifice clarity.\ndef get_attr(str, attr):\n m = re.search(attr + r'=(\\w+)', str)\n if m:\n return m.group(1)\n... | [
10,
4,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0003823980_python.txt |
Q:
Running Python command-line utility from Java
I developed a command-line utility which needs to be called from a Java GUI application. The team in charge on the Java GUI would like to bind my command-line application to a button in the GUI; the Python application is such that at the time we have no time or interest in rewriting it in Java.
I have no experience whatsoever in Java, so I ask you:
What is the best way to bind a command-line based Python application to a button in a Java-based GUI application?
I am very concerned about exception management (how to tell Java that Python failed).
Thanks.
A:
You should be able to execute a spawned process from Java using Runtime.exec(). Here's some examples.
Make sure you capture the stdout and stderr (concurrently - see this answer for more details) so you can report on errors. You can capture the exit code of the application, so make sure that the application itself correctly reports errors. The error code would be a more reliable way of detecting errors (I would suspect) thatn parsing the output streams.
A:
Have you considered jython? You can:
1) use it to run python scripts (allowing it to call Java classes)
2) compile python into class files, making them usable by normal Java code without jython being present at runtime
I've only used it in the first pattern, but I've seen tonnes of docs on the second.
A:
I agree with phlip - you can create a scripting engine in Java and use that to call your Python code. Providing that your python code doesn't use any unusual OS-specific library calls or DLLs, this should work fine. This link: http://jythonpodcast.hostjava.net/jythonbook/chapter10.html should give you more information on the exact mechanism you need.
| Running Python command-line utility from Java | I developed a command-line utility which needs to be called from a Java GUI application. The team in charge on the Java GUI would like to bind my command-line application to a button in the GUI; the Python application is such that at the time we have no time or interest in rewriting it in Java.
I have no experience whatsoever in Java, so I ask you:
What is the best way to bind a command-line based Python application to a button in a Java-based GUI application?
I am very concerned about exception management (how to tell Java that Python failed).
Thanks.
| [
"You should be able to execute a spawned process from Java using Runtime.exec(). Here's some examples.\nMake sure you capture the stdout and stderr (concurrently - see this answer for more details) so you can report on errors. You can capture the exit code of the application, so make sure that the application itsel... | [
1,
0,
0
] | [] | [] | [
"java",
"python",
"scripting"
] | stackoverflow_0003824249_java_python_scripting.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.