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:
Is it possible to install an msi using python?
Is it possible to write a script in python that installs an msi? Or
is it possible to make it through any other script?
A:
You can use the antiquated os.system('msiexec /i whatever.msi'), or, better, the subprocess equivalent subprocess.call -- in either case, you can also add whatever further msiexec flags or arguments you desire (documentation in abundance here).
A:
AFAIK, it's possible to use WMI in Python, so you should be able to install MSI files using the Win32_Product.Install method.
| Is it possible to install an msi using python? | Is it possible to write a script in python that installs an msi? Or
is it possible to make it through any other script?
| [
"You can use the antiquated os.system('msiexec /i whatever.msi'), or, better, the subprocess equivalent subprocess.call -- in either case, you can also add whatever further msiexec flags or arguments you desire (documentation in abundance here).\n",
"AFAIK, it's possible to use WMI in Python, so you should be able to install MSI files using the Win32_Product.Install method.\n"
] | [
7,
0
] | [] | [] | [
"python",
"scripting"
] | stackoverflow_0003130252_python_scripting.txt |
Q:
How do I create a unique property in python on google app engine?
In some database technologies, for a attribute in a record, you can guarantee uniqueness of that attribute within the entire database. An example of this might be a email_address attribute in a User record. By setting email_address to unique, you guarantee that a particular email address can only appear in one record in the entire database.
Is there any way in google app engine to have unique properties for a given model? As a example, could I have a User(db.Model) entity with a email property that is guaranteed unique across the entire datastore?
I found this resource here, which might prove helpful.
A:
The only help you get from GAE's datastore regarding "uniqueness" is via entities' keys -- but then, I see the URL you quote also noticed that and shows one way to exploit this fact. To get anywhere beyond keys, you need to perform your checks at application level (before you put an entity, or a change to a unique set of properties, you make a suitable query [[key-only for speed]] and check that it comes up empty), but that gets pretty costly (and hard to make transaction-safe).
A:
I use record.key().id() blogged how, Nick Johnson's blog has pro expert advice
A:
I have implemented it in the following way by overriding the put method and using the key.name
class Program(db.Model):
name = db.StringProperty("Title")
slug = db.StringProperty("Slug")
def put(self):
if Program.get_by_key_name(self.slug):
raise UniqueConstraintViolation("slug", self.slug)
self._key_name = self.slug
return db.Model.put(self)
class UniqueConstraintViolation(Exception):
def __init__(self, scope, value):
super(UniqueConstraintViolation, self).__init__("Value '%s' is not unique within scope '%s'." % (value, scope, ))
I save the slug as key.name and if you try to add another program it will check if the key name already exist. It's probably not a nice way, im also a beginner at python / app engine.
This is good article about somebody using a helper model: http://squeeville.com/2009/01/30/add-a-unique-constraint-to-google-app-engine/
Edit: I saw you also provided that article lol.
| How do I create a unique property in python on google app engine? | In some database technologies, for a attribute in a record, you can guarantee uniqueness of that attribute within the entire database. An example of this might be a email_address attribute in a User record. By setting email_address to unique, you guarantee that a particular email address can only appear in one record in the entire database.
Is there any way in google app engine to have unique properties for a given model? As a example, could I have a User(db.Model) entity with a email property that is guaranteed unique across the entire datastore?
I found this resource here, which might prove helpful.
| [
"The only help you get from GAE's datastore regarding \"uniqueness\" is via entities' keys -- but then, I see the URL you quote also noticed that and shows one way to exploit this fact. To get anywhere beyond keys, you need to perform your checks at application level (before you put an entity, or a change to a unique set of properties, you make a suitable query [[key-only for speed]] and check that it comes up empty), but that gets pretty costly (and hard to make transaction-safe).\n",
"I use record.key().id() blogged how, Nick Johnson's blog has pro expert advice\n",
"I have implemented it in the following way by overriding the put method and using the key.name\nclass Program(db.Model):\n name = db.StringProperty(\"Title\")\n slug = db.StringProperty(\"Slug\")\n def put(self):\n if Program.get_by_key_name(self.slug):\n raise UniqueConstraintViolation(\"slug\", self.slug)\n self._key_name = self.slug\n return db.Model.put(self)\n\n\nclass UniqueConstraintViolation(Exception):\n def __init__(self, scope, value):\n super(UniqueConstraintViolation, self).__init__(\"Value '%s' is not unique within scope '%s'.\" % (value, scope, ))\n\nI save the slug as key.name and if you try to add another program it will check if the key name already exist. It's probably not a nice way, im also a beginner at python / app engine.\nThis is good article about somebody using a helper model: http://squeeville.com/2009/01/30/add-a-unique-constraint-to-google-app-engine/\nEdit: I saw you also provided that article lol.\n"
] | [
4,
2,
2
] | [] | [] | [
"database",
"google_app_engine",
"python"
] | stackoverflow_0001809754_database_google_app_engine_python.txt |
Q:
Switch python distributions
I have a MacBook Pro with Snow Leopard, and the Python 2.6 distribution that comes standard. Numpy does not work properly on it. Loadtxt gives errors of the filename being too long, and getfromtxt does not work at all (no object in module error). So then I tried downloading the py26-numpy port on MacPorts. Of course when I use python, it defaults the mac distribution. How can I switch it to use the latest and greatest from MacPorts. This seems so much simpler than building all the tools I need from source...
Thanks!
A:
First of all, add the MacPorts path (/opt/local/bin) to your $PATH. In .bashrc (or whatever shell config file you use):
export PATH="/opt/local/bin:${PATH}"
If you have multiple versions of Python installed via MacPorts, and/or want to easily switch between the MacPorts and Apple distributions, you can install the python_select port as well.
Also note that the MacPorts version of Python 2.6 is installed into /opt/local/bin/python2.6, so to use that interpreter, you'll have to do one of three things:
Start the interpreter using python2.6 (not just python).
Set up a shell alias so that python calls python2.6 (alias python=python2.6).
Manually set up a symlink from /opt/local/bin/python -> /opt/local/bin/python2.6.
Use python_select to set the Python used by calling python.
Options #3 or #4 are probably the best bet.
A:
You need to update your PATH so that the stuff from MacPorts is in front of the standard system directories, e.g., export PATH=/opt/local/bin:/opt/local/sbin:/opt/local/Library/Frameworks/Python.framework/Versions/Current/bin/:$PATH.
UPDATE: Pay special attention to the fact that /opt/local/Library/Frameworks/Python.framework/Versions/Current/bin is in front of your old PATH value.
A:
The existing answers are quite useful, but I noticed that neither of them spell out how to make the change stick. If you're not familiar with the unix command line this might be important.
First, and explanation: In unix based operating systems, important configuration information in the shell is stored in things called environment variables. The environment variable called PATH directs your shell to a list of places to look for programs. When you type a command, it starts at the leftmost end of the PATH variable, and looks in that folder for the program you tried to run. If it finds it, it runs it; else it looks in the next folder. When you have multiple versions of the same program installed, you can use the PATH variable to give one precedence.
To make use of this, put the folder with the shiny new version in front of the path, like this:
PATH=/opt/local/bin:/usr/bin:/usr/local/bin
To make this change in a single version of your shell, you can type
export PATH=/opt/local/bin:/usr/bin:/usr/local/bin
To make the change in every shell you open, you need to instruct your shell to set this variable every time it starts. There is a file called .bashrc, and another one called .bash_profile that bash will read when it starts up. The .bashrc file is generally used to contain instructions for all shells, and .bash_profile is used to contain instructions only for interactive shells. So, to make this change stick, you can edit /Users/yourname/.bashrc to include a line like this:
export PATH="/opt/local/bin:$PATH"
What that does is add /opt/local/bin to the front of the path variable while leaving the rest of the path alone. If that change doesn't seem to work, you will need to either ensure .bashrc is getting called by adding source $HOME/.bashrc to your .bash_profile script, or just move the necessary line into .bash_profile.
| Switch python distributions | I have a MacBook Pro with Snow Leopard, and the Python 2.6 distribution that comes standard. Numpy does not work properly on it. Loadtxt gives errors of the filename being too long, and getfromtxt does not work at all (no object in module error). So then I tried downloading the py26-numpy port on MacPorts. Of course when I use python, it defaults the mac distribution. How can I switch it to use the latest and greatest from MacPorts. This seems so much simpler than building all the tools I need from source...
Thanks!
| [
"First of all, add the MacPorts path (/opt/local/bin) to your $PATH. In .bashrc (or whatever shell config file you use):\nexport PATH=\"/opt/local/bin:${PATH}\"\n\nIf you have multiple versions of Python installed via MacPorts, and/or want to easily switch between the MacPorts and Apple distributions, you can install the python_select port as well.\nAlso note that the MacPorts version of Python 2.6 is installed into /opt/local/bin/python2.6, so to use that interpreter, you'll have to do one of three things:\n\nStart the interpreter using python2.6 (not just python).\nSet up a shell alias so that python calls python2.6 (alias python=python2.6).\nManually set up a symlink from /opt/local/bin/python -> /opt/local/bin/python2.6.\nUse python_select to set the Python used by calling python.\n\nOptions #3 or #4 are probably the best bet.\n",
"You need to update your PATH so that the stuff from MacPorts is in front of the standard system directories, e.g., export PATH=/opt/local/bin:/opt/local/sbin:/opt/local/Library/Frameworks/Python.framework/Versions/Current/bin/:$PATH.\nUPDATE: Pay special attention to the fact that /opt/local/Library/Frameworks/Python.framework/Versions/Current/bin is in front of your old PATH value.\n",
"The existing answers are quite useful, but I noticed that neither of them spell out how to make the change stick. If you're not familiar with the unix command line this might be important. \nFirst, and explanation: In unix based operating systems, important configuration information in the shell is stored in things called environment variables. The environment variable called PATH directs your shell to a list of places to look for programs. When you type a command, it starts at the leftmost end of the PATH variable, and looks in that folder for the program you tried to run. If it finds it, it runs it; else it looks in the next folder. When you have multiple versions of the same program installed, you can use the PATH variable to give one precedence. \nTo make use of this, put the folder with the shiny new version in front of the path, like this: \nPATH=/opt/local/bin:/usr/bin:/usr/local/bin\n\nTo make this change in a single version of your shell, you can type \nexport PATH=/opt/local/bin:/usr/bin:/usr/local/bin\n\nTo make the change in every shell you open, you need to instruct your shell to set this variable every time it starts. There is a file called .bashrc, and another one called .bash_profile that bash will read when it starts up. The .bashrc file is generally used to contain instructions for all shells, and .bash_profile is used to contain instructions only for interactive shells. So, to make this change stick, you can edit /Users/yourname/.bashrc to include a line like this:\nexport PATH=\"/opt/local/bin:$PATH\"\n\nWhat that does is add /opt/local/bin to the front of the path variable while leaving the rest of the path alone. If that change doesn't seem to work, you will need to either ensure .bashrc is getting called by adding source $HOME/.bashrc to your .bash_profile script, or just move the necessary line into .bash_profile. \n"
] | [
4,
1,
0
] | [] | [] | [
"macports",
"numpy",
"osx_snow_leopard",
"python"
] | stackoverflow_0003134332_macports_numpy_osx_snow_leopard_python.txt |
Q:
Good real-world uses of metaclasses (e.g. in Python)
I'm learning about metaclasses in Python. I think it is a very powerful technique, and I'm looking for good uses for them. I'd like some feedback of good useful real-world examples of using metaclasses. I'm not looking for example code on how to write a metaclass (there are plenty examples of useless metaclasses out there), but real examples where you have applied the technique and it was really the appropriate solution. The rule is: no theoretical possibilities, but metaclasses at work in a real application.
I'll start with the one example I know:
Django models, for declarative programming, where the base class Model uses a metaclass to fill the model objects of useful ORM functionality from the attribute definitions.
Looking forward to your contributions.
A:
In Python 2.6 and 3.1, the Python standard library provides an abc.ABCMeta, a meta-class for Abstract Base Classes ("ABCs"). Classes that use the meta-class can use @abstractmethod and @abstractproperty to define abstract methods and properties. The meta-class will ensure that derived classes override the abstract methods and properties.
Also, classes that implement the ABC without actually inheriting from it can register as implementing the interface, so that issubclass and isinstance will work.
For example, the collections module defines the Sequence ABC. It also calls Sequence.register(tuple) to register the built-in tuple type as a Sequence, even though tuple does not actually inherit from Sequence.
A:
The Python implementation of Protocol Buffers uses metaclasses to generate the Python bindings that represent your data format. From the tutorial:
The important line in each class is __metaclass__ = reflection.GeneratedProtocolMessageType. While the details of how Python metaclasses work is beyond the scope of this tutorial, you can think of them as like a template for creating classes. At load time, the GeneratedProtocolMessageType metaclass uses the specified descriptors to create all the Python methods you need to work with each message type and adds them to the relevant classes. You can then use the fully-populated classes in your code.
A:
FormEncode validators and Turbogears / Tosca widgets.
You might also be interested in class decorators: they can be written with the latest releases, and cover many use cases that were previously handled with metaclasses.
A:
SQLalchemy also uses them for declarative database models.
Sorry my answer isn't very different from your example, but if you're looking for example code, I found declarative to be pretty readable.
A:
The only time I used a metaclass so far was to write a deprecation warning mechanism. It was something along the following lines - syntax may be very approximative, but code will illustrate my point more easily than a complicated sentence :
class New(object):
pass
class Old(object):
def __new__(self):
deprecation_warning("Old class is no more supported, use New class instead")
return New()
| Good real-world uses of metaclasses (e.g. in Python) | I'm learning about metaclasses in Python. I think it is a very powerful technique, and I'm looking for good uses for them. I'd like some feedback of good useful real-world examples of using metaclasses. I'm not looking for example code on how to write a metaclass (there are plenty examples of useless metaclasses out there), but real examples where you have applied the technique and it was really the appropriate solution. The rule is: no theoretical possibilities, but metaclasses at work in a real application.
I'll start with the one example I know:
Django models, for declarative programming, where the base class Model uses a metaclass to fill the model objects of useful ORM functionality from the attribute definitions.
Looking forward to your contributions.
| [
"In Python 2.6 and 3.1, the Python standard library provides an abc.ABCMeta, a meta-class for Abstract Base Classes (\"ABCs\"). Classes that use the meta-class can use @abstractmethod and @abstractproperty to define abstract methods and properties. The meta-class will ensure that derived classes override the abstract methods and properties.\nAlso, classes that implement the ABC without actually inheriting from it can register as implementing the interface, so that issubclass and isinstance will work. \nFor example, the collections module defines the Sequence ABC. It also calls Sequence.register(tuple) to register the built-in tuple type as a Sequence, even though tuple does not actually inherit from Sequence.\n",
"The Python implementation of Protocol Buffers uses metaclasses to generate the Python bindings that represent your data format. From the tutorial:\n\nThe important line in each class is __metaclass__ = reflection.GeneratedProtocolMessageType. While the details of how Python metaclasses work is beyond the scope of this tutorial, you can think of them as like a template for creating classes. At load time, the GeneratedProtocolMessageType metaclass uses the specified descriptors to create all the Python methods you need to work with each message type and adds them to the relevant classes. You can then use the fully-populated classes in your code. \n\n",
"FormEncode validators and Turbogears / Tosca widgets.\nYou might also be interested in class decorators: they can be written with the latest releases, and cover many use cases that were previously handled with metaclasses.\n",
"SQLalchemy also uses them for declarative database models. \nSorry my answer isn't very different from your example, but if you're looking for example code, I found declarative to be pretty readable.\n",
"The only time I used a metaclass so far was to write a deprecation warning mechanism. It was something along the following lines - syntax may be very approximative, but code will illustrate my point more easily than a complicated sentence :\nclass New(object):\n pass\n\nclass Old(object):\n def __new__(self):\n deprecation_warning(\"Old class is no more supported, use New class instead\")\n return New()\n\n"
] | [
3,
3,
2,
0,
0
] | [] | [] | [
"metaprogramming",
"python"
] | stackoverflow_0002907498_metaprogramming_python.txt |
Q:
401 and 403 Errors with google base API
I built a wiki using Google App engine and the Data APIs. The wiki pages are stored as Google Base 'Reference Articles.' I want users to be able to view, edit, and delete the items, so when a request is made to the server, client login uses my username and password, and retrieves or edits the data on the user's behalf. The login code:
client = gdata.base.service.GBaseService()
client.ssl = False
gdata.alt.appengine.run_on_appengine(client)
#EMAIL, API_KEY and PASSWORD are constants stored on the server
client.email = EMAIL
client.password = PASSWORD
client.api_key = API_KEY
client.ProgrammaticLogin()
q = gdata.base.service.BaseQuery()
q.feed = '/base/feeds/items/' + self.base_id
item = base_client.GetItem(q.ToUri())
This works fine for me, but if I log out of my google account, it returns the following error:
'status': 401L, 'body': '<HTML>\n<HEAD>\n<TITLE>Authorization required</TITLE>
All I want is for the users to be able to CRUD my data stored on Base. What am I doing wrong?
Thanks in advance
A:
It sounds like logging out in your client is invalidating all sessions for your account. Your best bet is probably to create a role account specifically for your app to use.
| 401 and 403 Errors with google base API | I built a wiki using Google App engine and the Data APIs. The wiki pages are stored as Google Base 'Reference Articles.' I want users to be able to view, edit, and delete the items, so when a request is made to the server, client login uses my username and password, and retrieves or edits the data on the user's behalf. The login code:
client = gdata.base.service.GBaseService()
client.ssl = False
gdata.alt.appengine.run_on_appengine(client)
#EMAIL, API_KEY and PASSWORD are constants stored on the server
client.email = EMAIL
client.password = PASSWORD
client.api_key = API_KEY
client.ProgrammaticLogin()
q = gdata.base.service.BaseQuery()
q.feed = '/base/feeds/items/' + self.base_id
item = base_client.GetItem(q.ToUri())
This works fine for me, but if I log out of my google account, it returns the following error:
'status': 401L, 'body': '<HTML>\n<HEAD>\n<TITLE>Authorization required</TITLE>
All I want is for the users to be able to CRUD my data stored on Base. What am I doing wrong?
Thanks in advance
| [
"It sounds like logging out in your client is invalidating all sessions for your account. Your best bet is probably to create a role account specifically for your app to use.\n"
] | [
1
] | [] | [] | [
"authentication",
"gdata_api",
"google_app_engine",
"google_base",
"python"
] | stackoverflow_0003134412_authentication_gdata_api_google_app_engine_google_base_python.txt |
Q:
How do I tell django to not escape % and _ in a query
I want to be able to use wildcards in my django queries used for searching. However as the documentation says:
Entry.objects.filter(headline__contains='%')
Will result in SQL that looks something like this:
SELECT ... WHERE headline LIKE '%\%%';
How do I tell django to not escape % and _ in a query. Or is there another way to implement wildcard search in django (apart from writing the sql directly)?
A:
headline__contains='%' would mean headline is anything, no? In which case why include it in the query?
A:
You can use the extra() method to insert a custom where clause:
Entry.objects.extra(where="headline LIKE '%'")
| How do I tell django to not escape % and _ in a query | I want to be able to use wildcards in my django queries used for searching. However as the documentation says:
Entry.objects.filter(headline__contains='%')
Will result in SQL that looks something like this:
SELECT ... WHERE headline LIKE '%\%%';
How do I tell django to not escape % and _ in a query. Or is there another way to implement wildcard search in django (apart from writing the sql directly)?
| [
"headline__contains='%' would mean headline is anything, no? In which case why include it in the query?\n",
"You can use the extra() method to insert a custom where clause:\nEntry.objects.extra(where=\"headline LIKE '%'\")\n\n"
] | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003134850_django_python.txt |
Q:
Can I have two init functions in a python class?
I'm porting some geolocation java code from http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#Java (shown below) to python. It can be initialized using two functions (fromDegrees or fromRadians). I thought I could do something like
class geoLocation:
_radLat = 0
_radLong = 0
_degLat = 0
_degLong = 0
def fromDegrees(lat, long):
#set _radLat, _radLong, _degLat, _degLong
def fromRadians(lat, long):
#set _radLat, _radLong, _degLat, _degLong
...
But that does not seem optimal since I set the values for _radLat, _radLong, _degLat and _degLong twice. Can I define two init functions? What's the best way to do that?
Thanks
/**
* <p>Represents a point on the surface of a sphere. (The Earth is almost
* spherical.)</p>
*
* <p>To create an instance, call one of the static methods fromDegrees() or
* fromRadians().</p>
*
* <p>This code was originally published at
* <a href="http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates#Java">
* http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates#Java</a>.</p>
*
* @author Jan Philip Matuschek
* @version 27 May 2010
*/
public class GeoLocation {
private double radLat; // latitude in radians
private double radLon; // longitude in radians
private double degLat; // latitude in degrees
private double degLon; // longitude in degrees
private static final double MIN_LAT = Math.toRadians(-90d); // -PI/2
private static final double MAX_LAT = Math.toRadians(90d); // PI/2
private static final double MIN_LON = Math.toRadians(-180d); // -PI*2
private static final double MAX_LON = Math.toRadians(180d); // PI*2
private GeoLocation () {
}
/**
* @param latitude the latitude, in degrees.
* @param longitude the longitude, in degrees.
*/
public static GeoLocation fromDegrees(double latitude, double longitude) {
GeoLocation result = new GeoLocation();
result.radLat = Math.toRadians(latitude);
result.radLon = Math.toRadians(longitude);
result.degLat = latitude;
result.degLon = longitude;
result.checkBounds();
return result;
}
/**
* @param latitude the latitude, in radians.
* @param longitude the longitude, in radians.
*/
public static GeoLocation fromRadians(double latitude, double longitude) {
GeoLocation result = new GeoLocation();
result.radLat = latitude;
result.radLon = longitude;
result.degLat = Math.toDegrees(latitude);
result.degLon = Math.toDegrees(longitude);
result.checkBounds();
return result;
}
private void checkBounds() {
if (radLat < MIN_LAT || radLat > MAX_LAT ||
radLon < MIN_LON || radLon > MAX_LON)
throw new IllegalArgumentException();
}
/**
* @return the latitude, in degrees.
*/
public double getLatitudeInDegrees() {
return degLat;
}
/**
* @return the longitude, in degrees.
*/
public double getLongitudeInDegrees() {
return degLon;
}
/**
* @return the latitude, in radians.
*/
public double getLatitudeInRadians() {
return radLat;
}
/**
* @return the longitude, in radians.
*/
public double getLongitudeInRadians() {
return radLon;
}
@Override
public String toString() {
return "(" + degLat + "\u00B0, " + degLon + "\u00B0) = (" +
radLat + " rad, " + radLon + " rad)";
}
/**
* Computes the great circle distance between this GeoLocation instance
* and the location argument.
* @param radius the radius of the sphere, e.g. the average radius for a
* spherical approximation of the figure of the Earth is approximately
* 6371.01 kilometers.
* @return the distance, measured in the same unit as the radius
* argument.
*/
public double distanceTo(GeoLocation location, double radius) {
return Math.acos(Math.sin(radLat) * Math.sin(location.radLat) +
Math.cos(radLat) * Math.cos(location.radLat) *
Math.cos(radLon - location.radLon)) * radius;
}
/**
* <p>Computes the bounding coordinates of all points on the surface
* of a sphere that have a great circle distance to the point represented
* by this GeoLocation instance that is less or equal to the distance
* argument.</p>
* <p>For more information about the formulae used in this method visit
* <a href="http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates">
* http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates</a>.</p>
* @param distance the distance from the point represented by this
* GeoLocation instance. Must me measured in the same unit as the radius
* argument.
* @param radius the radius of the sphere, e.g. the average radius for a
* spherical approximation of the figure of the Earth is approximately
* 6371.01 kilometers.
* @return an array of two GeoLocation objects such that:<ul>
* <li>The latitude of any point within the specified distance is greater
* or equal to the latitude of the first array element and smaller or
* equal to the latitude of the second array element.</li>
* <li>If the longitude of the first array element is smaller or equal to
* the longitude of the second element, then
* the longitude of any point within the specified distance is greater
* or equal to the longitude of the first array element and smaller or
* equal to the longitude of the second array element.</li>
* <li>If the longitude of the first array element is greater than the
* longitude of the second element (this is the case if the 180th
* meridian is within the distance), then
* the longitude of any point within the specified distance is greater
* or equal to the longitude of the first array element
* <strong>or</strong> smaller or equal to the longitude of the second
* array element.</li>
* </ul>
*/
public GeoLocation[] boundingCoordinates(double distance, double radius) {
if (radius < 0d || distance < 0d)
throw new IllegalArgumentException();
// angular distance in radians on a great circle
double radDist = distance / radius;
double minLat = radLat - radDist;
double maxLat = radLat + radDist;
double minLon, maxLon;
if (minLat > MIN_LAT && maxLat < MAX_LAT) {
double deltaLon = Math.asin(Math.sin(radDist) /
Math.cos(radLat));
minLon = radLon - deltaLon;
if (minLon < MIN_LON) minLon += 2d * Math.PI;
maxLon = radLon + deltaLon;
if (maxLon > MAX_LON) maxLon -= 2d * Math.PI;
} else {
// a pole is within the distance
minLat = Math.max(minLat, MIN_LAT);
maxLat = Math.min(maxLat, MAX_LAT);
minLon = MIN_LON;
maxLon = MAX_LON;
}
return new GeoLocation[]{fromRadians(minLat, minLon),
fromRadians(maxLat, maxLon)};
}
}
A:
Chose one default ( radians or degrees ) and stick with it. You can write a classmethod to automatically convert to the other:
class geoLocation:
def __init__(self, lat, long):
"""init class from lat,long as radians"""
@classmethod
def fromDegrees(cls, dlat, dlong):
"""creat `cls` from lat,long in degrees """
return cls( to_radians(dlat), to_radians(dlong))
@classmethod
def fromRadians(cls, lat, long): # just in case
return cls(lat, long)
obj = geoLocation.fromDegrees(10,20) # returns a new geoLocation object
A:
I would just include a boolean in your init method. Instead of having two __init__ methods, do the following:
class geoLocation:
def __init__(self, lat, long, degrees=True):
if degrees:
# process as fromDegrees
(self._radLat, self._radLong, self._degLat, self._degLong) = self.fromDegrees(lat, long)
else:
(self._radLat, self._radLong, self._degLat, self._degLong) = self.fromRadians(lat, long)
def fromDegrees(self, lat, long):
# some function returning radLat and long and degLat and long in a tuple
def fromRadians(self, lat, long):
# same idea but different calculations
A:
An option is to use factory class methods:
class geoLocation(object):
@classmethod
def fromDegrees(cls, lat, long):
return cls(lat, long, True)
@classmethod
def fromRadians(cls, lat, long):
return cls(lat, long, False)
def __init__(self, lat, long, degrees=True):
if degrees:
#blah
else:
#blah
A:
Another option is to have to subclasses of GeoLocation, say DegreesGeoLocation and RadiansGeoLocation. Now you can give each their own init function.
You are now storing the location twice in your class, once using radians and once using degrees. This can cause problems if you accidentally modify one representation but forget the other. I think you could best use one representation, and provide getters and setters which eventually do the conversion to the other representation.
| Can I have two init functions in a python class? | I'm porting some geolocation java code from http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates#Java (shown below) to python. It can be initialized using two functions (fromDegrees or fromRadians). I thought I could do something like
class geoLocation:
_radLat = 0
_radLong = 0
_degLat = 0
_degLong = 0
def fromDegrees(lat, long):
#set _radLat, _radLong, _degLat, _degLong
def fromRadians(lat, long):
#set _radLat, _radLong, _degLat, _degLong
...
But that does not seem optimal since I set the values for _radLat, _radLong, _degLat and _degLong twice. Can I define two init functions? What's the best way to do that?
Thanks
/**
* <p>Represents a point on the surface of a sphere. (The Earth is almost
* spherical.)</p>
*
* <p>To create an instance, call one of the static methods fromDegrees() or
* fromRadians().</p>
*
* <p>This code was originally published at
* <a href="http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates#Java">
* http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates#Java</a>.</p>
*
* @author Jan Philip Matuschek
* @version 27 May 2010
*/
public class GeoLocation {
private double radLat; // latitude in radians
private double radLon; // longitude in radians
private double degLat; // latitude in degrees
private double degLon; // longitude in degrees
private static final double MIN_LAT = Math.toRadians(-90d); // -PI/2
private static final double MAX_LAT = Math.toRadians(90d); // PI/2
private static final double MIN_LON = Math.toRadians(-180d); // -PI*2
private static final double MAX_LON = Math.toRadians(180d); // PI*2
private GeoLocation () {
}
/**
* @param latitude the latitude, in degrees.
* @param longitude the longitude, in degrees.
*/
public static GeoLocation fromDegrees(double latitude, double longitude) {
GeoLocation result = new GeoLocation();
result.radLat = Math.toRadians(latitude);
result.radLon = Math.toRadians(longitude);
result.degLat = latitude;
result.degLon = longitude;
result.checkBounds();
return result;
}
/**
* @param latitude the latitude, in radians.
* @param longitude the longitude, in radians.
*/
public static GeoLocation fromRadians(double latitude, double longitude) {
GeoLocation result = new GeoLocation();
result.radLat = latitude;
result.radLon = longitude;
result.degLat = Math.toDegrees(latitude);
result.degLon = Math.toDegrees(longitude);
result.checkBounds();
return result;
}
private void checkBounds() {
if (radLat < MIN_LAT || radLat > MAX_LAT ||
radLon < MIN_LON || radLon > MAX_LON)
throw new IllegalArgumentException();
}
/**
* @return the latitude, in degrees.
*/
public double getLatitudeInDegrees() {
return degLat;
}
/**
* @return the longitude, in degrees.
*/
public double getLongitudeInDegrees() {
return degLon;
}
/**
* @return the latitude, in radians.
*/
public double getLatitudeInRadians() {
return radLat;
}
/**
* @return the longitude, in radians.
*/
public double getLongitudeInRadians() {
return radLon;
}
@Override
public String toString() {
return "(" + degLat + "\u00B0, " + degLon + "\u00B0) = (" +
radLat + " rad, " + radLon + " rad)";
}
/**
* Computes the great circle distance between this GeoLocation instance
* and the location argument.
* @param radius the radius of the sphere, e.g. the average radius for a
* spherical approximation of the figure of the Earth is approximately
* 6371.01 kilometers.
* @return the distance, measured in the same unit as the radius
* argument.
*/
public double distanceTo(GeoLocation location, double radius) {
return Math.acos(Math.sin(radLat) * Math.sin(location.radLat) +
Math.cos(radLat) * Math.cos(location.radLat) *
Math.cos(radLon - location.radLon)) * radius;
}
/**
* <p>Computes the bounding coordinates of all points on the surface
* of a sphere that have a great circle distance to the point represented
* by this GeoLocation instance that is less or equal to the distance
* argument.</p>
* <p>For more information about the formulae used in this method visit
* <a href="http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates">
* http://JanMatuschek.de/LatitudeLongitudeBoundingCoordinates</a>.</p>
* @param distance the distance from the point represented by this
* GeoLocation instance. Must me measured in the same unit as the radius
* argument.
* @param radius the radius of the sphere, e.g. the average radius for a
* spherical approximation of the figure of the Earth is approximately
* 6371.01 kilometers.
* @return an array of two GeoLocation objects such that:<ul>
* <li>The latitude of any point within the specified distance is greater
* or equal to the latitude of the first array element and smaller or
* equal to the latitude of the second array element.</li>
* <li>If the longitude of the first array element is smaller or equal to
* the longitude of the second element, then
* the longitude of any point within the specified distance is greater
* or equal to the longitude of the first array element and smaller or
* equal to the longitude of the second array element.</li>
* <li>If the longitude of the first array element is greater than the
* longitude of the second element (this is the case if the 180th
* meridian is within the distance), then
* the longitude of any point within the specified distance is greater
* or equal to the longitude of the first array element
* <strong>or</strong> smaller or equal to the longitude of the second
* array element.</li>
* </ul>
*/
public GeoLocation[] boundingCoordinates(double distance, double radius) {
if (radius < 0d || distance < 0d)
throw new IllegalArgumentException();
// angular distance in radians on a great circle
double radDist = distance / radius;
double minLat = radLat - radDist;
double maxLat = radLat + radDist;
double minLon, maxLon;
if (minLat > MIN_LAT && maxLat < MAX_LAT) {
double deltaLon = Math.asin(Math.sin(radDist) /
Math.cos(radLat));
minLon = radLon - deltaLon;
if (minLon < MIN_LON) minLon += 2d * Math.PI;
maxLon = radLon + deltaLon;
if (maxLon > MAX_LON) maxLon -= 2d * Math.PI;
} else {
// a pole is within the distance
minLat = Math.max(minLat, MIN_LAT);
maxLat = Math.min(maxLat, MAX_LAT);
minLon = MIN_LON;
maxLon = MAX_LON;
}
return new GeoLocation[]{fromRadians(minLat, minLon),
fromRadians(maxLat, maxLon)};
}
}
| [
"Chose one default ( radians or degrees ) and stick with it. You can write a classmethod to automatically convert to the other:\nclass geoLocation:\n def __init__(self, lat, long):\n \"\"\"init class from lat,long as radians\"\"\"\n\n @classmethod\n def fromDegrees(cls, dlat, dlong):\n \"\"\"creat `cls` from lat,long in degrees \"\"\"\n return cls( to_radians(dlat), to_radians(dlong))\n\n @classmethod\n def fromRadians(cls, lat, long): # just in case\n return cls(lat, long)\n\nobj = geoLocation.fromDegrees(10,20) # returns a new geoLocation object\n\n",
"I would just include a boolean in your init method. Instead of having two __init__ methods, do the following:\nclass geoLocation:\n def __init__(self, lat, long, degrees=True):\n if degrees:\n # process as fromDegrees\n (self._radLat, self._radLong, self._degLat, self._degLong) = self.fromDegrees(lat, long)\n else:\n (self._radLat, self._radLong, self._degLat, self._degLong) = self.fromRadians(lat, long)\n\n def fromDegrees(self, lat, long):\n # some function returning radLat and long and degLat and long in a tuple\n def fromRadians(self, lat, long):\n # same idea but different calculations\n\n",
"An option is to use factory class methods:\nclass geoLocation(object):\n @classmethod\n def fromDegrees(cls, lat, long):\n return cls(lat, long, True)\n\n @classmethod\n def fromRadians(cls, lat, long):\n return cls(lat, long, False)\n\n def __init__(self, lat, long, degrees=True):\n if degrees:\n #blah\n else:\n #blah\n\n",
"Another option is to have to subclasses of GeoLocation, say DegreesGeoLocation and RadiansGeoLocation. Now you can give each their own init function.\nYou are now storing the location twice in your class, once using radians and once using degrees. This can cause problems if you accidentally modify one representation but forget the other. I think you could best use one representation, and provide getters and setters which eventually do the conversion to the other representation.\n"
] | [
30,
7,
5,
1
] | [] | [] | [
"init",
"python"
] | stackoverflow_0003134829_init_python.txt |
Q:
How can I break this multithreaded python script into "chunks"?
I'm processing 100k domain names into a CSV based on results taken from Siteadvisor using urllib (not the best method, I know). However, my current script creates too many threads and Python runs into errors. Is there a way I can "chunk" this script to do X number of domains at a time (say, 10-20) to prevent these errors? Thanks in advance.
import threading
import urllib
class Resolver(threading.Thread):
def __init__(self, address, result_dict):
threading.Thread.__init__(self)
self.address = address
self.result_dict = result_dict
def run(self):
try:
content = urllib.urlopen("http://www.siteadvisor.com/sites/" + self.address).read(12000)
search1 = content.find("didn't find any significant problems.")
search2 = content.find('yellow')
search3 = content.find('web reputation analysis found potential security')
search4 = content.find("don't have the results yet.")
if search1 != -1:
result = "safe"
elif search2 != -1:
result = "caution"
elif search3 != -1:
result = "warning"
elif search4 != -1:
result = "unknown"
else:
result = ""
self.result_dict[self.address] = result
except:
pass
def main():
infile = open("domainslist", "r")
intext = infile.readlines()
threads = []
results = {}
for address in [address.strip() for address in intext if address.strip()]:
resolver_thread = Resolver(address, results)
threads.append(resolver_thread)
resolver_thread.start()
for thread in threads:
thread.join()
outfile = open('final.csv', 'w')
outfile.write("\n".join("%s,%s" % (address, ip) for address, ip in results.iteritems()))
outfile.close()
if __name__ == '__main__':
main()
Edit: new version, based on andyortlieb's suggestions.
import threading
import urllib
import time
class Resolver(threading.Thread):
def __init__(self, address, result_dict, threads):
threading.Thread.__init__(self)
self.address = address
self.result_dict = result_dict
self.threads = threads
def run(self):
try:
content = urllib.urlopen("http://www.siteadvisor.com/sites/" + self.address).read(12000)
search1 = content.find("didn't find any significant problems.")
search2 = content.find('yellow')
search3 = content.find('web reputation analysis found potential security')
search4 = content.find("don't have the results yet.")
if search1 != -1:
result = "safe"
elif search2 != -1:
result = "caution"
elif search3 != -1:
result = "warning"
elif search4 != -1:
result = "unknown"
else:
result = ""
self.result_dict[self.address] = result
outfile = open('final.csv', 'a')
outfile.write(self.address + "," + result + "\n")
outfile.close()
print self.address + result
threads.remove(self)
except:
pass
def main():
infile = open("domainslist", "r")
intext = infile.readlines()
threads = []
results = {}
for address in [address.strip() for address in intext if address.strip()]:
loop=True
while loop:
if len(threads) < 20:
resolver_thread = Resolver(address, results, threads)
threads.append(resolver_thread)
resolver_thread.start()
loop=False
else:
time.sleep(.25)
for thread in threads:
thread.join()
# removed so I can track the progress of the script
# outfile = open('final.csv', 'w')
# outfile.write("\n".join("%s,%s" % (address, ip) for address, ip in results.iteritems()))
# outfile.close()
if __name__ == '__main__':
main()
A:
Your existing code will work beautifully - just modify your __init__ method inside Resolver to take in an additional list of addresses instead of one at a time, so instead of having one thread for each address, you have one thread for every 10 (for example). That way you won't overload the threading.
You'll obviously have to slightly modify run as well so it loops through the array of addresses instead of the one self.address.
I can work up a quick example if you'd like, but from the quality of your code I feel as though you'll be able to handle it quite easily.
Hope this helps!
EDIT Example below as requested. Note that you'll have to modify main to send your Resolver instance lists of addresses instead of a single address - I couldn't handle this for you without knowing more about the format of your file and how the addresses are stored. Note - you could do the run method with a helper function, but i thought this might be more understandable as an example
class Resolver(threading.Thread):
def __init__(self, addresses, result_dict):
threading.Thread.__init__(self)
self.addresses = addresses # Now takes in a list of multiple addresses
self.result_dict = result_dict
def run(self):
for address in self.addresses: # do your existing code for every address in the list
try:
content = urllib.urlopen("http://www.siteadvisor.com/sites/" + address).read(12000)
search1 = content.find("didn't find any significant problems.")
search2 = content.find('yellow')
search3 = content.find('web reputation analysis found potential security')
search4 = content.find("don't have the results yet.")
if search1 != -1:
result = "safe"
elif search2 != -1:
result = "caution"
elif search3 != -1:
result = "warning"
elif search4 != -1:
result = "unknown"
else:
result = ""
self.result_dict[address] = result
except:
pass
A:
This might be kind of rigid, but you could pass threads to Resolver, so that when Resolver.run is completed, it can call threads.remove(self)
Then you can nest some conditions so that threads are only created if there is room for them, and if there isn't room, they wait until there is.
for address in [address.strip() for address in intext if address.strip()]:
loop=True
while loop:
if len(threads)<20:
resolver_thread = Resolver(address, results, threads)
threads.append(resolver_thread)
resolver_thread.start()
loop=False
else:
time.sleep(.25)
| How can I break this multithreaded python script into "chunks"? | I'm processing 100k domain names into a CSV based on results taken from Siteadvisor using urllib (not the best method, I know). However, my current script creates too many threads and Python runs into errors. Is there a way I can "chunk" this script to do X number of domains at a time (say, 10-20) to prevent these errors? Thanks in advance.
import threading
import urllib
class Resolver(threading.Thread):
def __init__(self, address, result_dict):
threading.Thread.__init__(self)
self.address = address
self.result_dict = result_dict
def run(self):
try:
content = urllib.urlopen("http://www.siteadvisor.com/sites/" + self.address).read(12000)
search1 = content.find("didn't find any significant problems.")
search2 = content.find('yellow')
search3 = content.find('web reputation analysis found potential security')
search4 = content.find("don't have the results yet.")
if search1 != -1:
result = "safe"
elif search2 != -1:
result = "caution"
elif search3 != -1:
result = "warning"
elif search4 != -1:
result = "unknown"
else:
result = ""
self.result_dict[self.address] = result
except:
pass
def main():
infile = open("domainslist", "r")
intext = infile.readlines()
threads = []
results = {}
for address in [address.strip() for address in intext if address.strip()]:
resolver_thread = Resolver(address, results)
threads.append(resolver_thread)
resolver_thread.start()
for thread in threads:
thread.join()
outfile = open('final.csv', 'w')
outfile.write("\n".join("%s,%s" % (address, ip) for address, ip in results.iteritems()))
outfile.close()
if __name__ == '__main__':
main()
Edit: new version, based on andyortlieb's suggestions.
import threading
import urllib
import time
class Resolver(threading.Thread):
def __init__(self, address, result_dict, threads):
threading.Thread.__init__(self)
self.address = address
self.result_dict = result_dict
self.threads = threads
def run(self):
try:
content = urllib.urlopen("http://www.siteadvisor.com/sites/" + self.address).read(12000)
search1 = content.find("didn't find any significant problems.")
search2 = content.find('yellow')
search3 = content.find('web reputation analysis found potential security')
search4 = content.find("don't have the results yet.")
if search1 != -1:
result = "safe"
elif search2 != -1:
result = "caution"
elif search3 != -1:
result = "warning"
elif search4 != -1:
result = "unknown"
else:
result = ""
self.result_dict[self.address] = result
outfile = open('final.csv', 'a')
outfile.write(self.address + "," + result + "\n")
outfile.close()
print self.address + result
threads.remove(self)
except:
pass
def main():
infile = open("domainslist", "r")
intext = infile.readlines()
threads = []
results = {}
for address in [address.strip() for address in intext if address.strip()]:
loop=True
while loop:
if len(threads) < 20:
resolver_thread = Resolver(address, results, threads)
threads.append(resolver_thread)
resolver_thread.start()
loop=False
else:
time.sleep(.25)
for thread in threads:
thread.join()
# removed so I can track the progress of the script
# outfile = open('final.csv', 'w')
# outfile.write("\n".join("%s,%s" % (address, ip) for address, ip in results.iteritems()))
# outfile.close()
if __name__ == '__main__':
main()
| [
"Your existing code will work beautifully - just modify your __init__ method inside Resolver to take in an additional list of addresses instead of one at a time, so instead of having one thread for each address, you have one thread for every 10 (for example). That way you won't overload the threading.\nYou'll obviously have to slightly modify run as well so it loops through the array of addresses instead of the one self.address.\nI can work up a quick example if you'd like, but from the quality of your code I feel as though you'll be able to handle it quite easily.\nHope this helps!\nEDIT Example below as requested. Note that you'll have to modify main to send your Resolver instance lists of addresses instead of a single address - I couldn't handle this for you without knowing more about the format of your file and how the addresses are stored. Note - you could do the run method with a helper function, but i thought this might be more understandable as an example\nclass Resolver(threading.Thread):\n def __init__(self, addresses, result_dict):\n threading.Thread.__init__(self)\n self.addresses = addresses # Now takes in a list of multiple addresses\n self.result_dict = result_dict\n\n def run(self):\n for address in self.addresses: # do your existing code for every address in the list\n try:\n content = urllib.urlopen(\"http://www.siteadvisor.com/sites/\" + address).read(12000)\n search1 = content.find(\"didn't find any significant problems.\")\n search2 = content.find('yellow')\n search3 = content.find('web reputation analysis found potential security')\n search4 = content.find(\"don't have the results yet.\")\n\n if search1 != -1:\n result = \"safe\"\n elif search2 != -1:\n result = \"caution\"\n elif search3 != -1:\n result = \"warning\"\n elif search4 != -1:\n result = \"unknown\"\n else:\n result = \"\"\n\n self.result_dict[address] = result\n except:\n pass\n\n",
"This might be kind of rigid, but you could pass threads to Resolver, so that when Resolver.run is completed, it can call threads.remove(self)\nThen you can nest some conditions so that threads are only created if there is room for them, and if there isn't room, they wait until there is.\nfor address in [address.strip() for address in intext if address.strip()]:\n loop=True\n while loop:\n if len(threads)<20:\n resolver_thread = Resolver(address, results, threads)\n threads.append(resolver_thread)\n resolver_thread.start()\n loop=False\n else: \n time.sleep(.25)\n\n"
] | [
2,
2
] | [] | [] | [
"python",
"python_multithreading"
] | stackoverflow_0003135015_python_python_multithreading.txt |
Q:
Serious overhead in Python cProfile?
Hi expert Pythonists out there, I am starting to use cProfile so as to have a more detailed timing information on my program. However, it's quite disturbing to me that there's a significant overhead. Any idea why cProfile reported 7 seconds while time module only reported 2 seconds in the code below?
# a simple function
def f(a, b):
c = a+b
# a simple loop
def loop():
for i in xrange(10000000):
f(1,2)
# timing using time module
# 2 seconds on my computer
from time import time
x = time()
loop()
y = time()
print 'Time taken %.3f s.' % (y-x)
# timing using cProfile
# 7 seconds on my computer
import cProfile
cProfile.runctx('loop()', globals(), locals())
A:
Because it's doing a lot more work? time just times the whole operation, while cProfile runs it under instrumentation so it can get a detailed breakdown. Obviously, profiling is not meant to be used in production, so a 2.5x overhead seems like a small price to pay.
A:
The function f returns very quickly. When you use cProfile, the time being attributed to one call to f is not accurate because the time is so small that it is comparable to the error in measuring time. The clock used to measure differences in time may only be accurate to 0.001s. So the error in each measurement may be orders of magnitude greater that the time you are trying to measure. Do this 1e7 times and you've got bogus results. (See http://docs.python.org/library/profile.html#limitations for more discussion of this.)
Notice that if you change the code to use
def f(a, b):
for i in xrange(int(1e4)):
c = a+b
# a simple loop
def loop():
for i in xrange(int(1e3)):
f(1,2)
you get
Time taken 0.732 s.
1003 function calls in 0.725 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.725 0.725 <string>:1(<module>)
1000 0.723 0.001 0.723 0.001 test.py:4(f)
1 0.001 0.001 0.725 0.725 test.py:9(loop)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
You are doing the same number of loops, but each call to f takes longer. This cuts down on the error per measurement. (The time attributed to each call to f contains an error which is now not as large the total time measured.)
| Serious overhead in Python cProfile? | Hi expert Pythonists out there, I am starting to use cProfile so as to have a more detailed timing information on my program. However, it's quite disturbing to me that there's a significant overhead. Any idea why cProfile reported 7 seconds while time module only reported 2 seconds in the code below?
# a simple function
def f(a, b):
c = a+b
# a simple loop
def loop():
for i in xrange(10000000):
f(1,2)
# timing using time module
# 2 seconds on my computer
from time import time
x = time()
loop()
y = time()
print 'Time taken %.3f s.' % (y-x)
# timing using cProfile
# 7 seconds on my computer
import cProfile
cProfile.runctx('loop()', globals(), locals())
| [
"Because it's doing a lot more work? time just times the whole operation, while cProfile runs it under instrumentation so it can get a detailed breakdown. Obviously, profiling is not meant to be used in production, so a 2.5x overhead seems like a small price to pay.\n",
"The function f returns very quickly. When you use cProfile, the time being attributed to one call to f is not accurate because the time is so small that it is comparable to the error in measuring time. The clock used to measure differences in time may only be accurate to 0.001s. So the error in each measurement may be orders of magnitude greater that the time you are trying to measure. Do this 1e7 times and you've got bogus results. (See http://docs.python.org/library/profile.html#limitations for more discussion of this.) \nNotice that if you change the code to use\ndef f(a, b):\n for i in xrange(int(1e4)): \n c = a+b\n\n# a simple loop\ndef loop():\n for i in xrange(int(1e3)):\n f(1,2)\n\nyou get\nTime taken 0.732 s.\n 1003 function calls in 0.725 CPU seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.725 0.725 <string>:1(<module>)\n 1000 0.723 0.001 0.723 0.001 test.py:4(f)\n 1 0.001 0.001 0.725 0.725 test.py:9(loop)\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n\nYou are doing the same number of loops, but each call to f takes longer. This cuts down on the error per measurement. (The time attributed to each call to f contains an error which is now not as large the total time measured.)\n"
] | [
5,
1
] | [] | [] | [
"cprofile",
"performance",
"profile",
"python",
"time"
] | stackoverflow_0003134843_cprofile_performance_profile_python_time.txt |
Q:
How to Close an Image?
I'm trying to take an image file, do some stuff to it and save the changes back to the original file. The problem I'm having is in overwriting the original image; there doesn't seem to be a reliable way to release the handle on filename.
I need this content to be saved back to the same file because external processes depend on that filename to stay the same.
def do_post_processing(filename):
image = Image.open(str(filename))
try:
new_image = optimalimage.trim(image)
except ValueError as ex:
# The image is a blank placeholder image.
new_image = image.copy()
new_image = optimalimage.rescale(new_image)
new_image.save('tmp.tif')
del image
os.remove(str(filename))
os.rename('tmp.tif', str(filename))
del image was working until I added the exception handler where I made a copy of the image. I've also tried accessing a close() attribute of Image and with image, no success.
A:
You can provide a file-like object instead of a filename to the Image.open function. So try this:
def do_post_processing(filename):
with open(str(filename), 'rb') as f:
image = Image.open(f)
...
del new_image, image
os.remove(str(filename))
os.rename(...)
| How to Close an Image? | I'm trying to take an image file, do some stuff to it and save the changes back to the original file. The problem I'm having is in overwriting the original image; there doesn't seem to be a reliable way to release the handle on filename.
I need this content to be saved back to the same file because external processes depend on that filename to stay the same.
def do_post_processing(filename):
image = Image.open(str(filename))
try:
new_image = optimalimage.trim(image)
except ValueError as ex:
# The image is a blank placeholder image.
new_image = image.copy()
new_image = optimalimage.rescale(new_image)
new_image.save('tmp.tif')
del image
os.remove(str(filename))
os.rename('tmp.tif', str(filename))
del image was working until I added the exception handler where I made a copy of the image. I've also tried accessing a close() attribute of Image and with image, no success.
| [
"You can provide a file-like object instead of a filename to the Image.open function. So try this:\ndef do_post_processing(filename):\n with open(str(filename), 'rb') as f:\n image = Image.open(f)\n ...\n del new_image, image\n os.remove(str(filename))\n os.rename(...)\n\n"
] | [
16
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0003135328_python_python_imaging_library.txt |
Q:
Is Python (Django) experience professionaly comparable to Ruby on Rails?
I ask this because there seems to be a few more jobs available (at least by telecommute) in RoR. If an employer sees significant Python/Django experience on a resume, would it be plausible to believe that the developer would be able quickly learn Rails?
A:
My experience is, that the more languages and/or frameworks you know, the easier it is to learn a new language. So if you have pretty good experience in programming it shouldn't be a big problem.
Python and Ruby are both dynamic and completely object oriented Languages. Just the syntax is a little bit different. i.e. where python uses indention two mark blocks of code, ruby uses {|begin|then|do|... and }|end to mark the beginning and end of a block.
As far as I know Django is a little bit more low level like merb or sinatra. But Django embraces the MVC style. So there you must not learn something new.
But to really know how quickly you can learn RoR is just trying, it can be fun. Just try it out in some freetime. IMHO it can be very easy to learn, especially for someone experienced with other MVC frameworks with similar languages.
A:
I can't speak for all organizations, but as a hiring manager where I work, yes. I am really interested in experience with MVC in general. The specific technology / framework doesn't concern me as much as the fact that you understand what a model/view/controller framework is good for, and when to use it.
That said, if I see RoR and Python/Django, I'm probably going to pigeon-hole you as a front-end developer and push you towards the web apps division as opposed to our infrastructure division.
A:
I interviewed for a Rails job once. I had almost no experience in Rails, although I had a fair amount of experience with Python and Django. I told the interviewer this up front, and I still got through several rounds of interviews, since the technical guys figured I could pick up the Rails stuff easily enough. (Ultimately I didn't get the job. Ah, well.)
But it probably depends on who is interviewing you. Some people might see the experience as comparable, others might not.
| Is Python (Django) experience professionaly comparable to Ruby on Rails? | I ask this because there seems to be a few more jobs available (at least by telecommute) in RoR. If an employer sees significant Python/Django experience on a resume, would it be plausible to believe that the developer would be able quickly learn Rails?
| [
"My experience is, that the more languages and/or frameworks you know, the easier it is to learn a new language. So if you have pretty good experience in programming it shouldn't be a big problem. \nPython and Ruby are both dynamic and completely object oriented Languages. Just the syntax is a little bit different. i.e. where python uses indention two mark blocks of code, ruby uses {|begin|then|do|... and }|end to mark the beginning and end of a block.\nAs far as I know Django is a little bit more low level like merb or sinatra. But Django embraces the MVC style. So there you must not learn something new.\nBut to really know how quickly you can learn RoR is just trying, it can be fun. Just try it out in some freetime. IMHO it can be very easy to learn, especially for someone experienced with other MVC frameworks with similar languages.\n",
"I can't speak for all organizations, but as a hiring manager where I work, yes. I am really interested in experience with MVC in general. The specific technology / framework doesn't concern me as much as the fact that you understand what a model/view/controller framework is good for, and when to use it. \nThat said, if I see RoR and Python/Django, I'm probably going to pigeon-hole you as a front-end developer and push you towards the web apps division as opposed to our infrastructure division.\n",
"I interviewed for a Rails job once. I had almost no experience in Rails, although I had a fair amount of experience with Python and Django. I told the interviewer this up front, and I still got through several rounds of interviews, since the technical guys figured I could pick up the Rails stuff easily enough. (Ultimately I didn't get the job. Ah, well.)\nBut it probably depends on who is interviewing you. Some people might see the experience as comparable, others might not.\n"
] | [
2,
0,
0
] | [] | [] | [
"django",
"python",
"ruby_on_rails"
] | stackoverflow_0003136131_django_python_ruby_on_rails.txt |
Q:
Deleting already printed in Python
For practice, I'm trying to do some stuff in Python. I've decided to make a simple hangman game - I'm not making a GUI. The game would start with a simple input(). Now, I'd like next line to, beside asking for input, to delete the hidden word. I've tried using \b (backspace character), but it's not working. Something like:
word = input("Your word: ")
for i in range(len(word) + 12):
print("\b")
Now, printing the backlash character is supposed to delete the input and "Your word", but it isn't doing anything. If I do this in IDLE I get squares, and I get nothing if I open it by clicking.
How to accomplish this? I'm afraid I wasn't too clear with my question, but I hope you'll see what I meant. :)
A:
\b does not erase the character before the cursor, it simply moves the cursor left one column. If you want text entry without echoing the characters then look at getpass.
A:
I assume the player entering the word wants to be sure they've entered it correctly so you probably want to display the word as they're typing it right?
How about printing enough \ns to move it off the screen when they're done or issue a clear screen command?
You mentioned this was a simple game so a simple solution seems fitting.
[Edit] Here's a simple routine to clear the console on just about any platform (taken from here):
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
import os
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print '\n' * numlines
A:
word = raw_input("Your word: ")
import sys
sys.stdout.write("\x1b[1A" + 25*" " + "\n")
This will replace the last line printed with 25 spaces.
A:
I think part of your problem is that input is echoing the Enter that terminates your word entry. Your backspaces are on another line, and I don't think they'll back up to the previous line. I seem to recall a SO question about how to prevent that, but I can't find it just now.
Also, I believe print, by default, will output a newline on each call, so each backspace would be on its own line. You can change this by using an end='' argument.
Edit: I found the question I was thinking of, but it doesn't look like there's any help there. You can look at it if you like: Python input that ends without showing a newline
| Deleting already printed in Python | For practice, I'm trying to do some stuff in Python. I've decided to make a simple hangman game - I'm not making a GUI. The game would start with a simple input(). Now, I'd like next line to, beside asking for input, to delete the hidden word. I've tried using \b (backspace character), but it's not working. Something like:
word = input("Your word: ")
for i in range(len(word) + 12):
print("\b")
Now, printing the backlash character is supposed to delete the input and "Your word", but it isn't doing anything. If I do this in IDLE I get squares, and I get nothing if I open it by clicking.
How to accomplish this? I'm afraid I wasn't too clear with my question, but I hope you'll see what I meant. :)
| [
"\\b does not erase the character before the cursor, it simply moves the cursor left one column. If you want text entry without echoing the characters then look at getpass.\n",
"I assume the player entering the word wants to be sure they've entered it correctly so you probably want to display the word as they're typing it right?\nHow about printing enough \\ns to move it off the screen when they're done or issue a clear screen command?\nYou mentioned this was a simple game so a simple solution seems fitting.\n[Edit] Here's a simple routine to clear the console on just about any platform (taken from here):\ndef clearscreen(numlines=100):\n \"\"\"Clear the console.\n numlines is an optional argument used only as a fall-back.\n \"\"\"\n import os\n if os.name == \"posix\":\n # Unix/Linux/MacOS/BSD/etc\n os.system('clear')\n elif os.name in (\"nt\", \"dos\", \"ce\"):\n # DOS/Windows\n os.system('CLS')\n else:\n # Fallback for other operating systems.\n print '\\n' * numlines\n\n",
"word = raw_input(\"Your word: \")\nimport sys\nsys.stdout.write(\"\\x1b[1A\" + 25*\" \" + \"\\n\")\n\nThis will replace the last line printed with 25 spaces.\n",
"I think part of your problem is that input is echoing the Enter that terminates your word entry. Your backspaces are on another line, and I don't think they'll back up to the previous line. I seem to recall a SO question about how to prevent that, but I can't find it just now.\nAlso, I believe print, by default, will output a newline on each call, so each backspace would be on its own line. You can change this by using an end='' argument.\nEdit: I found the question I was thinking of, but it doesn't look like there's any help there. You can look at it if you like: Python input that ends without showing a newline\n"
] | [
4,
2,
2,
1
] | [] | [] | [
"printing",
"python",
"python_3.x"
] | stackoverflow_0003136202_printing_python_python_3.x.txt |
Q:
Find MacOSX version from Python
Currently I am using this:
def _get_mac_ver():
import subprocess
p = subprocess.Popen(['sw_vers', '-productVersion'], stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.strip()
Is there a better version (eg: by using built-in Python API)?
>>> print _get_mac_ver()
10.6.3
Note: I tried os.uname()[2] which prints 10.3.0 on a Snow Leopard system.
A:
True to the philosophy that python comes with batteries included, there is a module in the standard library to do this: platform.
See in particular the `mac_ver()' function:
>>> import platform
>>> platform.mac_ver()
('10.6.3', ('', '', ''), 'i386')
>>> print platform.mac_ver()[0]
10.6.3
| Find MacOSX version from Python | Currently I am using this:
def _get_mac_ver():
import subprocess
p = subprocess.Popen(['sw_vers', '-productVersion'], stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.strip()
Is there a better version (eg: by using built-in Python API)?
>>> print _get_mac_ver()
10.6.3
Note: I tried os.uname()[2] which prints 10.3.0 on a Snow Leopard system.
| [
"True to the philosophy that python comes with batteries included, there is a module in the standard library to do this: platform. \nSee in particular the `mac_ver()' function:\n>>> import platform\n>>> platform.mac_ver()\n('10.6.3', ('', '', ''), 'i386')\n>>> print platform.mac_ver()[0]\n10.6.3\n\n"
] | [
8
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0003136818_macos_python.txt |
Q:
Find root of implicit function in Python
I have an implicit function, for example:
f(x,y) = x**y + y**y - 3*x
I want to solve the root on a meshgrid. So f(x,y) = 0
Drawing the solution is easy:
x = linspace(-2,2,11)
y = linspace(-2,2,11)
(X,Y) = meshgrid(x,y)
A = X**Y + Y**Y - 3*X
contour(X,Y,A,0)
This works great, I have a drawing of the curve I need, however I would like to have the data that is in the plot and not only the visual plot. So how do I find the data of the plot?
A:
You can get "the data that is in the [matplotlib] plot" using:
cs = contour(X,Y,A,0)
data = cs.collections[0].get_paths()[1]
There are a variety of algorithms for calculating the contours directly, though I don't know of any numpy/scipy versions. Marching squares is the one I always here about, although the algorithm is patented and there are severe restrictions on it's use, so I doubt matplotlib uses it. Here's a link with a bit of chat on how matplotlib calculates the contours.
| Find root of implicit function in Python | I have an implicit function, for example:
f(x,y) = x**y + y**y - 3*x
I want to solve the root on a meshgrid. So f(x,y) = 0
Drawing the solution is easy:
x = linspace(-2,2,11)
y = linspace(-2,2,11)
(X,Y) = meshgrid(x,y)
A = X**Y + Y**Y - 3*X
contour(X,Y,A,0)
This works great, I have a drawing of the curve I need, however I would like to have the data that is in the plot and not only the visual plot. So how do I find the data of the plot?
| [
"You can get \"the data that is in the [matplotlib] plot\" using:\ncs = contour(X,Y,A,0)\ndata = cs.collections[0].get_paths()[1]\n\nThere are a variety of algorithms for calculating the contours directly, though I don't know of any numpy/scipy versions. Marching squares is the one I always here about, although the algorithm is patented and there are severe restrictions on it's use, so I doubt matplotlib uses it. Here's a link with a bit of chat on how matplotlib calculates the contours.\n"
] | [
3
] | [] | [] | [
"implicit",
"numpy",
"python",
"root"
] | stackoverflow_0003136432_implicit_numpy_python_root.txt |
Q:
EDI X12 Templates in Python (Most likely django or jinja) (w/ sqlalchemy)
My Case:
I'm working on a system that will need to create various X12 files for health care (insurance) transactions and inquiries (Specifically 270 Eligibility and 837 Claim).
I know there are good tools out there (pyx12 specifically) for converting between XML and X12, and actually I've gone as far as importing some components from pyx12 to actually create/manipulate x12 data.
Even considering that, after researching the formats a bit, I'm starting to believe that I could have an easier time generating these formats using a template language. I think that it would be a matter of defining for loops for any segments&loops that need to be repeated per portion claim/inquiry, and the header regions are going to be somewhat static besides whatever element values that could be easily updated by my context.
Almost all of my records are coming out from sqlalchemy so it should be easy enough to loop through my records in the database where relations are very well defined and mapped.
My questions:
I suppose this is less of a question and more of a quest for advice & insight, so feel free to shoot with all of that. IE, Do you think this is a good idea or a waste of time?
For any die-hard x12 people, what kind of problems have you run into building x12 from scratch? What should I watch out for?
Has this style of implementation been done before? Are there examples of specific X12 format templates available, from any language? (I did look with little success)
Just a side note:
We're already working with python and django, so that template language is available to us. If we need to do these things as a background process we'll either do the hacky config environment tricks to get django templates to work outside of our django project or else use jinja instead--which is nearly interchangeable.
A:
I haven't worked on x12 specifically, but I've often generated all kinds of textual formats by templating, and I can confirm it works like a charm. I would recommend mako (because it basically gives you all the power of Python for your templating), but if you're keen on staying with django-like templates, then jinja2 is definitely the way to go. Its main advantages include speed, ease of debugging, and a richer templating library, as well as the ease of stand-alone use.
| EDI X12 Templates in Python (Most likely django or jinja) (w/ sqlalchemy) | My Case:
I'm working on a system that will need to create various X12 files for health care (insurance) transactions and inquiries (Specifically 270 Eligibility and 837 Claim).
I know there are good tools out there (pyx12 specifically) for converting between XML and X12, and actually I've gone as far as importing some components from pyx12 to actually create/manipulate x12 data.
Even considering that, after researching the formats a bit, I'm starting to believe that I could have an easier time generating these formats using a template language. I think that it would be a matter of defining for loops for any segments&loops that need to be repeated per portion claim/inquiry, and the header regions are going to be somewhat static besides whatever element values that could be easily updated by my context.
Almost all of my records are coming out from sqlalchemy so it should be easy enough to loop through my records in the database where relations are very well defined and mapped.
My questions:
I suppose this is less of a question and more of a quest for advice & insight, so feel free to shoot with all of that. IE, Do you think this is a good idea or a waste of time?
For any die-hard x12 people, what kind of problems have you run into building x12 from scratch? What should I watch out for?
Has this style of implementation been done before? Are there examples of specific X12 format templates available, from any language? (I did look with little success)
Just a side note:
We're already working with python and django, so that template language is available to us. If we need to do these things as a background process we'll either do the hacky config environment tricks to get django templates to work outside of our django project or else use jinja instead--which is nearly interchangeable.
| [
"I haven't worked on x12 specifically, but I've often generated all kinds of textual formats by templating, and I can confirm it works like a charm. I would recommend mako (because it basically gives you all the power of Python for your templating), but if you're keen on staying with django-like templates, then jinja2 is definitely the way to go. Its main advantages include speed, ease of debugging, and a richer templating library, as well as the ease of stand-alone use.\n"
] | [
1
] | [] | [] | [
"python",
"sqlalchemy",
"templates",
"x12"
] | stackoverflow_0003137023_python_sqlalchemy_templates_x12.txt |
Q:
python sql interval
With PostgreSQL, one of my tables has an 'interval' column, values of which I would like to extract as something I can manipulate (datetime.timedelta?); however I am using PyGreSQL which seems to be returning intervals as strings, which is less than helpful.
Where should I be looking to either parse the interval or make PyGreSQL return it as a <something useful>?
A:
Use Psycopg 2. It correctly converts between Postgres's interval data type and Python's timedelta.
| python sql interval | With PostgreSQL, one of my tables has an 'interval' column, values of which I would like to extract as something I can manipulate (datetime.timedelta?); however I am using PyGreSQL which seems to be returning intervals as strings, which is less than helpful.
Where should I be looking to either parse the interval or make PyGreSQL return it as a <something useful>?
| [
"Use Psycopg 2. It correctly converts between Postgres's interval data type and Python's timedelta.\n"
] | [
3
] | [] | [] | [
"postgresql",
"pygresql",
"python",
"sql"
] | stackoverflow_0003134699_postgresql_pygresql_python_sql.txt |
Q:
How to write python web service server WSDL?
All the stuff I am seeing points me towards writing clients.
A:
I believe the popular approach is to hand-write WSDL first (typically with an XML-oriented editor, of course, such as oxygen), then generate a Python server skeleton from it with wsdl2py. Unfortunately I have no first-hand experience with this so I'm not sure if it works as well as it's advertised to.
| How to write python web service server WSDL? | All the stuff I am seeing points me towards writing clients.
| [
"I believe the popular approach is to hand-write WSDL first (typically with an XML-oriented editor, of course, such as oxygen), then generate a Python server skeleton from it with wsdl2py. Unfortunately I have no first-hand experience with this so I'm not sure if it works as well as it's advertised to.\n"
] | [
0
] | [] | [] | [
"python",
"python_3.x",
"web_services"
] | stackoverflow_0003136778_python_python_3.x_web_services.txt |
Q:
Using an StringIO object for holding uu.encode/uu.decode data
I would like to do the following:
import StringIO, uu
my_data = StringIO.StringIO() # this is a file-like object
uu.encode(in_file, my_data)
# do stuff with my data (send over network)
uu.decode(my_data, out_file) # here I finally write to disk
The above code works. However, if I implement the previous step as a property in an object:
@property
def content(self):
out = StringIO.StringIO()
uu.decode(self._content, out)
return out.getvalue()
@content.setter
def content(self, value):
self._content = StringIO.StringIO()
with open('value', 'rb') as stream:
uu.encode(stream, self._content)
but when I do it like that, self._content is empty (None, to be precise). Any ideas?
A:
self._content is left with the "current point" at its end after the content.setter method has written to it. You probably want to add self._content.seek(0) at the end of that method so you can next read that pseudo-file from the beginning (reading while starting from the end will return "nothing more", quite correctly since it does start at the end, and that's probably what's leaving you with the impression that it's "empty";-).
| Using an StringIO object for holding uu.encode/uu.decode data | I would like to do the following:
import StringIO, uu
my_data = StringIO.StringIO() # this is a file-like object
uu.encode(in_file, my_data)
# do stuff with my data (send over network)
uu.decode(my_data, out_file) # here I finally write to disk
The above code works. However, if I implement the previous step as a property in an object:
@property
def content(self):
out = StringIO.StringIO()
uu.decode(self._content, out)
return out.getvalue()
@content.setter
def content(self, value):
self._content = StringIO.StringIO()
with open('value', 'rb') as stream:
uu.encode(stream, self._content)
but when I do it like that, self._content is empty (None, to be precise). Any ideas?
| [
"self._content is left with the \"current point\" at its end after the content.setter method has written to it. You probably want to add self._content.seek(0) at the end of that method so you can next read that pseudo-file from the beginning (reading while starting from the end will return \"nothing more\", quite correctly since it does start at the end, and that's probably what's leaving you with the impression that it's \"empty\";-).\n"
] | [
1
] | [] | [] | [
"encoding",
"python"
] | stackoverflow_0003136697_encoding_python.txt |
Q:
Is it possible copy the contents of multiple widgets simultaneous in Tkinter?
I'm trying to add a feature in python that copies the entire contents of two text widgets. How would one go about that?
Pseudo Code:
text1.SelectAll()
C1 = text1.get(Copy)
text2.SelectAll()
C2 = text2.get(Copy)
Paste('Widget 1:\n\n' + C1 + 'Widget 2:\n\n' + C2 )
A:
Just do (if you have a from Tkinter import * -- I don't like it but many use it):
C1 = text1.get(1.0, END)
C2 = text2.get(1.0, END)
Now you have the two strings. I'm not sure where that Paste is supposed to put the text into -- if you mean to replace the previous contents of text2, for example, just do
text2.delete(1.0, END)
text2.insert(END, "Whatever: %s and: %s" % (C1, C2))
To learn more about Tkinter text controls, read this chapter in effbot's online Tkinter book.
| Is it possible copy the contents of multiple widgets simultaneous in Tkinter? | I'm trying to add a feature in python that copies the entire contents of two text widgets. How would one go about that?
Pseudo Code:
text1.SelectAll()
C1 = text1.get(Copy)
text2.SelectAll()
C2 = text2.get(Copy)
Paste('Widget 1:\n\n' + C1 + 'Widget 2:\n\n' + C2 )
| [
"Just do (if you have a from Tkinter import * -- I don't like it but many use it):\nC1 = text1.get(1.0, END)\nC2 = text2.get(1.0, END)\n\nNow you have the two strings. I'm not sure where that Paste is supposed to put the text into -- if you mean to replace the previous contents of text2, for example, just do\ntext2.delete(1.0, END)\ntext2.insert(END, \"Whatever: %s and: %s\" % (C1, C2))\n\nTo learn more about Tkinter text controls, read this chapter in effbot's online Tkinter book.\n"
] | [
3
] | [] | [] | [
"copy",
"python",
"tkinter",
"widget"
] | stackoverflow_0003135646_copy_python_tkinter_widget.txt |
Q:
Highlight selected Tab - Python webpage
I am trying to develop my first python web project. It have multiple tabs (like apple.com have Store, iPhone, iPad etc tabs) and when user click on any tab, the page is served from server.
I want to make sure that the selected tab will have different background color when page is loaded.
Which is a best way to do it? JavaScript/CSS/Directly from server? and How?
Thanks.
A:
I think the best way would be through CSS. You can handle it by adding the pseudoclass :active to the CSS.
Other way is serving the page with a new class added to the tab, which will change the background color, but I would not recommend that.
| Highlight selected Tab - Python webpage | I am trying to develop my first python web project. It have multiple tabs (like apple.com have Store, iPhone, iPad etc tabs) and when user click on any tab, the page is served from server.
I want to make sure that the selected tab will have different background color when page is loaded.
Which is a best way to do it? JavaScript/CSS/Directly from server? and How?
Thanks.
| [
"I think the best way would be through CSS. You can handle it by adding the pseudoclass :active to the CSS.\nOther way is serving the page with a new class added to the tab, which will change the background color, but I would not recommend that.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003137167_python.txt |
Q:
How do I undo/redo something in a Tkinter text widget?
I need to make both a Control-Z and Shift-Control-Z function in Python. Anyone have any Idea?
Also I need to select the contents of an entire text widget, anyone know how to go about that?
A:
For the undo mechanism, check the UndoDelegator.py of Idle in combination with EditorWindow.py.
To select the entire contents of a Text widget, you can do:
# remove previous selection, if any
text_widget.tag_remove(Tkinter.SEL, "1.0", Tkinter.END)
# select all
text_widget.tag_add(Tkinter.SEL, "1.0", Tkinter.END)
# place cursor
text_widget.mark_set(Tkinter.INSERT, Tkinter.END)
| How do I undo/redo something in a Tkinter text widget? | I need to make both a Control-Z and Shift-Control-Z function in Python. Anyone have any Idea?
Also I need to select the contents of an entire text widget, anyone know how to go about that?
| [
"For the undo mechanism, check the UndoDelegator.py of Idle in combination with EditorWindow.py.\nTo select the entire contents of a Text widget, you can do:\n# remove previous selection, if any\ntext_widget.tag_remove(Tkinter.SEL, \"1.0\", Tkinter.END)\n# select all\ntext_widget.tag_add(Tkinter.SEL, \"1.0\", Tkinter.END)\n# place cursor\ntext_widget.mark_set(Tkinter.INSERT, Tkinter.END)\n\n"
] | [
2
] | [] | [] | [
"python",
"tkinter",
"undo_redo"
] | stackoverflow_0003135924_python_tkinter_undo_redo.txt |
Q:
How to reference object properties in another module
I am relatively new to Python having used C# for many years and I'm hoping someone can help me with this question. I have a module called actuators.py that contains a number of classes for defining properties and methods for the servos I use in a robot project. In another module called robot.py, I instantiate my actuators like this:
import actuators as Actuators
myActuators = Actuators.AllActuators()
This allows me to access the properties of my servos as long as I am in the robot.py module. For example, I can write:
print myActuators.HeadTilt.MinPosition
to get the minimum value allowed for the servo that tilts the robot's head. So far so good.
Now I want to access these same values in a separate thread that is defined by a different module called tilt_head.py. I assume I need to import a reference to the robot.py module, but doing this ends up re-executing all the code in robot.py whereas all I really want is a static reference to the myActuators object. And I can't use
from robot.py import myActuators
because myActuators is not a module.
In C#, I would do this using a declaration like this:
public static Actuators myActuators;
which then allows me to reference myActuators in any other file within my project. Is there a way to do something similar in Python? If you need my actual code, I will be happy to post it.
Thanks!
A:
And I can't use
from robot.py import myActuators
because myActuators is not a module.
But myActuators doesn't need to be a module. You can do exactly that. (Though you'll want to use just robot rather than robot.py)
http://docs.python.org/reference/simple_stmts.html#import
As well:
http://docs.python.org/tutorial/modules.html#more-on-modules
"A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module is imported somewhere."
So using a script that imports robot and then tilt_head, the executable stuff in robot.py will NOT be run multiple times.
Of course, if robot.py is intended to be the main module of the program, then I'd suggest going with A. Levy's answer.
A:
You should be able to simply use:
from robot import myActuators
You can't say "from robot.py" because the name there is a module name, not a file name.
BTW: I'm not sure why you are doing import actuators as Actuators. Why do you want to change the case? Modules are most commonly lowercase.
A:
As others have been saying, you can actually import myActuators from the robot module. To solve your problem of the code in robot being re-executed, the standard Python approach is to wrap the stand-alone code in an if __name__ == '__main__': so that it will only be executed when the module is used as a standalone app, but not when it is imported.
E.G.
# Things that are defined when robot.py is used as a module
# and when used standalone.
import actuators as Actuators
myActuators = Actuators.AllActuators()
if __name__ == '__main__':
# Stuff that you only want executed when running robot.py
Then when you want to use robot.py in another module, you should be able to do this:
from robot import myActuators
EDIT:
Actually, as JAB pointed out, I was a little confused in my explanation of conditional execution. your code won't be re-executed if you reload the module. The module loading machinery handles reloading of modules to make sure that they only get loaded and defined one time. All subsequent loads are references to the previously loaded module. If, however, you do have some steps that you only want to happen when you are running the module as a script, then you can place them in the if block and they won't be executed when you load robots from another module.
I guess it doesn't really solve your problem, though it seems like your problem was really an incorrect import syntax.
A:
I would guess that you can access that object as robot.myActuators because it already exists in the process, inside the robot.py namespace.
A:
Many thanks for all the answers and pointers. As it turns out, my problem was a recursive import that ended up trying to create an object more than once. By sorting out the instance creation a little more logically, I was finally able to make the problem go away.
| How to reference object properties in another module | I am relatively new to Python having used C# for many years and I'm hoping someone can help me with this question. I have a module called actuators.py that contains a number of classes for defining properties and methods for the servos I use in a robot project. In another module called robot.py, I instantiate my actuators like this:
import actuators as Actuators
myActuators = Actuators.AllActuators()
This allows me to access the properties of my servos as long as I am in the robot.py module. For example, I can write:
print myActuators.HeadTilt.MinPosition
to get the minimum value allowed for the servo that tilts the robot's head. So far so good.
Now I want to access these same values in a separate thread that is defined by a different module called tilt_head.py. I assume I need to import a reference to the robot.py module, but doing this ends up re-executing all the code in robot.py whereas all I really want is a static reference to the myActuators object. And I can't use
from robot.py import myActuators
because myActuators is not a module.
In C#, I would do this using a declaration like this:
public static Actuators myActuators;
which then allows me to reference myActuators in any other file within my project. Is there a way to do something similar in Python? If you need my actual code, I will be happy to post it.
Thanks!
| [
"\nAnd I can't use\nfrom robot.py import myActuators\n\nbecause myActuators is not a module.\n\nBut myActuators doesn't need to be a module. You can do exactly that. (Though you'll want to use just robot rather than robot.py)\nhttp://docs.python.org/reference/simple_stmts.html#import\nAs well:\nhttp://docs.python.org/tutorial/modules.html#more-on-modules\n\"A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module is imported somewhere.\"\nSo using a script that imports robot and then tilt_head, the executable stuff in robot.py will NOT be run multiple times.\nOf course, if robot.py is intended to be the main module of the program, then I'd suggest going with A. Levy's answer.\n",
"You should be able to simply use:\nfrom robot import myActuators\n\nYou can't say \"from robot.py\" because the name there is a module name, not a file name.\nBTW: I'm not sure why you are doing import actuators as Actuators. Why do you want to change the case? Modules are most commonly lowercase.\n",
"As others have been saying, you can actually import myActuators from the robot module. To solve your problem of the code in robot being re-executed, the standard Python approach is to wrap the stand-alone code in an if __name__ == '__main__': so that it will only be executed when the module is used as a standalone app, but not when it is imported.\nE.G.\n# Things that are defined when robot.py is used as a module\n# and when used standalone.\nimport actuators as Actuators\n\nmyActuators = Actuators.AllActuators()\n\nif __name__ == '__main__':\n # Stuff that you only want executed when running robot.py\n\nThen when you want to use robot.py in another module, you should be able to do this:\nfrom robot import myActuators\n\nEDIT:\nActually, as JAB pointed out, I was a little confused in my explanation of conditional execution. your code won't be re-executed if you reload the module. The module loading machinery handles reloading of modules to make sure that they only get loaded and defined one time. All subsequent loads are references to the previously loaded module. If, however, you do have some steps that you only want to happen when you are running the module as a script, then you can place them in the if block and they won't be executed when you load robots from another module. \nI guess it doesn't really solve your problem, though it seems like your problem was really an incorrect import syntax.\n",
"I would guess that you can access that object as robot.myActuators because it already exists in the process, inside the robot.py namespace.\n",
"Many thanks for all the answers and pointers. As it turns out, my problem was a recursive import that ended up trying to create an object more than once. By sorting out the instance creation a little more logically, I was finally able to make the problem go away.\n"
] | [
2,
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003134549_python.txt |
Q:
How to layout all children of a wxPanel?
I have a wxPython application which allows the users to select items from menus that then change what is visible on the screen. This often requires a recalculation of the layout of panels. I'd like to be able to call the layout of all the children of a panel (and the children of those children) in reverse order. That is, the items with no children have their Layout() function called first, then their parents, and so on.
Otherwise I have to keep all kinds of knowledge about the parents of panels in the codes. (i.e. how many parents will be affected by a change in this-or-that panel).
A:
Have a look at wxSizers and some examples for a fluid way to layout forms.
You can specify heights, poportions etc. etc. and then let the layout code do the rest for you :)
A:
More in response to your comment to Jon Cage's answer, than to your
original question (which was perfectly answered by Jon):
The user might find it irritating, if the position of every element in
your dialog changes, when he makes a choice. Maybe it'll look better,
if only the "variable part" is updated. To achieve this, you could
make a panel for each set of additional controls. The minimum size of
each panel should be the minimum size of the largest of these
panels. Depending on the user's choice you can hide or show the
desired panel.
Alternatively, wxChoicebook might be what you need?
| How to layout all children of a wxPanel? | I have a wxPython application which allows the users to select items from menus that then change what is visible on the screen. This often requires a recalculation of the layout of panels. I'd like to be able to call the layout of all the children of a panel (and the children of those children) in reverse order. That is, the items with no children have their Layout() function called first, then their parents, and so on.
Otherwise I have to keep all kinds of knowledge about the parents of panels in the codes. (i.e. how many parents will be affected by a change in this-or-that panel).
| [
"Have a look at wxSizers and some examples for a fluid way to layout forms.\nYou can specify heights, poportions etc. etc. and then let the layout code do the rest for you :)\n",
"More in response to your comment to Jon Cage's answer, than to your\noriginal question (which was perfectly answered by Jon):\nThe user might find it irritating, if the position of every element in\nyour dialog changes, when he makes a choice. Maybe it'll look better,\nif only the \"variable part\" is updated. To achieve this, you could\nmake a panel for each set of additional controls. The minimum size of\neach panel should be the minimum size of the largest of these\npanels. Depending on the user's choice you can hide or show the\ndesired panel.\nAlternatively, wxChoicebook might be what you need?\n"
] | [
0,
0
] | [] | [] | [
"dry",
"model_view_controller",
"python",
"wxpython",
"wxwidgets"
] | stackoverflow_0003136997_dry_model_view_controller_python_wxpython_wxwidgets.txt |
Q:
Test assertions for tuples with floats
I have a function that returns a tuple that, among others, contains a float value. Usually I use assertAlmostEquals to compare those, but this does not work with tuples. Also, the tuple contains other data-types as well. Currently I am asserting every element of the tuple individually, but that gets too much for a list of such tuples. Is there any good way to write assertions for such cases?
Consider this function:
def f(a):
return [(1.0/x, x * 2) for x in a]
Now I want to write a test for it:
def testF(self):
self.assertEqual(f(range(1,3)), [(1.0, 2), (0.5, 4)])
This will fail because the result of 1.0/2 is not exactly 0.5. Can anyone recommend a good way of writing such an assertion in a readable way?
Edit: Actually 1.0/2 is exactly 0.5, but you get my meaning.
A:
Well how about pimping up your function with couple of zips:
def testF(self):
for tuple1, tuple2 in zip(f(range(1,3)), [(1.0, 2), (0.5, 4)]):
for val1, val2 in zip(tuple1, tuple2):
if type(val2) is float:
self.assertAlmostEquals(val1, val2, 5)
else:
self.assertEquals(val1, val2)
My premise here is that it is better to use multiple asserts in a loop as to get the exact values where it breaks, vs. using single assert with all().
ps. If you have other numeric types you want to use assertAlmostEquals for, you can change the if above to e.g. if type(val2) in [float, decimal.Decimal]:
A:
I'll probably define a recursive function.
from collections import Iterable;
def recursiveAssertAlmostEqual(testCase, first, second, *args, **kwargs):
if isinstance(first, Iterable) and isinstance(second, Iterable):
for a, b in zip(first, second):
recursiveAssertAlmostEqual(testCase, a, b, *args, **kwargs)
else:
testCase.assertAlmostEqual(first, second, *args, **kwargs)
(Note that it will assert (1, 2) and [1, 2] are equal.)
A:
What I have done in the past is to write a custom-function that establishes validity for a complicated data type, and then used assert( IsFooValid( foo ) ). The validity function can simply return true/false, but it's usually better for it to raise AssertionError with an appropriate message.
| Test assertions for tuples with floats | I have a function that returns a tuple that, among others, contains a float value. Usually I use assertAlmostEquals to compare those, but this does not work with tuples. Also, the tuple contains other data-types as well. Currently I am asserting every element of the tuple individually, but that gets too much for a list of such tuples. Is there any good way to write assertions for such cases?
Consider this function:
def f(a):
return [(1.0/x, x * 2) for x in a]
Now I want to write a test for it:
def testF(self):
self.assertEqual(f(range(1,3)), [(1.0, 2), (0.5, 4)])
This will fail because the result of 1.0/2 is not exactly 0.5. Can anyone recommend a good way of writing such an assertion in a readable way?
Edit: Actually 1.0/2 is exactly 0.5, but you get my meaning.
| [
"Well how about pimping up your function with couple of zips:\ndef testF(self):\n for tuple1, tuple2 in zip(f(range(1,3)), [(1.0, 2), (0.5, 4)]):\n for val1, val2 in zip(tuple1, tuple2):\n if type(val2) is float:\n self.assertAlmostEquals(val1, val2, 5)\n else:\n self.assertEquals(val1, val2)\n\nMy premise here is that it is better to use multiple asserts in a loop as to get the exact values where it breaks, vs. using single assert with all().\nps. If you have other numeric types you want to use assertAlmostEquals for, you can change the if above to e.g. if type(val2) in [float, decimal.Decimal]: \n",
"I'll probably define a recursive function.\nfrom collections import Iterable;\n\ndef recursiveAssertAlmostEqual(testCase, first, second, *args, **kwargs):\n if isinstance(first, Iterable) and isinstance(second, Iterable):\n for a, b in zip(first, second):\n recursiveAssertAlmostEqual(testCase, a, b, *args, **kwargs)\n else:\n testCase.assertAlmostEqual(first, second, *args, **kwargs)\n\n(Note that it will assert (1, 2) and [1, 2] are equal.)\n",
"What I have done in the past is to write a custom-function that establishes validity for a complicated data type, and then used assert( IsFooValid( foo ) ). The validity function can simply return true/false, but it's usually better for it to raise AssertionError with an appropriate message.\n"
] | [
8,
3,
2
] | [] | [] | [
"assert",
"floating_point",
"python",
"tuples",
"unit_testing"
] | stackoverflow_0003022952_assert_floating_point_python_tuples_unit_testing.txt |
Q:
How do you debug (trace execution) of a pylons web application?
How do you debug (trace execution) of a pylons web application?
(using a mac with textmate)
A:
It's really easy
To sum it up, import the python logging module and send debug messages to the terminal on your Mac where you have the paste server running.
import logging
log = logging.getLogger(__name__)
log.debug('Your trace message')
This will show up in whatever terminal your paste server is running in as:
17:14:51,060 DEBUG [your_app.controllers.your_controller] Your trace message
| How do you debug (trace execution) of a pylons web application? | How do you debug (trace execution) of a pylons web application?
(using a mac with textmate)
| [
"It's really easy\nTo sum it up, import the python logging module and send debug messages to the terminal on your Mac where you have the paste server running.\nimport logging\nlog = logging.getLogger(__name__)\nlog.debug('Your trace message')\n\nThis will show up in whatever terminal your paste server is running in as:\n\n17:14:51,060 DEBUG [your_app.controllers.your_controller] Your trace message\n\n"
] | [
1
] | [] | [] | [
"debugging",
"pylons",
"python",
"trace"
] | stackoverflow_0003133206_debugging_pylons_python_trace.txt |
Q:
Python: If an iterator is an expression, is it calculated every time?
Take the following example:
>>> for item in [i * 2 for i in range(1, 10)]:
print item
2
4
6
8
10
12
14
16
18
Is [i * 2 for i in range(1, 10)] computed every time through the loop, or just once and stored? (Also, what is the proper name for that part of the expression?)
One reason I would want to do this is that I only want the results of that list comprehension to be available in the loop.
A:
A good translation of for i in <whatever>: <loopbody>, showing exactly what it does for any <whatever> and any <loopbody>:
_aux = iter(<whatever>)
while True:
try: i = next(_aux)
except StopIteration: break
<loopbody>
except that the pseudo-variable I have here named _aux actually remains unnamed.
So, <whatever> always gets evaluated just once (to get an iter() from it) and the resulting iterator is nexted until it runs out (unless there's some break in the <loopbody>).
With a listcomp, as you've used, the evaluation produces a list object (which in your code sample remains unnamed). In the very similar code:
for item in (i * 2 for i in range(1, 10)): ...
using a genexp rather than the listcomp (syntactically, round parentheses instead of the listcomp's square brackets), it's the next() that actually does most of the work (advancing i and doubling it), instead of lumping all work at construction time -- this takes up less temporary memory, and may save time if the loop body's reasonably likely to break out early, but except in such special conditions (very tight memory or likely early loop termination) a listcomp may typically be (by a wee little bit) faster.
A:
All members of the expression list are calculated once, and then iterated over.
In Python 2.x, the variable used in a LC does leak out into the parent scope, but since the LC has already been evaluated, the only value available is the one used to generate the final element in the resultant list.
A:
In that case, you are constructing a list in memory and then you are iterating over the contents of the list, so yes, it is computed once and stored. it is the no different than doing
i for i in [2,4,6,8]:
print(i)
If you do iter(i * 2 for i in xrange(1,10)), you get an iterator which evaluates on each iteration.
| Python: If an iterator is an expression, is it calculated every time? | Take the following example:
>>> for item in [i * 2 for i in range(1, 10)]:
print item
2
4
6
8
10
12
14
16
18
Is [i * 2 for i in range(1, 10)] computed every time through the loop, or just once and stored? (Also, what is the proper name for that part of the expression?)
One reason I would want to do this is that I only want the results of that list comprehension to be available in the loop.
| [
"A good translation of for i in <whatever>: <loopbody>, showing exactly what it does for any <whatever> and any <loopbody>:\n_aux = iter(<whatever>)\nwhile True:\n try: i = next(_aux)\n except StopIteration: break\n <loopbody>\n\nexcept that the pseudo-variable I have here named _aux actually remains unnamed.\nSo, <whatever> always gets evaluated just once (to get an iter() from it) and the resulting iterator is nexted until it runs out (unless there's some break in the <loopbody>).\nWith a listcomp, as you've used, the evaluation produces a list object (which in your code sample remains unnamed). In the very similar code:\nfor item in (i * 2 for i in range(1, 10)): ...\n\nusing a genexp rather than the listcomp (syntactically, round parentheses instead of the listcomp's square brackets), it's the next() that actually does most of the work (advancing i and doubling it), instead of lumping all work at construction time -- this takes up less temporary memory, and may save time if the loop body's reasonably likely to break out early, but except in such special conditions (very tight memory or likely early loop termination) a listcomp may typically be (by a wee little bit) faster.\n",
"All members of the expression list are calculated once, and then iterated over.\nIn Python 2.x, the variable used in a LC does leak out into the parent scope, but since the LC has already been evaluated, the only value available is the one used to generate the final element in the resultant list.\n",
"In that case, you are constructing a list in memory and then you are iterating over the contents of the list, so yes, it is computed once and stored. it is the no different than doing\ni for i in [2,4,6,8]:\n print(i)\n\nIf you do iter(i * 2 for i in xrange(1,10)), you get an iterator which evaluates on each iteration.\n"
] | [
7,
4,
3
] | [] | [] | [
"iterator",
"loops",
"python"
] | stackoverflow_0003137443_iterator_loops_python.txt |
Q:
Python question relating to dated values in a csv file
I am loading a data file with dated data into a csv.DictReader
The data looks like this:
date, weight, blood_pressure, sugar_level
1/1/01, 120.1, 100.1, 25.2
2/1/01, 130.1, 102.1, 26.2
3/1/01, 110.1, 120.1, 24.2
4/1/01, 130.1, 130.1, 28.2
5/1/01, 160.1, 104.1, 27.0
6/1/01, 150.5, 100.1, 22.5
7/1/01, 120.2, 129.1, 25.2
... etc...
I want to write a function that allows me to pass in the dictionary (read from the csv file), and return the previous value of a column an epoch ago. Since there are no enumerations in Python, I will use enums to 'constrain' the permissible epochs and column names:
The code snippet I have so far looks something like this:
import csv;
headers = ['date', 'weight', 'blood_pressure', 'sugar_level']
data = csv.DictReader(csvfile, headers);
epoch_type = (week_ago, fortnight_ago, month_ago);
column_names = headers[1:];
def function get_previous_value(data, column_name, epoch_name):
""" Note: data is assumed to be sorted in date ascending order """
""" Returns the previous value in the data, using the specified """
""" column name and epoch type """
I would be grateful if someone could show how to implement this function
[Edit]
Changed argument name from 'lookback' to 'epoch_name' to aid clarity
A:
First of all, please don't use ; after commands in python.
import datetime
import csv
WEEK = datetime.timedelta(weeks=1)
DAY = datetime.timedelta(days=1)
MONTH = datetime.timedelta(days=30)
# read the entire file to memory in a dict keyed by date
data = {}
with open('file.csv') as csvfile:
for row in csv.DictReader(csvfile):
data[datetime.datetime.strptime(row['date'], '%d/%m/%y').date()] = row
now just query the data:
# blood pressure one week ago:
print data[(datetime.datetime.now() - WEEK).date()]['blood_pressure']
# the entire data for two months ago:
print data[(datetime.datetime.now() - 2 * MONTH).date()]
As an added bonus, you could use dateutil's relativedeltas to make stuff like "last friday in last month".
EDIT: If the file is too big to fit memory, the best solution would be to use a database.
Read the entire csv file to a sqlite database. You could use python to do this, but sqlite can already import csv files to table format on its own, and using it is faster than using python to read and parse the file.
Then you can just query the database:
import sqlite3
import datetime
# connect to db
con = sqlite3.connect('myfile.db', detect_types=sqlite3.PARSE_DECLTYPES)
date_i_want = datetime.date(2001, 1, 6)
cur.execute('SELECT * FROM data WHERE date = ?', (date_i_want,))
row = cur.fetchone()
A:
>>> epochdict = {'week_ago': 7, 'fortnight_ago': 14, 'month_ago': 30}
>>> datetime.datetime.strptime('1/1/01', '%m/%d/%y').date() + datetime.timedelta(epochdict['week_ago']) < datetime.date.today()
True
| Python question relating to dated values in a csv file | I am loading a data file with dated data into a csv.DictReader
The data looks like this:
date, weight, blood_pressure, sugar_level
1/1/01, 120.1, 100.1, 25.2
2/1/01, 130.1, 102.1, 26.2
3/1/01, 110.1, 120.1, 24.2
4/1/01, 130.1, 130.1, 28.2
5/1/01, 160.1, 104.1, 27.0
6/1/01, 150.5, 100.1, 22.5
7/1/01, 120.2, 129.1, 25.2
... etc...
I want to write a function that allows me to pass in the dictionary (read from the csv file), and return the previous value of a column an epoch ago. Since there are no enumerations in Python, I will use enums to 'constrain' the permissible epochs and column names:
The code snippet I have so far looks something like this:
import csv;
headers = ['date', 'weight', 'blood_pressure', 'sugar_level']
data = csv.DictReader(csvfile, headers);
epoch_type = (week_ago, fortnight_ago, month_ago);
column_names = headers[1:];
def function get_previous_value(data, column_name, epoch_name):
""" Note: data is assumed to be sorted in date ascending order """
""" Returns the previous value in the data, using the specified """
""" column name and epoch type """
I would be grateful if someone could show how to implement this function
[Edit]
Changed argument name from 'lookback' to 'epoch_name' to aid clarity
| [
"First of all, please don't use ; after commands in python.\nimport datetime\nimport csv\n\nWEEK = datetime.timedelta(weeks=1)\nDAY = datetime.timedelta(days=1)\nMONTH = datetime.timedelta(days=30)\n\n# read the entire file to memory in a dict keyed by date\ndata = {}\nwith open('file.csv') as csvfile:\n for row in csv.DictReader(csvfile):\n data[datetime.datetime.strptime(row['date'], '%d/%m/%y').date()] = row\n\nnow just query the data:\n# blood pressure one week ago:\nprint data[(datetime.datetime.now() - WEEK).date()]['blood_pressure']\n\n# the entire data for two months ago:\nprint data[(datetime.datetime.now() - 2 * MONTH).date()]\n\nAs an added bonus, you could use dateutil's relativedeltas to make stuff like \"last friday in last month\".\n\nEDIT: If the file is too big to fit memory, the best solution would be to use a database.\nRead the entire csv file to a sqlite database. You could use python to do this, but sqlite can already import csv files to table format on its own, and using it is faster than using python to read and parse the file.\nThen you can just query the database:\nimport sqlite3\nimport datetime\n\n# connect to db\ncon = sqlite3.connect('myfile.db', detect_types=sqlite3.PARSE_DECLTYPES)\n\ndate_i_want = datetime.date(2001, 1, 6)\ncur.execute('SELECT * FROM data WHERE date = ?', (date_i_want,))\nrow = cur.fetchone()\n\n",
">>> epochdict = {'week_ago': 7, 'fortnight_ago': 14, 'month_ago': 30}\n>>> datetime.datetime.strptime('1/1/01', '%m/%d/%y').date() + datetime.timedelta(epochdict['week_ago']) < datetime.date.today()\nTrue\n\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003137505_python.txt |
Q:
Python: Can a class forbid clients setting new attributes?
I just spent too long on a bug like the following:
>>> class Odp():
def __init__(self):
self.foo = "bar"
>>> o = Odp()
>>> o.raw_foo = 3 # oops - meant o.foo
I have a class with an attribute. I was trying to set it, and wondering why it had no effect. Then, I went back to the original class definition, and saw that the attribute was named something slightly different. Thus, I was creating/setting a new attribute instead of the one meant to.
First off, isn't this exactly the type of error that statically-typed languages are supposed to prevent? In this case, what is the advantage of dynamic typing?
Secondly, is there a way I could have forbidden this when defining Odp, and thus saved myself the trouble?
A:
You can implement a __setattr__ method for the purpose -- that's much more robust than the __slots__ which is often misused for the purpose (for example, __slots__ is automatically "lost" when the class is inherited from, while __setattr__ survives unless explicitly overridden).
def __setattr__(self, name, value):
if hasattr(self, name):
object.__setattr__(self, name, value)
else:
raise TypeError('Cannot set name %r on object of type %s' % (
name, self.__class__.__name__))
You'll have to make sure the hasattr succeeds for the names you do want to be able to set, for example by setting the attributes at a class level or by using object.__setattr__ in your __init__ method rather than direct attribute assignment. (To forbid setting attributes on a class rather than its instances you'll have to define a custom metaclass with a similar special method).
| Python: Can a class forbid clients setting new attributes? | I just spent too long on a bug like the following:
>>> class Odp():
def __init__(self):
self.foo = "bar"
>>> o = Odp()
>>> o.raw_foo = 3 # oops - meant o.foo
I have a class with an attribute. I was trying to set it, and wondering why it had no effect. Then, I went back to the original class definition, and saw that the attribute was named something slightly different. Thus, I was creating/setting a new attribute instead of the one meant to.
First off, isn't this exactly the type of error that statically-typed languages are supposed to prevent? In this case, what is the advantage of dynamic typing?
Secondly, is there a way I could have forbidden this when defining Odp, and thus saved myself the trouble?
| [
"You can implement a __setattr__ method for the purpose -- that's much more robust than the __slots__ which is often misused for the purpose (for example, __slots__ is automatically \"lost\" when the class is inherited from, while __setattr__ survives unless explicitly overridden).\ndef __setattr__(self, name, value):\n if hasattr(self, name):\n object.__setattr__(self, name, value)\n else:\n raise TypeError('Cannot set name %r on object of type %s' % (\n name, self.__class__.__name__))\n\nYou'll have to make sure the hasattr succeeds for the names you do want to be able to set, for example by setting the attributes at a class level or by using object.__setattr__ in your __init__ method rather than direct attribute assignment. (To forbid setting attributes on a class rather than its instances you'll have to define a custom metaclass with a similar special method).\n"
] | [
22
] | [] | [] | [
"oop",
"python",
"typing"
] | stackoverflow_0003137558_oop_python_typing.txt |
Q:
Using enum properties in PyGTK/GObject
This tutorial on using GObject in Python only covers using a property of type gobject.TYPE_FLOAT.
I've adapted it to use an enumerated type:
import pygtk
pygtk.require('2.0')
import gobject
FUEL_NONE = 0
FUEL_SOME = 1
FUEL_FULL = 2
class Car(gobject.GObject):
__gproperties__ = {
'fuel' : (gobject.TYPE_ENUM, # type
'fuel of the car', # nick name
'amount of fuel that remains in the tank', # description
FUEL_SOME, # default value
gobject.PARAM_READWRITE) # flags
}
# <<rest of demo code>>
...but when I attempt to run it I get the following error:
/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py:114: Warning: g_param_spec_enum: assertion `g_enum_get_value (enum_class, default_value) != NULL' failed
type_register(cls, namespace.get('__gtype_name__'))
Traceback (most recent call last):
File "gcar.py", line 9, in <module>
class Car(gobject.GObject):
File "/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py", line 60, in __init__
cls._type_register(cls.__dict__)
File "/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py", line 114, in _type_register
type_register(cls, namespace.get('__gtype_name__'))
TypeError: Error when calling the metaclass bases
could not create param spec for type GEnum (while registering property 'fuel' for GType '__main__+Car')
What am I missing?
A:
It's not enough enough to tell __gproperties__ that it's an enumerated type; you need to register the enumeration with the GObject type system, and then use the GType value you get from that instead of gobject.TYPE_ENUM. At least, that's how it's done in C. I'm not sure what the proper way to do this is PyGTK is, but it might involve writing a .defs file and running pygobject-codegen-2.0 on it.
Of course, it's probably easier to just make the property of type gobject.TYPE_INT with a minimum and maximum value that matches the bounds of your enum, unless you really need the GObject system to understand the details of your enumeration.
| Using enum properties in PyGTK/GObject | This tutorial on using GObject in Python only covers using a property of type gobject.TYPE_FLOAT.
I've adapted it to use an enumerated type:
import pygtk
pygtk.require('2.0')
import gobject
FUEL_NONE = 0
FUEL_SOME = 1
FUEL_FULL = 2
class Car(gobject.GObject):
__gproperties__ = {
'fuel' : (gobject.TYPE_ENUM, # type
'fuel of the car', # nick name
'amount of fuel that remains in the tank', # description
FUEL_SOME, # default value
gobject.PARAM_READWRITE) # flags
}
# <<rest of demo code>>
...but when I attempt to run it I get the following error:
/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py:114: Warning: g_param_spec_enum: assertion `g_enum_get_value (enum_class, default_value) != NULL' failed
type_register(cls, namespace.get('__gtype_name__'))
Traceback (most recent call last):
File "gcar.py", line 9, in <module>
class Car(gobject.GObject):
File "/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py", line 60, in __init__
cls._type_register(cls.__dict__)
File "/usr/lib/pymodules/python2.5/gtk-2.0/gobject/__init__.py", line 114, in _type_register
type_register(cls, namespace.get('__gtype_name__'))
TypeError: Error when calling the metaclass bases
could not create param spec for type GEnum (while registering property 'fuel' for GType '__main__+Car')
What am I missing?
| [
"It's not enough enough to tell __gproperties__ that it's an enumerated type; you need to register the enumeration with the GObject type system, and then use the GType value you get from that instead of gobject.TYPE_ENUM. At least, that's how it's done in C. I'm not sure what the proper way to do this is PyGTK is, but it might involve writing a .defs file and running pygobject-codegen-2.0 on it.\nOf course, it's probably easier to just make the property of type gobject.TYPE_INT with a minimum and maximum value that matches the bounds of your enum, unless you really need the GObject system to understand the details of your enumeration.\n"
] | [
2
] | [] | [] | [
"gobject",
"pygtk",
"python"
] | stackoverflow_0003137262_gobject_pygtk_python.txt |
Q:
Using @property decorator on dicts
I'm trying to use Python's @property decorator on a dict in a class. The idea is that I want a certain value (call it 'message') to be cleared after it is accessed. But I also want another value (call it 'last_message') to contain the last set message, and keep it until another message is set. In my mind, this code would work:
>>> class A(object):
... def __init__(self):
... self._b = {"message": "",
... "last_message": ""}
... @property
... def b(self):
... b = self._b
... self._b["message"] = ""
... return b
... @b.setter
... def b(self, value):
... self._b = value
... self._b["last_message"] = value["message"]
...
>>>
However, it doesn't seem to:
>>> a = A()
>>> a.b["message"] = "hello"
>>> a.b["message"]
''
>>> a.b["last_message"]
''
>>>
I'm not sure what I have done wrong? It seems to me like @property doesn't work like I would expect it to on dicts, but maybe I'm doing something else fundamentally wrong?
Also, I know that I could just use individual values in the class. But this is implemented as a session in a web application and I need it to be a dict. I could either make this work, or make the whole session object to pretend it's a dict, or use individual variables and hack it into workingness throughout the rest of the code base. I would much rather just get this to work.
A:
class MyDict(dict):
def __setitem__(self, key, value):
if key == 'message':
super().__setitem__('message', '')
super().__setitem__('last_message', value)
else:
super().__setitem__(key, value)
class A(object):
def __init__(self):
self._b = MyDict({"message": "",
"last_message": ""})
@property
def b(self):
return self._b
a = A()
a.b['message'] = 'hello'
print(a.b['message'])
# ''
print(a.b['last_message'])
# hello
As I think you've discovered, the reason why your setter wasn't working is because
a.b['message']='hello'
first accesses a.b, which calls the b property's getter, not its setter. The getter returns the dict self._b. Then self._b['message']='hello' causes the dict's __setitem__ is called .
So to fix the problem, you need a special dict (like MyDict).
A:
I may be missing what you are trying to do here, but does this solve your problem?
class A(object):
def __init__(self):
self._b = {'message':'',
'last_message': ''}
@property
def b(self):
b = self._b.copy()
self._b['message'] = ''
return b
@b.setter
def b(self, value):
self._b['message'] = value
self._b['last_message'] = value
if __name__ == "__main__":
a = A()
a.b = "hello"
print a.b
print a.b
print a.b["last_message"]
$ python dictPropTest.py
{'last_message': 'hello', 'message': 'hello'}
{'last_message': 'hello', 'message': ''}
hello
| Using @property decorator on dicts | I'm trying to use Python's @property decorator on a dict in a class. The idea is that I want a certain value (call it 'message') to be cleared after it is accessed. But I also want another value (call it 'last_message') to contain the last set message, and keep it until another message is set. In my mind, this code would work:
>>> class A(object):
... def __init__(self):
... self._b = {"message": "",
... "last_message": ""}
... @property
... def b(self):
... b = self._b
... self._b["message"] = ""
... return b
... @b.setter
... def b(self, value):
... self._b = value
... self._b["last_message"] = value["message"]
...
>>>
However, it doesn't seem to:
>>> a = A()
>>> a.b["message"] = "hello"
>>> a.b["message"]
''
>>> a.b["last_message"]
''
>>>
I'm not sure what I have done wrong? It seems to me like @property doesn't work like I would expect it to on dicts, but maybe I'm doing something else fundamentally wrong?
Also, I know that I could just use individual values in the class. But this is implemented as a session in a web application and I need it to be a dict. I could either make this work, or make the whole session object to pretend it's a dict, or use individual variables and hack it into workingness throughout the rest of the code base. I would much rather just get this to work.
| [
"class MyDict(dict):\n def __setitem__(self, key, value):\n if key == 'message':\n super().__setitem__('message', '')\n super().__setitem__('last_message', value) \n else:\n super().__setitem__(key, value)\n\nclass A(object):\n def __init__(self):\n self._b = MyDict({\"message\": \"\", \n \"last_message\": \"\"})\n\n @property\n def b(self):\n return self._b\n\na = A()\na.b['message'] = 'hello'\nprint(a.b['message'])\n# ''\nprint(a.b['last_message'])\n# hello\n\nAs I think you've discovered, the reason why your setter wasn't working is because\na.b['message']='hello'\n\nfirst accesses a.b, which calls the b property's getter, not its setter. The getter returns the dict self._b. Then self._b['message']='hello' causes the dict's __setitem__ is called .\nSo to fix the problem, you need a special dict (like MyDict).\n",
"I may be missing what you are trying to do here, but does this solve your problem?\nclass A(object):\n def __init__(self):\n self._b = {'message':'',\n 'last_message': ''}\n\n @property\n def b(self):\n b = self._b.copy()\n self._b['message'] = ''\n return b\n\n @b.setter\n def b(self, value):\n self._b['message'] = value\n self._b['last_message'] = value\n\n\nif __name__ == \"__main__\":\n a = A()\n a.b = \"hello\"\n print a.b\n print a.b\n print a.b[\"last_message\"]\n\n\n$ python dictPropTest.py\n{'last_message': 'hello', 'message': 'hello'}\n{'last_message': 'hello', 'message': ''}\nhello\n\n"
] | [
21,
3
] | [] | [] | [
"dictionary",
"getter",
"properties",
"python",
"setter"
] | stackoverflow_0003137685_dictionary_getter_properties_python_setter.txt |
Q:
How do I build a flexible counter with 1000+ rows but few reads in Google App Engine?
I have a list of users that only administrators can see (= few reads). This list also displays a count of the number of users in the datastore. Because the list could grow larger than 1000 my first thought was to avoid a normal count() and instead use a sharded counter.
However, the problem is that the admins also have access to various search filters (in the GUI), such as only viewing male/female users and so on. It's important that the count reflects these filters, so that they can get the number of female users, male users and a myriad of other combinations.
Because of this, sharded counters and high concurrency counters without sharding don't seem like a good idea, because I would need to create a counter for every combination of search filters.
Should I simply create a loop of count() methods, such as described here or is this very bad practice? How would I do it otherwise?
Note that this counter is for an admin interface and would have a very limited number of reads. This is really a case of when I would like to sacrifice some read performance for flexibility and accuracy. Although it should be able to grow beyond 1000, it's not expected to grow larger than 10 000.
A:
"Loop of counts" is slow, but these days you can make it a bit better with cursors. Normally I would recommend denormalizing into all the "filtered" counters you need, but that slows down user addition and deletion (and probably demographic changes as well), so, given your particular use case with a very low volume of reads, you can probably get away with the "loop of counts" approach (plus cursors;-).
A:
I've tried two approaches:
1) Write my own task that queries the data store (the query is a key descending query) with a fixed limit of entities (say 50). It then enqueues the next task to start querying where it left off. Each task enqueues the next one passing it two parameters (where it last left off like a cursor and a running total of the number of entities it has seen).
2) This approach is much easier - and that is to use the mapreduce library provided by google for appengine. It runs totally in user space so you just have to download and build the library and include it in your project. Basically, it will handle iterating through all the entities you specify and lets you write a handler for what to do with each one (like incrementing a counter). See the details here: mapreduce.appspot.com - they even have a sample app that does just what you are asking for. THe only problem with this is that the results will appear in your browser and not necessarily stored in the datastore unless you do that yourself.
| How do I build a flexible counter with 1000+ rows but few reads in Google App Engine? | I have a list of users that only administrators can see (= few reads). This list also displays a count of the number of users in the datastore. Because the list could grow larger than 1000 my first thought was to avoid a normal count() and instead use a sharded counter.
However, the problem is that the admins also have access to various search filters (in the GUI), such as only viewing male/female users and so on. It's important that the count reflects these filters, so that they can get the number of female users, male users and a myriad of other combinations.
Because of this, sharded counters and high concurrency counters without sharding don't seem like a good idea, because I would need to create a counter for every combination of search filters.
Should I simply create a loop of count() methods, such as described here or is this very bad practice? How would I do it otherwise?
Note that this counter is for an admin interface and would have a very limited number of reads. This is really a case of when I would like to sacrifice some read performance for flexibility and accuracy. Although it should be able to grow beyond 1000, it's not expected to grow larger than 10 000.
| [
"\"Loop of counts\" is slow, but these days you can make it a bit better with cursors. Normally I would recommend denormalizing into all the \"filtered\" counters you need, but that slows down user addition and deletion (and probably demographic changes as well), so, given your particular use case with a very low volume of reads, you can probably get away with the \"loop of counts\" approach (plus cursors;-).\n",
"I've tried two approaches:\n1) Write my own task that queries the data store (the query is a key descending query) with a fixed limit of entities (say 50). It then enqueues the next task to start querying where it left off. Each task enqueues the next one passing it two parameters (where it last left off like a cursor and a running total of the number of entities it has seen).\n2) This approach is much easier - and that is to use the mapreduce library provided by google for appengine. It runs totally in user space so you just have to download and build the library and include it in your project. Basically, it will handle iterating through all the entities you specify and lets you write a handler for what to do with each one (like incrementing a counter). See the details here: mapreduce.appspot.com - they even have a sample app that does just what you are asking for. THe only problem with this is that the results will appear in your browser and not necessarily stored in the datastore unless you do that yourself.\n"
] | [
2,
2
] | [] | [] | [
"count",
"counter",
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003137070_count_counter_google_app_engine_google_cloud_datastore_python.txt |
Q:
SocketServer.ThreadingTCPServer - Cannot bind to address after program restart
As a follow-up to cannot-bind-to-address-after-socket-program-crashes, I was receiving this error after my program was restarted:
socket.error: [Errno 98] Address already in use
In this particular case, instead of using a socket directly, the program is starting its own threaded TCP server:
httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler)
httpd.serve_forever()
How can I fix this error message?
A:
The above solution didn't work for me but this one did:
SocketServer.ThreadingTCPServer.allow_reuse_address = True
server = SocketServer.ThreadingTCPServer(("localhost", port), CustomHandler)
server.serve_forever()
A:
In this particular case, .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) may be called from the TCPServer class when the allow_reuse_address option is set. So I was able to solve it as follows:
httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler, False) # Do not automatically bind
httpd.allow_reuse_address = True # Prevent 'cannot bind to address' errors on restart
httpd.server_bind() # Manually bind, to support allow_reuse_address
httpd.server_activate() # (see above comment)
httpd.serve_forever()
Anyway, thought this might be useful. The solution will differ slightly in Python 3.0
| SocketServer.ThreadingTCPServer - Cannot bind to address after program restart | As a follow-up to cannot-bind-to-address-after-socket-program-crashes, I was receiving this error after my program was restarted:
socket.error: [Errno 98] Address already in use
In this particular case, instead of using a socket directly, the program is starting its own threaded TCP server:
httpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler)
httpd.serve_forever()
How can I fix this error message?
| [
"The above solution didn't work for me but this one did:\n SocketServer.ThreadingTCPServer.allow_reuse_address = True\n server = SocketServer.ThreadingTCPServer((\"localhost\", port), CustomHandler)\n server.serve_forever()\n\n",
"In this particular case, .setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) may be called from the TCPServer class when the allow_reuse_address option is set. So I was able to solve it as follows:\nhttpd = SocketServer.ThreadingTCPServer(('localhost', port), CustomHandler, False) # Do not automatically bind\nhttpd.allow_reuse_address = True # Prevent 'cannot bind to address' errors on restart\nhttpd.server_bind() # Manually bind, to support allow_reuse_address\nhttpd.server_activate() # (see above comment)\nhttpd.serve_forever()\n\nAnyway, thought this might be useful. The solution will differ slightly in Python 3.0\n"
] | [
19,
16
] | [] | [] | [
"linux",
"python",
"sockets",
"tcpserver"
] | stackoverflow_0002274320_linux_python_sockets_tcpserver.txt |
Q:
Is this correct way to import python scripts residing in arbitrary folders?
This snippet is from an earlier answer here on SO. It is about a year old (and the answer was not accepted). I am new to Python and I am finding the system path a real pain. I have a few functions written in scripts in different directories, and I would like to be able to import them into new projects without having to jump through hoops.
This is the snippet:
def import_path(fullpath):
""" Import a file with full path specification. Allows one to
import from anywhere, something __import__ does not do.
"""
path, filename = os.path.split(fullpath)
filename, ext = os.path.splitext(filename)
sys.path.append(path)
module = __import__(filename)
reload(module) # Might be out of date
del sys.path[-1]
return module
Its from here:
How to do relative imports in Python?
I would like some feedback as to whether I can use it or not - and if there are any undesirable side effects that may not be obvious to a newbie.
I intend to use it something like this:
import_path(/home/pydev/path1/script1.py)
script1.func1()
etc
Is it 'safe' to use the function in the way I intend to?
A:
The "official" and fully safe approach is the imp module of the standard Python library.
Use imp.find_module to find the module on your precisely-specified list of acceptable directories -- it returns a 3-tuple (file, pathname, description) -- if unsuccessful, file is actually None (but it can also raise ImportError so you should use a try/except for that as well as checking if file is None:).
If the search is successful, call imp.load_module (in a try/finally to make sure you close the file!) with the above three arguments after the first one which must be the same name you passed to find_module -- it returns the module object (phew;-).
A:
As mentioned, please consider thread safety, if appropriate. I prefer something closer to a solution posted in a similar post. The main differences below: the use of insert to specify priority of the import, correct restoration of sys.path using try...finally, and setting the global namespace.
# inspired by Alex Martelli's solution to
# http://stackoverflow.com/questions/1096216/override-namespace-in-python/1096247#1096247
def import_from_absolute_path(fullpath, global_name=None):
"""Dynamic script import using full path."""
import os
import sys
script_dir, filename = os.path.split(fullpath)
script, ext = os.path.splitext(filename)
sys.path.insert(0, script_dir)
try:
module = __import__(script)
if global_name is None:
global_name = script
globals()[global_name] = module
sys.modules[global_name] = module
finally:
del sys.path[0]
A:
It does feel like a bit of a hack, but at the moment, I can't think of any unintended side effects that are likely to occur, at least not as long as you're just using this for your own scripts. Basically what it does is temporarily add the parent directory of the specified file (in your example, /home/pydev/path1/) to the list of paths that Python checks when it's looking for a module to import.
The only risk I can think of right now would arise in a multithreaded environment, where two or more threads (or processes) are running this function simultaneously. If thread A wants to import module A from path dirA/A.py, and thread B wants to import module B from path dirB/B.py, you'd wind up with both dirA and dirB in sys.path for a short time. And if there is a file named B.py in dirA, it's possible that thread B will find that (dirA/B.py) instead of the file it's looking for (dirB/B.py), thus importing the wrong module. For this reason, I wouldn't use it in production code, or code that you're going to distribute to other people (at least not without warning them that this hack is in here!). In a situation like that, you could write a more complex function that allows you to specify the file to import without messing with the standard set of paths. (That's what mod_python does, for example)
A:
I would be worried that your script name might correspond with a module that shows up earlier in the path. To dispel this fear, I would fully replace the path with a new list containing just the directory containing the module, then put it back once the import has completed. Also, you should wrap this in some sort of lock so that multiple threads trying to do the same thing don't interfere with each other.
| Is this correct way to import python scripts residing in arbitrary folders? | This snippet is from an earlier answer here on SO. It is about a year old (and the answer was not accepted). I am new to Python and I am finding the system path a real pain. I have a few functions written in scripts in different directories, and I would like to be able to import them into new projects without having to jump through hoops.
This is the snippet:
def import_path(fullpath):
""" Import a file with full path specification. Allows one to
import from anywhere, something __import__ does not do.
"""
path, filename = os.path.split(fullpath)
filename, ext = os.path.splitext(filename)
sys.path.append(path)
module = __import__(filename)
reload(module) # Might be out of date
del sys.path[-1]
return module
Its from here:
How to do relative imports in Python?
I would like some feedback as to whether I can use it or not - and if there are any undesirable side effects that may not be obvious to a newbie.
I intend to use it something like this:
import_path(/home/pydev/path1/script1.py)
script1.func1()
etc
Is it 'safe' to use the function in the way I intend to?
| [
"The \"official\" and fully safe approach is the imp module of the standard Python library.\nUse imp.find_module to find the module on your precisely-specified list of acceptable directories -- it returns a 3-tuple (file, pathname, description) -- if unsuccessful, file is actually None (but it can also raise ImportError so you should use a try/except for that as well as checking if file is None:).\nIf the search is successful, call imp.load_module (in a try/finally to make sure you close the file!) with the above three arguments after the first one which must be the same name you passed to find_module -- it returns the module object (phew;-).\n",
"As mentioned, please consider thread safety, if appropriate. I prefer something closer to a solution posted in a similar post. The main differences below: the use of insert to specify priority of the import, correct restoration of sys.path using try...finally, and setting the global namespace.\n# inspired by Alex Martelli's solution to\n# http://stackoverflow.com/questions/1096216/override-namespace-in-python/1096247#1096247\ndef import_from_absolute_path(fullpath, global_name=None):\n \"\"\"Dynamic script import using full path.\"\"\"\n import os\n import sys\n\n script_dir, filename = os.path.split(fullpath)\n script, ext = os.path.splitext(filename)\n\n sys.path.insert(0, script_dir)\n try:\n module = __import__(script)\n if global_name is None:\n global_name = script\n globals()[global_name] = module\n sys.modules[global_name] = module\n finally:\n del sys.path[0]\n\n",
"It does feel like a bit of a hack, but at the moment, I can't think of any unintended side effects that are likely to occur, at least not as long as you're just using this for your own scripts. Basically what it does is temporarily add the parent directory of the specified file (in your example, /home/pydev/path1/) to the list of paths that Python checks when it's looking for a module to import.\nThe only risk I can think of right now would arise in a multithreaded environment, where two or more threads (or processes) are running this function simultaneously. If thread A wants to import module A from path dirA/A.py, and thread B wants to import module B from path dirB/B.py, you'd wind up with both dirA and dirB in sys.path for a short time. And if there is a file named B.py in dirA, it's possible that thread B will find that (dirA/B.py) instead of the file it's looking for (dirB/B.py), thus importing the wrong module. For this reason, I wouldn't use it in production code, or code that you're going to distribute to other people (at least not without warning them that this hack is in here!). In a situation like that, you could write a more complex function that allows you to specify the file to import without messing with the standard set of paths. (That's what mod_python does, for example)\n",
"I would be worried that your script name might correspond with a module that shows up earlier in the path. To dispel this fear, I would fully replace the path with a new list containing just the directory containing the module, then put it back once the import has completed. Also, you should wrap this in some sort of lock so that multiple threads trying to do the same thing don't interfere with each other.\n"
] | [
8,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003137731_python.txt |
Q:
Cross-platform Python GUI suitable for taskbar (Win) and menubar (mac) functionality?
I am fairly new to Python programming, and completely new to cross-platform GUI building (only previous GUI experience is through visual basic and Java).
I've written some python code to screen-scrape data from a website, and now I want to build a GUI that will reside in the Mac OS X menubar, and in Window's task bar (i.e., the system tray).
The most useful general page on cross-plaform Python GUIs for me was this one (despite its name indication Window GUIs). And some stackoverflow questions came in useful as well (especially this one, and the accepted answer of this one about splitting up the GUI and cli code).
I think I will go for either wxPython or QT because I want the GUI to look as native as possible.
However, as I've said the fairly simple GUI will mainly live in the taskbar/menubar.
Should this influence my decision?
A:
Here's an example for PyQt. This works for me on MacOS X; I haven't tried it on other platforms. Note that the QSystemTrayIcon class will raise exceptions if it doesn't have an icon – I grabbed the RSS feed svg from Wiki commons for my icon.svg (but you can give QIcon a PNG directly and not mess around with QtSvg).
import PyQt4
from PyQt4 import QtCore, QtGui, QtSvg
app = QtGui.QApplication([])
i = QtGui.QSystemTrayIcon()
m = QtGui.QMenu()
def quitCB():
QtGui.QApplication.quit()
def aboutToShowCB():
print 'about to show'
m.addAction('Quit', quitCB)
QtCore.QObject.connect(m, QtCore.SIGNAL('aboutToShow()'), aboutToShowCB)
i.setContextMenu(m)
svg = QtSvg.QSvgRenderer('icon.svg')
if not svg.isValid():
raise RuntimeError('bad SVG')
pm = QtGui.QPixmap(16, 16)
painter = QtGui.QPainter(pm)
svg.render(painter)
icon = QtGui.QIcon(pm)
i.setIcon(icon)
i.show()
app.exec_()
del painter, pm, svg # avoid the paint device getting
del i, icon # deleted before the painter
del app
A:
See this related SO answer on how to accomplish Windows system tray/OS X menu bar functionality in wxPython.
| Cross-platform Python GUI suitable for taskbar (Win) and menubar (mac) functionality? | I am fairly new to Python programming, and completely new to cross-platform GUI building (only previous GUI experience is through visual basic and Java).
I've written some python code to screen-scrape data from a website, and now I want to build a GUI that will reside in the Mac OS X menubar, and in Window's task bar (i.e., the system tray).
The most useful general page on cross-plaform Python GUIs for me was this one (despite its name indication Window GUIs). And some stackoverflow questions came in useful as well (especially this one, and the accepted answer of this one about splitting up the GUI and cli code).
I think I will go for either wxPython or QT because I want the GUI to look as native as possible.
However, as I've said the fairly simple GUI will mainly live in the taskbar/menubar.
Should this influence my decision?
| [
"Here's an example for PyQt. This works for me on MacOS X; I haven't tried it on other platforms. Note that the QSystemTrayIcon class will raise exceptions if it doesn't have an icon – I grabbed the RSS feed svg from Wiki commons for my icon.svg (but you can give QIcon a PNG directly and not mess around with QtSvg).\nimport PyQt4\nfrom PyQt4 import QtCore, QtGui, QtSvg\n\napp = QtGui.QApplication([])\n\ni = QtGui.QSystemTrayIcon()\n\nm = QtGui.QMenu()\ndef quitCB():\n QtGui.QApplication.quit()\ndef aboutToShowCB():\n print 'about to show'\nm.addAction('Quit', quitCB)\nQtCore.QObject.connect(m, QtCore.SIGNAL('aboutToShow()'), aboutToShowCB)\ni.setContextMenu(m)\n\nsvg = QtSvg.QSvgRenderer('icon.svg')\nif not svg.isValid():\n raise RuntimeError('bad SVG')\npm = QtGui.QPixmap(16, 16)\npainter = QtGui.QPainter(pm)\nsvg.render(painter)\nicon = QtGui.QIcon(pm)\ni.setIcon(icon)\ni.show()\n\napp.exec_()\n\ndel painter, pm, svg # avoid the paint device getting\ndel i, icon # deleted before the painter\ndel app\n\n",
"See this related SO answer on how to accomplish Windows system tray/OS X menu bar functionality in wxPython.\n"
] | [
10,
2
] | [] | [] | [
"cross_platform",
"menubar",
"python",
"taskbar",
"user_interface"
] | stackoverflow_0003104818_cross_platform_menubar_python_taskbar_user_interface.txt |
Q:
Implementing a special type of multiprocessing queue in Python
Imagine an inverted binary tree with nodes A, B, C, D, E, F on level 0. nodes G,H,I on level 1, node J on level 2, and node K on level 3.
Level 1: G = func(A,B), H = func(C,D), I = func(E,F)
Level 2: J = func(G,H)
Level 3: K = func(J,I).
Each pair of nodes on Level 0 must be processed in order, Each pair of nodes on Level 1 can be processed in any order but the result must on the next level must be processed as shown, and so forth until we end up with the final result, K.
The actual problem is a computational geometry problem in which a sequence of solids are fused together. A is adjacent to B which is adjacent to C, and so on. The resulting fuse of A and B (G) is adjacent to the fuse of C and D (H). The resulting fuse of J and I (K) is the final result. Thus you can't fuse G and I since they are not adjacent. If the number of nodes on a level is not a power of 2, you end up with a dangling entity that must be processed one level further.
Since the fuse process is computationally expensive and memory intensive but very parallel, I would like to use the Python multiprocessing package and some form of queue. After calculating G = func(A,B), I would like to push the result G onto the queue for the subsequent J = func(G,H) computation. When the queue is empty, the last result is the final result. Keep in mind that the mp.queue will not necessarily produce results FIFO, since I = func(E,F) may finish before H = func(C,D)
I have come up with a few (bad) solutions but I'm sure there is an elegant solution just beyond my grasp. Suggestions?
A:
I couldn't come up with a smart design for a queue, but you can easily replace the queue with one more process, which in my example I called WorkerManager. This process gathers results from all Worker processes and starts new workers only if there are two adjacent data packs waiting to be processed. This way, you'll never try to join non-adjacent results, so you can ignore "levels" and fire the computation of next pair as soon as it's ready.
from multiprocessing import Process, Queue
class Result(object):
'''Result from start to end.'''
def __init__(self, start, end, data):
self.start = start
self.end = end
self.data = data
class Worker(Process):
'''Joins two results into one result.'''
def __init__(self, result_queue, pair):
self.result_queue = result_queue
self.pair = pair
super(Worker, self).__init__()
def run(self):
left, right = self.pair
result = Result(left.start, right.end,
'(%s, %s)' % (left.data, right.data))
self.result_queue.put(result)
class WorkerManager(Process):
'''
Takes results from result_queue, pairs them
and assigns workers to process them.
Returns final result into final_queue.
'''
def __init__(self, result_queue, final_queue, start, end):
self._result_queue = result_queue
self._final_queue = final_queue
self._start = start
self._end = end
self._results = []
super(WorkerManager, self).__init__()
def run(self):
while True:
result = self._result_queue.get()
self._add_result(result)
if self._has_final_result():
self._final_queue.put(self._get_final_result())
return
pair = self._find_adjacent_pair()
if pair:
self._start_worker(pair)
def _add_result(self, result):
self._results.append(result)
self._results.sort(key=lambda result: result.start)
def _has_final_result(self):
return (len(self._results) == 1
and self._results[0].start == self._start
and self._results[0].end == self._end)
def _get_final_result(self):
return self._results[0]
def _find_adjacent_pair(self):
for i in xrange(len(self._results) - 1):
left, right = self._results[i], self._results[i + 1]
if left.end == right.start:
self._results = self._results[:i] + self._results[i + 2:]
return left, right
def _start_worker(self, pair):
worker = Worker(self._result_queue, pair)
worker.start()
if __name__ == '__main__':
DATA = [Result(i, i + 1, str(i)) for i in xrange(6)]
result_queue = Queue()
final_queue = Queue()
start = 0
end = len(DATA)
man = WorkerManager(result_queue, final_queue, start, end)
man.start()
for res in DATA:
result_queue.put(res)
final = final_queue.get()
print final.start
# 0
print final.end
# 6
print final.data
# For example:
# (((0, 1), (2, 3)), (4, 5))
For my example, I used a simple Worker that returns given data in parentheses, separated by a comma, but you could put any computation in there. In my case, final result was (((0, 1), (2, 3)), (4, 5)) which means that the algorithm computed (0, 1) and (2, 3) before computing ((0, 1), (2, 3)) and then joined the result with (4, 5). I hope this is what you were looking for.
| Implementing a special type of multiprocessing queue in Python | Imagine an inverted binary tree with nodes A, B, C, D, E, F on level 0. nodes G,H,I on level 1, node J on level 2, and node K on level 3.
Level 1: G = func(A,B), H = func(C,D), I = func(E,F)
Level 2: J = func(G,H)
Level 3: K = func(J,I).
Each pair of nodes on Level 0 must be processed in order, Each pair of nodes on Level 1 can be processed in any order but the result must on the next level must be processed as shown, and so forth until we end up with the final result, K.
The actual problem is a computational geometry problem in which a sequence of solids are fused together. A is adjacent to B which is adjacent to C, and so on. The resulting fuse of A and B (G) is adjacent to the fuse of C and D (H). The resulting fuse of J and I (K) is the final result. Thus you can't fuse G and I since they are not adjacent. If the number of nodes on a level is not a power of 2, you end up with a dangling entity that must be processed one level further.
Since the fuse process is computationally expensive and memory intensive but very parallel, I would like to use the Python multiprocessing package and some form of queue. After calculating G = func(A,B), I would like to push the result G onto the queue for the subsequent J = func(G,H) computation. When the queue is empty, the last result is the final result. Keep in mind that the mp.queue will not necessarily produce results FIFO, since I = func(E,F) may finish before H = func(C,D)
I have come up with a few (bad) solutions but I'm sure there is an elegant solution just beyond my grasp. Suggestions?
| [
"I couldn't come up with a smart design for a queue, but you can easily replace the queue with one more process, which in my example I called WorkerManager. This process gathers results from all Worker processes and starts new workers only if there are two adjacent data packs waiting to be processed. This way, you'll never try to join non-adjacent results, so you can ignore \"levels\" and fire the computation of next pair as soon as it's ready.\nfrom multiprocessing import Process, Queue\n\nclass Result(object):\n '''Result from start to end.'''\n def __init__(self, start, end, data):\n self.start = start\n self.end = end\n self.data = data\n\n\nclass Worker(Process):\n '''Joins two results into one result.'''\n def __init__(self, result_queue, pair):\n self.result_queue = result_queue\n self.pair = pair\n super(Worker, self).__init__()\n\n def run(self):\n left, right = self.pair\n result = Result(left.start, right.end,\n '(%s, %s)' % (left.data, right.data))\n self.result_queue.put(result)\n\n\nclass WorkerManager(Process):\n '''\n Takes results from result_queue, pairs them\n and assigns workers to process them.\n Returns final result into final_queue.\n '''\n def __init__(self, result_queue, final_queue, start, end):\n self._result_queue = result_queue\n self._final_queue = final_queue\n self._start = start\n self._end = end\n self._results = []\n super(WorkerManager, self).__init__()\n\n def run(self):\n while True:\n result = self._result_queue.get()\n self._add_result(result)\n if self._has_final_result():\n self._final_queue.put(self._get_final_result())\n return\n pair = self._find_adjacent_pair()\n if pair:\n self._start_worker(pair)\n\n def _add_result(self, result):\n self._results.append(result)\n self._results.sort(key=lambda result: result.start)\n\n def _has_final_result(self):\n return (len(self._results) == 1\n and self._results[0].start == self._start\n and self._results[0].end == self._end)\n\n def _get_final_result(self):\n return self._results[0]\n\n def _find_adjacent_pair(self):\n for i in xrange(len(self._results) - 1):\n left, right = self._results[i], self._results[i + 1]\n if left.end == right.start:\n self._results = self._results[:i] + self._results[i + 2:]\n return left, right\n\n def _start_worker(self, pair):\n worker = Worker(self._result_queue, pair)\n worker.start()\n\nif __name__ == '__main__':\n DATA = [Result(i, i + 1, str(i)) for i in xrange(6)]\n result_queue = Queue()\n final_queue = Queue()\n start = 0\n end = len(DATA)\n man = WorkerManager(result_queue, final_queue, start, end)\n man.start()\n for res in DATA:\n result_queue.put(res)\n final = final_queue.get()\n print final.start\n # 0\n print final.end\n # 6\n print final.data\n # For example:\n # (((0, 1), (2, 3)), (4, 5))\n\nFor my example, I used a simple Worker that returns given data in parentheses, separated by a comma, but you could put any computation in there. In my case, final result was (((0, 1), (2, 3)), (4, 5)) which means that the algorithm computed (0, 1) and (2, 3) before computing ((0, 1), (2, 3)) and then joined the result with (4, 5). I hope this is what you were looking for.\n"
] | [
0
] | [] | [] | [
"multiprocessing",
"python",
"queue"
] | stackoverflow_0003098785_multiprocessing_python_queue.txt |
Q:
Including HTML variable in Django template without escaping
I have html encoded text which reads like this:
RT <a href="http://twitter.com/freuter">@freuter</a>...
I want this displayed as html but I am not sure if there is a filter which i can apply to this text to convert the html-encoded text back to html ...
can someone help?
A:
As Daniel says, use the {{ tweet|safe }} filter in the html, or mark it safe from the views.
Use django.template.mark_safe()
A:
Try the |safe filter if you want to render all HTML.
A:
See: How do I perform HTML decoding/encoding using Python/Django?
I think this answers your querstion.
| Including HTML variable in Django template without escaping | I have html encoded text which reads like this:
RT <a href="http://twitter.com/freuter">@freuter</a>...
I want this displayed as html but I am not sure if there is a filter which i can apply to this text to convert the html-encoded text back to html ...
can someone help?
| [
"As Daniel says, use the {{ tweet|safe }} filter in the html, or mark it safe from the views.\nUse django.template.mark_safe()\n",
"Try the |safe filter if you want to render all HTML.\n",
"See: How do I perform HTML decoding/encoding using Python/Django?\nI think this answers your querstion.\n"
] | [
27,
4,
2
] | [] | [] | [
"django",
"encoding",
"html",
"python"
] | stackoverflow_0003138588_django_encoding_html_python.txt |
Q:
OSError on uploading files in Django
While trying to send form with image field in it I'm getting :
Exception Type: OSError at /user/register/
Exception Value: (13, 'Permission denied')
Of course first thing I've checked were the permissions to my folders, and just in case set them to 777 on the whole path from '/'. Still nothing. So I've tried adding parameters to settings, which now are set like this :
ADMIN_MEDIA_PREFIX
'/site_media/admin/'
CACHE_BACKEND
'locmem://'
DEFAULT_CHARSET
'utf-8'
DEFAULT_CONTENT_TYPE
'text/html'
DEFAULT_FILE_STORAGE
'django.core.files.storage.FileSystemStorage'
FILE_CHARSET
'utf-8'
FILE_UPLOAD_HANDLERS
('django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler')
FILE_UPLOAD_MAX_MEMORY_SIZE
2621440
FILE_UPLOAD_PERMISSIONS
777
FILE_UPLOAD_TEMP_DIR
None
FS_ROOT
'/home/rails/fandrive'
MEDIA_ROOT
'/home/fandrive/www/fandrive/site_media'
MEDIA_URL
'/site_media/'
PROJECT_PATH
'/home/rails/fandrive'
SESSION_FILE_PATH
None
Request.META :
CONTENT_LENGTH
'8249'
CONTENT_TYPE
'multipart/form-data; boundary=---------------------------26681719213985'
DOCUMENT_ROOT
'/home/rails/fandrive/public'
HTTP_ACCEPT
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
HTTP_ACCEPT_CHARSET
'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
HTTP_ACCEPT_ENCODING
'gzip,deflate'
HTTP_ACCEPT_LANGUAGE
'en-us,en;q=0.5'
HTTP_CONNECTION
'keep-alive'
HTTP_CONTENT_LENGTH
'8249'
HTTP_CONTENT_TYPE
'multipart/form-data; boundary=---------------------------26681719213985'
HTTP_HOST
'example.com'
HTTP_KEEP_ALIVE
'115'
HTTP_REFERER
'http://example.com/user/register/'
HTTP_USER_AGENT
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6'
PATH_INFO
u'/user/register/'
QUERY_STRING
''
REMOTE_PORT
'52869'
REQUEST_METHOD
'POST'
REQUEST_URI
'/user/register/'
SCRIPT_NAME
u''
SERVER_PROTOCOL
'HTTP/1.1'
SERVER_SOFTWARE
'Apache'
_
'_'
wsgi.errors
<open file '<stderr>', mode 'w' at 0x7f2a6026f140>
wsgi.input
<socket._fileobject object at 0x7f2a5cbc4848>
wsgi.multiprocess
True
wsgi.multithread
False
wsgi.run_once
True
wsgi.url_scheme
'http'
wsgi.version
(1, 0)
And finally my traceback :
Traceback:
File "/home/rails/fandrive/site-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/rails/fandrive/registration/views.py" in register
47. new_user = backend.register(request, **form.cleaned_data)
File "/home/rails/fandrive/registration/backends/default/__init__.py" in register
23. request=request)
File "/home/rails/fandrive/site-packages/django/dispatch/dispatcher.py" in send
166. response = receiver(signal=self, sender=sender, **named)
File "/home/rails/fandrive/regbackend.py" in user_created
39. data.save()
File "/home/rails/fandrive/site-packages/django/db/models/base.py" in save
410. self.save_base(force_insert=force_insert, force_update=force_update)
File "/home/rails/fandrive/site-packages/django/db/models/base.py" in save_base
483. values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True))) for f in meta.local_fields if not isinstance(f, AutoField)]
File "/home/rails/fandrive/site-packages/django/db/models/fields/files.py" in pre_save
252. file.save(file.name, file, save=False)
File "/home/rails/fandrive/site-packages/django/db/models/fields/files.py" in save
91. self.name = self.storage.save(name, content)
File "/home/rails/fandrive/site-packages/django/core/files/storage.py" in save
47. name = self._save(name, content)
File "/home/rails/fandrive/site-packages/django/core/files/storage.py" in _save
146. os.makedirs(directory)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
157. mkdir(name, mode)
Any ideas what more should I check ?
UPDATE : My model
class UserProfile(InheritedProfile):
def upload_path(self, field_attname):
filename = hashlib.md5(field_attname).hexdigest()[:4] + "_" + field_attname
return "uploads/users/%s" % (filename,)
user = models.ForeignKey(User, unique=True, related_name='profile')
image = models.ImageField(upload_to=upload_path, verbose_name="Image", blank=True, null=True)
I have already created 'uploads/users' folder so why is it trying to create a folder - not just a file ?
A:
The apache use that runs your django application does not have the permission to create the folder/file in your media directory.
A quick temporary fix would be to
Go to your media folder:
/home/fandrive/www/fandrive/site_media
and type:
sudo chmod -R a+w
which makes your folder writeable by all users.
This approach may not be secure. To make it secure, you can change the ownership of the folder to that user, or create a group and assign the permissions to that group.
| OSError on uploading files in Django | While trying to send form with image field in it I'm getting :
Exception Type: OSError at /user/register/
Exception Value: (13, 'Permission denied')
Of course first thing I've checked were the permissions to my folders, and just in case set them to 777 on the whole path from '/'. Still nothing. So I've tried adding parameters to settings, which now are set like this :
ADMIN_MEDIA_PREFIX
'/site_media/admin/'
CACHE_BACKEND
'locmem://'
DEFAULT_CHARSET
'utf-8'
DEFAULT_CONTENT_TYPE
'text/html'
DEFAULT_FILE_STORAGE
'django.core.files.storage.FileSystemStorage'
FILE_CHARSET
'utf-8'
FILE_UPLOAD_HANDLERS
('django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler')
FILE_UPLOAD_MAX_MEMORY_SIZE
2621440
FILE_UPLOAD_PERMISSIONS
777
FILE_UPLOAD_TEMP_DIR
None
FS_ROOT
'/home/rails/fandrive'
MEDIA_ROOT
'/home/fandrive/www/fandrive/site_media'
MEDIA_URL
'/site_media/'
PROJECT_PATH
'/home/rails/fandrive'
SESSION_FILE_PATH
None
Request.META :
CONTENT_LENGTH
'8249'
CONTENT_TYPE
'multipart/form-data; boundary=---------------------------26681719213985'
DOCUMENT_ROOT
'/home/rails/fandrive/public'
HTTP_ACCEPT
'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
HTTP_ACCEPT_CHARSET
'ISO-8859-1,utf-8;q=0.7,*;q=0.7'
HTTP_ACCEPT_ENCODING
'gzip,deflate'
HTTP_ACCEPT_LANGUAGE
'en-us,en;q=0.5'
HTTP_CONNECTION
'keep-alive'
HTTP_CONTENT_LENGTH
'8249'
HTTP_CONTENT_TYPE
'multipart/form-data; boundary=---------------------------26681719213985'
HTTP_HOST
'example.com'
HTTP_KEEP_ALIVE
'115'
HTTP_REFERER
'http://example.com/user/register/'
HTTP_USER_AGENT
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6'
PATH_INFO
u'/user/register/'
QUERY_STRING
''
REMOTE_PORT
'52869'
REQUEST_METHOD
'POST'
REQUEST_URI
'/user/register/'
SCRIPT_NAME
u''
SERVER_PROTOCOL
'HTTP/1.1'
SERVER_SOFTWARE
'Apache'
_
'_'
wsgi.errors
<open file '<stderr>', mode 'w' at 0x7f2a6026f140>
wsgi.input
<socket._fileobject object at 0x7f2a5cbc4848>
wsgi.multiprocess
True
wsgi.multithread
False
wsgi.run_once
True
wsgi.url_scheme
'http'
wsgi.version
(1, 0)
And finally my traceback :
Traceback:
File "/home/rails/fandrive/site-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/rails/fandrive/registration/views.py" in register
47. new_user = backend.register(request, **form.cleaned_data)
File "/home/rails/fandrive/registration/backends/default/__init__.py" in register
23. request=request)
File "/home/rails/fandrive/site-packages/django/dispatch/dispatcher.py" in send
166. response = receiver(signal=self, sender=sender, **named)
File "/home/rails/fandrive/regbackend.py" in user_created
39. data.save()
File "/home/rails/fandrive/site-packages/django/db/models/base.py" in save
410. self.save_base(force_insert=force_insert, force_update=force_update)
File "/home/rails/fandrive/site-packages/django/db/models/base.py" in save_base
483. values = [(f, f.get_db_prep_save(raw and getattr(self, f.attname) or f.pre_save(self, True))) for f in meta.local_fields if not isinstance(f, AutoField)]
File "/home/rails/fandrive/site-packages/django/db/models/fields/files.py" in pre_save
252. file.save(file.name, file, save=False)
File "/home/rails/fandrive/site-packages/django/db/models/fields/files.py" in save
91. self.name = self.storage.save(name, content)
File "/home/rails/fandrive/site-packages/django/core/files/storage.py" in save
47. name = self._save(name, content)
File "/home/rails/fandrive/site-packages/django/core/files/storage.py" in _save
146. os.makedirs(directory)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
150. makedirs(head, mode)
File "/bin/python-2.6.1/lib/python2.6/os.py" in makedirs
157. mkdir(name, mode)
Any ideas what more should I check ?
UPDATE : My model
class UserProfile(InheritedProfile):
def upload_path(self, field_attname):
filename = hashlib.md5(field_attname).hexdigest()[:4] + "_" + field_attname
return "uploads/users/%s" % (filename,)
user = models.ForeignKey(User, unique=True, related_name='profile')
image = models.ImageField(upload_to=upload_path, verbose_name="Image", blank=True, null=True)
I have already created 'uploads/users' folder so why is it trying to create a folder - not just a file ?
| [
"The apache use that runs your django application does not have the permission to create the folder/file in your media directory.\nA quick temporary fix would be to \nGo to your media folder:\n/home/fandrive/www/fandrive/site_media\nand type:\nsudo chmod -R a+w\n\nwhich makes your folder writeable by all users.\nThis approach may not be secure. To make it secure, you can change the ownership of the folder to that user, or create a group and assign the permissions to that group.\n"
] | [
2
] | [] | [] | [
"django",
"file_permissions",
"file_upload",
"permissions",
"python"
] | stackoverflow_0003137111_django_file_permissions_file_upload_permissions_python.txt |
Q:
Trying to install Django via Macports on Leopard
I have Python 2.6 & 3.1 installed on Leopard via mac ports with no problems. I want to install Django 1.2 via mac ports for Python 2.6, but a google search of how to do it seems to point me in the wrong direction. Can anyone point me in the right direction? Thanks again.....
A:
Just don't do that. Install it directly from source.
Or better, use easy_install:
easy_install django
Or even better, use pip (and add virtualenv as a bonus (and virtualenvwrapper for more fun!)):
pip install django
A:
What is wrong with this package?
$ port info py26-django
py26-django @1.2.1 (python, www)
Variants: bash_completion, universal
Description: Django is a high-level Python Web framework that
encourages rapid development and clean, pragmatic design.
Homepage: http://www.djangoproject.com
Library Dependencies: python26, py26-distribute
Platforms: darwin
License: unknown
Maintainers: arthurk@macports.org
A:
Just "throw" the django tarball within the site-packages (dist-packages in py2.6+) and you are done. What for do you need macports etc, with a pure python library?
| Trying to install Django via Macports on Leopard | I have Python 2.6 & 3.1 installed on Leopard via mac ports with no problems. I want to install Django 1.2 via mac ports for Python 2.6, but a google search of how to do it seems to point me in the wrong direction. Can anyone point me in the right direction? Thanks again.....
| [
"Just don't do that. Install it directly from source.\nOr better, use easy_install:\neasy_install django\n\nOr even better, use pip (and add virtualenv as a bonus (and virtualenvwrapper for more fun!)):\npip install django\n\n",
"What is wrong with this package?\n$ port info py26-django\npy26-django @1.2.1 (python, www)\nVariants: bash_completion, universal\n\nDescription: Django is a high-level Python Web framework that\n encourages rapid development and clean, pragmatic design.\nHomepage: http://www.djangoproject.com\n\nLibrary Dependencies: python26, py26-distribute\nPlatforms: darwin\nLicense: unknown\nMaintainers: arthurk@macports.org\n\n",
"Just \"throw\" the django tarball within the site-packages (dist-packages in py2.6+) and you are done. What for do you need macports etc, with a pure python library?\n"
] | [
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003136423_django_python.txt |
Q:
Python - passing object references?
I learning Python (coming from a dotnet background) and developing an app which interacts with a webservice.
The web service is flat, in that it has numerous calls some of which are related to sessions e.g. logging on etc, whereas other calls are related to retrieving/setting business data.
To accompany the webservice, there are a couple of python classes which wrap all the calls. I am looking to develop a client on top of that class but give the client more OO structure.
The design of my own app was to have a Session-type class which would be responsible for logging on/maintaining the connection etc , but itself would be injected into a Business-type class which is responsible for making all the business calls.
So the stack is something like
WebService (Soap)
WebServiceWrapper (Python)
Session (Python)
Business (Python)
Here's a sample of my code (I've renamed some methods to try and make stuff more explicit)
from webServiceWrapper import webServiceAPI
class Session():
def __init__(self, user, password):
self._api = webServiceAPI()
self.login = self._api.login(user, password)
def webServiceCalls(self):
return self._api()
class Business():
def __init__(self, service):
self._service=service
def getBusinessData(self):
return self._service.get_business_data()
and my unit test
class exchange(unittest.TestCase):
def setUp(self):
self.service = Session("username","password")
self._business = Business(self.service.webServiceCalls())
def testBusinessReturnsData(self):
self.assertFalse(self._business.getBusinessData()==None)
The unit test fails fails on
return self._api()
saying that the underlying class is not callable
TypeError: 'webServiceAPI' is not callable
My first q is, is that the python way? Is the OO thinking which underpins app development with static languages good for dynamic as well? (That's probably quite a big q!)
My second q is that, if this kind of architecture is ok, what am I doing wrong (I guess in terms of passing references to objects in this way)?
Many thx
S
A:
If WebserviceAPI is an object just remove the parentheses like that:
return self._api
You already created an instance of the object in the constructor.
Maybe add the definition of WebserviceAPI to the question, I can only guess at the moment.
A:
I don't see anything that is wrong or un-Pythonic here. Pythonistas often point out the differences to static languages like Java or C#, but many real-world application mostly use a simple static class design in Python, too.
I guess that webServiceAPI is not a class, thus it can't be called.
If you are using Python 2.x, always inherit from the object type, otherwise you'll get a “classic class” (a relict from ancient times that is kept for background compatibility).
| Python - passing object references? | I learning Python (coming from a dotnet background) and developing an app which interacts with a webservice.
The web service is flat, in that it has numerous calls some of which are related to sessions e.g. logging on etc, whereas other calls are related to retrieving/setting business data.
To accompany the webservice, there are a couple of python classes which wrap all the calls. I am looking to develop a client on top of that class but give the client more OO structure.
The design of my own app was to have a Session-type class which would be responsible for logging on/maintaining the connection etc , but itself would be injected into a Business-type class which is responsible for making all the business calls.
So the stack is something like
WebService (Soap)
WebServiceWrapper (Python)
Session (Python)
Business (Python)
Here's a sample of my code (I've renamed some methods to try and make stuff more explicit)
from webServiceWrapper import webServiceAPI
class Session():
def __init__(self, user, password):
self._api = webServiceAPI()
self.login = self._api.login(user, password)
def webServiceCalls(self):
return self._api()
class Business():
def __init__(self, service):
self._service=service
def getBusinessData(self):
return self._service.get_business_data()
and my unit test
class exchange(unittest.TestCase):
def setUp(self):
self.service = Session("username","password")
self._business = Business(self.service.webServiceCalls())
def testBusinessReturnsData(self):
self.assertFalse(self._business.getBusinessData()==None)
The unit test fails fails on
return self._api()
saying that the underlying class is not callable
TypeError: 'webServiceAPI' is not callable
My first q is, is that the python way? Is the OO thinking which underpins app development with static languages good for dynamic as well? (That's probably quite a big q!)
My second q is that, if this kind of architecture is ok, what am I doing wrong (I guess in terms of passing references to objects in this way)?
Many thx
S
| [
"If WebserviceAPI is an object just remove the parentheses like that:\nreturn self._api \n\nYou already created an instance of the object in the constructor.\nMaybe add the definition of WebserviceAPI to the question, I can only guess at the moment.\n",
"I don't see anything that is wrong or un-Pythonic here. Pythonistas often point out the differences to static languages like Java or C#, but many real-world application mostly use a simple static class design in Python, too.\nI guess that webServiceAPI is not a class, thus it can't be called.\nIf you are using Python 2.x, always inherit from the object type, otherwise you'll get a “classic class” (a relict from ancient times that is kept for background compatibility).\n"
] | [
3,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003139042_oop_python.txt |
Q:
Installing django with python 2.5 and not with the default version of python
I have to install Django on my linux server where python 2.4 is available as the default installation. I have installed python 2.5 as a separate version. Now I have to install Django which I have to use with python 2.5. Is there any specific requirement, so that it is installed with the python 2.5 and not with the default 2.4 version available on the server ?
Please suggest.
Thanks in advance.
A:
after downloading the django source, instead of doing
python setup.py install
do
/path/to/python2.5 setup.py install
A:
Django is 100% compatible with Python 2.4. However if you really want to use 2.5 you would probably be best off using a virtualenv and installing Django and your project inside that.
Don't forget if you do try and install 2.5, you will also need to recompile mod_wsgi to use it, as the system packaged version will only use 2.4.
| Installing django with python 2.5 and not with the default version of python | I have to install Django on my linux server where python 2.4 is available as the default installation. I have installed python 2.5 as a separate version. Now I have to install Django which I have to use with python 2.5. Is there any specific requirement, so that it is installed with the python 2.5 and not with the default 2.4 version available on the server ?
Please suggest.
Thanks in advance.
| [
"after downloading the django source, instead of doing\npython setup.py install\n\ndo\n/path/to/python2.5 setup.py install\n\n",
"Django is 100% compatible with Python 2.4. However if you really want to use 2.5 you would probably be best off using a virtualenv and installing Django and your project inside that.\nDon't forget if you do try and install 2.5, you will also need to recompile mod_wsgi to use it, as the system packaged version will only use 2.4.\n"
] | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003139372_django_python.txt |
Q:
timeit module hangs with bigger values of pow()
I am trying to calculate the time taken by pow function to calculate exponential modulo. With the values of g,x,p hardcoded the code gives error and with the values placed in the pow function, the code hangs. The same piece of code is working efficiently when i am using time() and clock() to calculate the time taken by this piece of code.
i wanted accuracy and for that now i have moved to timeit module after testing with clock() and time() functions.
The code works fine with small values such as pow(2, 3, 5) which makes sense. how can i improve the efficency to calculate time using timeit module.
Also i am a beginner to python, forgive me if there is any stupid mistake in the code.
import math
import random
import hashlib
import time
from timeit import Timer
g = 141802876407053547664378835005750805370737584038368838959151050908654130616798415530564917923311706921535439557793280725844349256960807398107370211978304
x = 1207729835787890214
p = 4870352607375058055471602136317178172283784073796673298937466544646468718314482464390112574915498953621226853454222898392076852427324057496200810018794472
t = Timer('pow(g,x,p)', 'import math')
z = t.timeit()
print ('the value of z is: '), z
Thanks
A:
There are two issues here:
You can't directly access globals from timeit: See this question. You can use this to fix the error:
t = Timer('pow(g,x,p)', 'from __main__ import g,x,p')
Or just put the numerical values directly in the string.
By default, the timeit module runs 1000000 iterations, which will take much too long here. You can change the number of iterations, for example:
z = t.timeit(1000)
This will prevent what seems like a hang (but is actually just a very long calculation).
| timeit module hangs with bigger values of pow() | I am trying to calculate the time taken by pow function to calculate exponential modulo. With the values of g,x,p hardcoded the code gives error and with the values placed in the pow function, the code hangs. The same piece of code is working efficiently when i am using time() and clock() to calculate the time taken by this piece of code.
i wanted accuracy and for that now i have moved to timeit module after testing with clock() and time() functions.
The code works fine with small values such as pow(2, 3, 5) which makes sense. how can i improve the efficency to calculate time using timeit module.
Also i am a beginner to python, forgive me if there is any stupid mistake in the code.
import math
import random
import hashlib
import time
from timeit import Timer
g = 141802876407053547664378835005750805370737584038368838959151050908654130616798415530564917923311706921535439557793280725844349256960807398107370211978304
x = 1207729835787890214
p = 4870352607375058055471602136317178172283784073796673298937466544646468718314482464390112574915498953621226853454222898392076852427324057496200810018794472
t = Timer('pow(g,x,p)', 'import math')
z = t.timeit()
print ('the value of z is: '), z
Thanks
| [
"There are two issues here:\n\nYou can't directly access globals from timeit: See this question. You can use this to fix the error:\nt = Timer('pow(g,x,p)', 'from __main__ import g,x,p')\n\nOr just put the numerical values directly in the string.\nBy default, the timeit module runs 1000000 iterations, which will take much too long here. You can change the number of iterations, for example:\nz = t.timeit(1000)\n\nThis will prevent what seems like a hang (but is actually just a very long calculation).\n\n"
] | [
4
] | [] | [] | [
"python",
"timeit"
] | stackoverflow_0003139586_python_timeit.txt |
Q:
Django: Update order attribute for objects in a queryset
I'm having a attribute on my model to allow the user to order the objects. I have to update the element's order depending on a list, that contains the object's ids in the new order; right now I'm iterating over the whole queryset and set one objects after the other. What would be the easiest/fastest way to do the same with the whole queryset?
def update_ordering(model, order):
""" order is in the form [id,id,id,id] for example: [8,4,5,1,3] """
id_to_order = dict((order[i], i) for i in range(len(order)))
for x in model.objects.all():
x.order = id_to_order[x.id]
x.save()
A:
This cannot be done in one single queryset operation. As far as I know it can't even be done in one query with raw SQL. So you will always need the update call for each object that has to be updated. So both your and Collin Anderson's solutions seem quite optimal for your description.
However, what's your use case? Is really the whole list going to change every time? In most situations this seems very unlikely. I can see some different approaches.
You save the order field like you say, but you generate a diff for the order list:def
update_ordering(model, order):
""" order is in the form [id,id,id,id] for example: [8,4,5,1,3] """
original_order = model.objects.value_list('id', flat=True).order_by('order')
order = filter( lambda x: x[1]!=x[2], zip(xrange(len(order)), order, original_order))
for i in order:
model.objects.filter(id=i[1]).update(order=i[0])
Another approach, depending on what you're making is to do a partial update (e.g. using AJAX) if possible, instead of updating the whole re-ordered set, just update every update separately. This will often increase the total load, but will spread it more over time. Take for example moving the 5th element step-by-step to place 2, this will introduce 3 swaps: (5,4); (4,3); (3,2). Resulting in 6 updates, while with the all-in-one-time approach only 4 will be needed. But the small operations will be spread over time.
A:
I don't know if it is possible to do this using one query, but this is more efficient in any case:
def update_ordering(model, order):
""" order is in the form [id,id,id,id] for example: [8,4,5,1,3] """
for id in model.objects.values_list('id', flat=True):
model.objects.filter(id=id).update(order=order.index(id))
| Django: Update order attribute for objects in a queryset | I'm having a attribute on my model to allow the user to order the objects. I have to update the element's order depending on a list, that contains the object's ids in the new order; right now I'm iterating over the whole queryset and set one objects after the other. What would be the easiest/fastest way to do the same with the whole queryset?
def update_ordering(model, order):
""" order is in the form [id,id,id,id] for example: [8,4,5,1,3] """
id_to_order = dict((order[i], i) for i in range(len(order)))
for x in model.objects.all():
x.order = id_to_order[x.id]
x.save()
| [
"This cannot be done in one single queryset operation. As far as I know it can't even be done in one query with raw SQL. So you will always need the update call for each object that has to be updated. So both your and Collin Anderson's solutions seem quite optimal for your description.\nHowever, what's your use case? Is really the whole list going to change every time? In most situations this seems very unlikely. I can see some different approaches.\nYou save the order field like you say, but you generate a diff for the order list:def \nupdate_ordering(model, order):\n \"\"\" order is in the form [id,id,id,id] for example: [8,4,5,1,3] \"\"\"\n original_order = model.objects.value_list('id', flat=True).order_by('order')\n order = filter( lambda x: x[1]!=x[2], zip(xrange(len(order)), order, original_order))\n for i in order:\n model.objects.filter(id=i[1]).update(order=i[0])\n\nAnother approach, depending on what you're making is to do a partial update (e.g. using AJAX) if possible, instead of updating the whole re-ordered set, just update every update separately. This will often increase the total load, but will spread it more over time. Take for example moving the 5th element step-by-step to place 2, this will introduce 3 swaps: (5,4); (4,3); (3,2). Resulting in 6 updates, while with the all-in-one-time approach only 4 will be needed. But the small operations will be spread over time.\n",
"I don't know if it is possible to do this using one query, but this is more efficient in any case:\ndef update_ordering(model, order):\n \"\"\" order is in the form [id,id,id,id] for example: [8,4,5,1,3] \"\"\"\n for id in model.objects.values_list('id', flat=True):\n model.objects.filter(id=id).update(order=order.index(id))\n\n"
] | [
6,
2
] | [] | [] | [
"django",
"django_queryset",
"list",
"performance",
"python"
] | stackoverflow_0003048171_django_django_queryset_list_performance_python.txt |
Q:
Has anyone here tried using the iSeries Python port?
I found http://www.iseriespython.com/, which is a version of Python for the iSeries apparently including some system specific data access classes. I am keen to try this out, but will have to get approval at work to do so. My questions are:
Does the port work well, or are there limits to what the interpreter can handle compared with standard Python implementations?
Does the iSeries database access layer work well, creating usable objects from table definitions?
A:
From what I have seen so far, it works pretty well. Note that I'm using iSeries Python 2.3.3. The fact that strings are natively EBCDIC can be a problem; it's definitely one of the reasons many third-party packages won't work as-is, even if they are pure Python. (In some cases they can be tweaked and massaged into working with judicious use of encoding and decoding.) Supposedly 2.5 uses ASCII natively, which would in principle improve compatibility, but I have no way to test this because I'm on a too-old version of OS/400.
Partly because of EBCDIC and partly because OS/400 and the QSYS file system are neither Unix-like nor Windows-like, there are some pieces of the standard library that are not implemented or are imperfectly implemented. How badly this would affect you depends on what you're trying to do.
On the plus side, the iSeries-specific features work quite well. It's very easy to work with physical files as well as stream files. Calling CL or RPG programs from Python is fairly painless. On balance, I find iSeries Python to be highly usable and very worthwhile.
Update (2012): A lot of work has gone into iSeries Python since this question was asked. Version 2.7 is now available, meaning it's up-to-date as far as 2.x versions go. A few participants of the forum are reasonably active and provide amazing support. One of them has gotten Django working on the i. As expected, the move to native ASCII strings solves a lot of the EBCDIC problems and greatly increases compatibility with third-party packages. I enthusiastically recommend iSeries Python 2.7 for anyone on V5R3 or later. (I still strongly recommend iSeries Python 2.3.3 for those who are on earlier versions of the operating system.)
Update (2021): Unfortunately, iSeriesPython is no longer maintained, and the old website and forum are gone. You can still get the software from its SourceForge repository, and it is still an amazingly useful and worthwhile asset for those who are stuck on old (pre-7.2) versions of the operating system. For those who are on 7.2 or newer, there is a Python for PASE from IBM, which should be considered the preferred way to run Python on the midrange platform. This version of Python is part of a growing ecosystem of open source software on IBM i.
A:
It sounds like it is would work as expected. Support for other libraries might be pretty limited, though.
Timothy Prickett talks about some Python ports for the iSeries in this article:
http://www.itjungle.com/tfh/tfh041706-story02.html
Also, some discussion popped up in the Python mailing archives:
http://mail.python.org/pipermail/python-list/2004-January/245276.html
A:
iSeriesPython is working very well.
We are usning it since 2005 (or earlier) in our Development and Production Environments as an utility language, for generating of COBOL source code, generating of PCML interfaces, sending SMS, validating/correcting some data ... etc.
With iSeriesPython you can access the iSeries database at 2 ways: using File400 and/or db2 module. You can execute OS/400 commands and you can work with both QSYS.LIB members and IFS stream files.
IMHO, iSeries Python is very powerful tool, more better than REXX included with iSeries.
Try it!
A:
I got permission to install iSeries Python on a box about 3 years ago. I found that it worked pretty much as advertised. I contacted the developer and he was very good about answering questions. However, before I could think about using it in production, I had to approach the developer regarding a support contract. That really isn't his gig, so he said no and we scrapped the idea. The main limitation I found is that it is several releases behind Python on other platforms.
I have also had very good experience with Jython on the iSeries. Java is completely supported on the iSeries. Theoretically, everything you can do in RPG on the iSeries, you can do in Java, which means you can do it in Jython. I was sending email from an AS/400 (old name for iSeries) via JPython (old name for Jython) and smtplib.py in 1999 or 2000.
A:
Another place to look is on the mailing list MIDRANGE-L or search the archives for the list at midrange.com. I know they have talked about this a while back.
| Has anyone here tried using the iSeries Python port? | I found http://www.iseriespython.com/, which is a version of Python for the iSeries apparently including some system specific data access classes. I am keen to try this out, but will have to get approval at work to do so. My questions are:
Does the port work well, or are there limits to what the interpreter can handle compared with standard Python implementations?
Does the iSeries database access layer work well, creating usable objects from table definitions?
| [
"From what I have seen so far, it works pretty well. Note that I'm using iSeries Python 2.3.3. The fact that strings are natively EBCDIC can be a problem; it's definitely one of the reasons many third-party packages won't work as-is, even if they are pure Python. (In some cases they can be tweaked and massaged into working with judicious use of encoding and decoding.) Supposedly 2.5 uses ASCII natively, which would in principle improve compatibility, but I have no way to test this because I'm on a too-old version of OS/400.\nPartly because of EBCDIC and partly because OS/400 and the QSYS file system are neither Unix-like nor Windows-like, there are some pieces of the standard library that are not implemented or are imperfectly implemented. How badly this would affect you depends on what you're trying to do.\nOn the plus side, the iSeries-specific features work quite well. It's very easy to work with physical files as well as stream files. Calling CL or RPG programs from Python is fairly painless. On balance, I find iSeries Python to be highly usable and very worthwhile.\nUpdate (2012): A lot of work has gone into iSeries Python since this question was asked. Version 2.7 is now available, meaning it's up-to-date as far as 2.x versions go. A few participants of the forum are reasonably active and provide amazing support. One of them has gotten Django working on the i. As expected, the move to native ASCII strings solves a lot of the EBCDIC problems and greatly increases compatibility with third-party packages. I enthusiastically recommend iSeries Python 2.7 for anyone on V5R3 or later. (I still strongly recommend iSeries Python 2.3.3 for those who are on earlier versions of the operating system.)\nUpdate (2021): Unfortunately, iSeriesPython is no longer maintained, and the old website and forum are gone. You can still get the software from its SourceForge repository, and it is still an amazingly useful and worthwhile asset for those who are stuck on old (pre-7.2) versions of the operating system. For those who are on 7.2 or newer, there is a Python for PASE from IBM, which should be considered the preferred way to run Python on the midrange platform. This version of Python is part of a growing ecosystem of open source software on IBM i.\n",
"It sounds like it is would work as expected. Support for other libraries might be pretty limited, though.\nTimothy Prickett talks about some Python ports for the iSeries in this article:\nhttp://www.itjungle.com/tfh/tfh041706-story02.html\nAlso, some discussion popped up in the Python mailing archives:\nhttp://mail.python.org/pipermail/python-list/2004-January/245276.html\n",
"iSeriesPython is working very well. \nWe are usning it since 2005 (or earlier) in our Development and Production Environments as an utility language, for generating of COBOL source code, generating of PCML interfaces, sending SMS, validating/correcting some data ... etc.\nWith iSeriesPython you can access the iSeries database at 2 ways: using File400 and/or db2 module. You can execute OS/400 commands and you can work with both QSYS.LIB members and IFS stream files.\nIMHO, iSeries Python is very powerful tool, more better than REXX included with iSeries.\nTry it!\n",
"I got permission to install iSeries Python on a box about 3 years ago. I found that it worked pretty much as advertised. I contacted the developer and he was very good about answering questions. However, before I could think about using it in production, I had to approach the developer regarding a support contract. That really isn't his gig, so he said no and we scrapped the idea. The main limitation I found is that it is several releases behind Python on other platforms.\nI have also had very good experience with Jython on the iSeries. Java is completely supported on the iSeries. Theoretically, everything you can do in RPG on the iSeries, you can do in Java, which means you can do it in Jython. I was sending email from an AS/400 (old name for iSeries) via JPython (old name for Jython) and smtplib.py in 1999 or 2000. \n",
"Another place to look is on the mailing list MIDRANGE-L or search the archives for the list at midrange.com. I know they have talked about this a while back.\n"
] | [
7,
5,
4,
3,
0
] | [] | [] | [
"ibm_midrange",
"python"
] | stackoverflow_0000752349_ibm_midrange_python.txt |
Q:
heapq.nlargest index of returned result in original sequence
How do I return the index in the original list of the nth largest items of an iterable
heapq.nlargest(2, [100, 2, 400, 500, 400])
output = [(3,500), (2, 400)]
This already cost me a couple hours. I can't figure it out.
A:
>>> seq = [100, 2, 400, 500, 400]
>>> heapq.nlargest(2, enumerate(seq), key=lambda x: x[1])
[(3, 500), (2, 400)]
A:
You can use list.index in combination with map, which is fast for small n (beware the list.index returns the index in the list of the first item whose value is x):
>>> iterable = [100, 2, 400, 500, 400]
>>> map(iterable.index, heapq.nlargest(2, iterable))
[3, 2]
To see the associated values ...
>>> map(lambda n: (n, iterable.index(n)), heapq.nlargest(2, iterable))
[(500, 3), (400, 2)]
For larger n see @SilentGhost's post.
Edit: Benchmarked some solution:
#!/usr/bin/env python
import heapq
from timeit import Timer
seq = [100, 2, 400, 500, 400]
def a(seq):
"""returns [(3, 500), (2, 400)]"""
return heapq.nlargest(2, enumerate(seq), key=lambda x: x[1])
def b(seq):
"""returns [3, 2]"""
return map(seq.index, heapq.nlargest(2, seq))
def c(seq):
"""returns [(500, 3), (400, 2)]"""
map(lambda n: (n, seq.index(n)), heapq.nlargest(2, seq))
if __name__ == '__main__':
_a = Timer("a(seq)", "from __main__ import a, seq")
_b = Timer("b(seq)", "from __main__ import b, seq")
_c = Timer("c(seq)", "from __main__ import c, seq")
loops = 1000000
print _a.timeit(number=loops)
print _b.timeit(number=loops)
print _c.timeit(number=loops)
# Core i5, 2.4GHz, Python 2.6, Darwin
# 8.92712688446
# 5.64332985878
# 6.50824809074
| heapq.nlargest index of returned result in original sequence | How do I return the index in the original list of the nth largest items of an iterable
heapq.nlargest(2, [100, 2, 400, 500, 400])
output = [(3,500), (2, 400)]
This already cost me a couple hours. I can't figure it out.
| [
">>> seq = [100, 2, 400, 500, 400]\n>>> heapq.nlargest(2, enumerate(seq), key=lambda x: x[1])\n[(3, 500), (2, 400)]\n\n",
"You can use list.index in combination with map, which is fast for small n (beware the list.index returns the index in the list of the first item whose value is x):\n>>> iterable = [100, 2, 400, 500, 400]\n>>> map(iterable.index, heapq.nlargest(2, iterable))\n[3, 2]\n\nTo see the associated values ...\n>>> map(lambda n: (n, iterable.index(n)), heapq.nlargest(2, iterable))\n[(500, 3), (400, 2)]\n\nFor larger n see @SilentGhost's post.\n\nEdit: Benchmarked some solution:\n#!/usr/bin/env python\nimport heapq\nfrom timeit import Timer\n\nseq = [100, 2, 400, 500, 400]\n\ndef a(seq):\n \"\"\"returns [(3, 500), (2, 400)]\"\"\"\n return heapq.nlargest(2, enumerate(seq), key=lambda x: x[1])\n\ndef b(seq):\n \"\"\"returns [3, 2]\"\"\"\n return map(seq.index, heapq.nlargest(2, seq))\n\ndef c(seq):\n \"\"\"returns [(500, 3), (400, 2)]\"\"\"\n map(lambda n: (n, seq.index(n)), heapq.nlargest(2, seq))\n\nif __name__ == '__main__':\n _a = Timer(\"a(seq)\", \"from __main__ import a, seq\")\n _b = Timer(\"b(seq)\", \"from __main__ import b, seq\")\n _c = Timer(\"c(seq)\", \"from __main__ import c, seq\") \n\n loops = 1000000\n\n print _a.timeit(number=loops)\n print _b.timeit(number=loops)\n print _c.timeit(number=loops)\n\n # Core i5, 2.4GHz, Python 2.6, Darwin\n # 8.92712688446\n # 5.64332985878\n # 6.50824809074\n\n"
] | [
29,
6
] | [] | [] | [
"heap",
"python",
"sorting"
] | stackoverflow_0003139869_heap_python_sorting.txt |
Q:
Python limited multithreading
As you surely know, I can do multithreading to download files from the Internet faster.
But if I send lots of requests to the same website, I could be black listed.
So could you help me to implement something like
"I've got a list of urls.
I want you to download all of these files but if 10 downloads are already running, wait for a slot."
I'll appreciate any help.
Tk.
binoua
This is the code I'm using (doesn't work).
class PDBDownloader(threading.Thread):
prefix = 'http://www.rcsb.org/pdb/files/'
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
self.pdbid = None
self.urlstr = ''
self.content = ''
def run(self):
while True:
self.pdbid = self.queue.get()
self.urlstr = self.prefix + pdbid + '.pdb'
print 'downloading', pdbid
self.download()
filename = '%s.pdb' %(pdbid)
f = open(filename, 'wt')
f.write(self.content)
f.close()
self.queue.task_done()
def download(self):
try:
f = urllib2.urlopen(self.urlstr)
except urllib2.HTTPError, e:
msg = 'HTTPError while downloading file %s at %s. '\
'Details: %s.' %(self.pdbid, self.urlstr, str(e))
raise OstDownloadException, msg
except urllib2.URLError, e:
msg = 'URLError while downloading file %s at %s. '\
'RCSB erveur unavailable.' %(self.pdbid, self.urlstr)
raise OstDownloadException, msg
except Exception, e:
raise OstDownloadException, str(e)
else:
self.content = f.read()
if __name__ == '__main__':
pdblist = ['1BTA', '3EAM', '1EGJ', '2BV9', '2X6A']
for i in xrange(len(pdblist)):
pdb = PDBDownloader(queue)
pdb.setDaemon(True)
pdb.start()
while pdblist:
pdbid = pdblist.pop()
queue.put(pdbid)
queue.join()
A:
Using threads doesn't "download files from the Internet faster". You have only one network card and one internet connection so that's just not true.
The threads are being used to wait, and you can't wait faster.
You can use a single thread and be as fast, or even faster -- Just don't wait for the response of one file before starting another. In other words, use asynchronous, non-blocking network programming.
Here's a complete script that uses twisted.internet.task.coiterate to start multiple downloads at the same time, without using any kind of threading, and respecting the pool size (I'm using 2 simultaneous downloads for the demonstration, but you can change the size):
from twisted.internet import defer, task, reactor
from twisted.web import client
from twisted.python import log
@defer.inlineCallbacks
def deferMap(job, dataSource, size=1):
successes = []
failures = []
def _cbGather(result, dataUnit, succeeded):
"""This will be called when any download finishes"""
if succeeded:
# you could save the file to disk here
successes.append((dataUnit, result))
else:
failures.append((dataUnit, result))
@apply
def work():
for dataUnit in dataSource:
d = job(dataUnit).addCallbacks(_cbGather, _cbGather,
callbackArgs=(dataUnit, True), errbackArgs=(dataUnit, False))
yield d
yield defer.DeferredList([task.coiterate(work) for i in xrange(size)])
defer.returnValue((successes, failures))
def printResults(result):
successes, failures = result
print "*** Got %d pages total:" % (len(successes),)
for url, page in successes:
print ' * %s -> %d bytes' % (url, len(page))
if failures:
print "*** %d pages failed download:" % (len(failures),)
for url, failure in failures:
print ' * %s -> %s' % (url, failure.getErrorMessage())
if __name__ == '__main__':
import sys
log.startLogging(sys.stdout)
urls = ['http://twistedmatrix.com',
'XXX',
'http://debian.org',
'http://python.org',
'http://python.org/foo',
'https://launchpad.net',
'noway.com',
'somedata',
]
pool = deferMap(client.getPage, urls, size=2) # download 2 at once
pool.addCallback(printResults)
pool.addErrback(log.err).addCallback(lambda ign: reactor.stop())
reactor.run()
Note that I included some bad urls on purpose so we can see some failures in the result:
...
2010-06-29 08:18:04-0300 [-] *** Got 4 pages total:
2010-06-29 08:18:04-0300 [-] * http://twistedmatrix.com -> 16992 bytes
2010-06-29 08:18:04-0300 [-] * http://python.org -> 17207 bytes
2010-06-29 08:18:04-0300 [-] * http://debian.org -> 13820 bytes
2010-06-29 08:18:04-0300 [-] * https://launchpad.net -> 18511 bytes
2010-06-29 08:18:04-0300 [-] *** 4 pages failed download:
2010-06-29 08:18:04-0300 [-] * XXX -> Connection was refused by other side: 111: Connection refused.
2010-06-29 08:18:04-0300 [-] * http://python.org/foo -> 404 Not Found
2010-06-29 08:18:04-0300 [-] * noway.com -> Connection was refused by other side: 111: Connection refused.
2010-06-29 08:18:04-0300 [-] * somedata -> Connection was refused by other side: 111: Connection refused.
...
A:
Use a thread pool with a shared list of urls. Each thread tries to pop a url from the list and download it until none are left. pop() from a list is threadsafe
while True:
try:
url = url_list.pop()
# download URL here
except IndexError:
break
| Python limited multithreading | As you surely know, I can do multithreading to download files from the Internet faster.
But if I send lots of requests to the same website, I could be black listed.
So could you help me to implement something like
"I've got a list of urls.
I want you to download all of these files but if 10 downloads are already running, wait for a slot."
I'll appreciate any help.
Tk.
binoua
This is the code I'm using (doesn't work).
class PDBDownloader(threading.Thread):
prefix = 'http://www.rcsb.org/pdb/files/'
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
self.pdbid = None
self.urlstr = ''
self.content = ''
def run(self):
while True:
self.pdbid = self.queue.get()
self.urlstr = self.prefix + pdbid + '.pdb'
print 'downloading', pdbid
self.download()
filename = '%s.pdb' %(pdbid)
f = open(filename, 'wt')
f.write(self.content)
f.close()
self.queue.task_done()
def download(self):
try:
f = urllib2.urlopen(self.urlstr)
except urllib2.HTTPError, e:
msg = 'HTTPError while downloading file %s at %s. '\
'Details: %s.' %(self.pdbid, self.urlstr, str(e))
raise OstDownloadException, msg
except urllib2.URLError, e:
msg = 'URLError while downloading file %s at %s. '\
'RCSB erveur unavailable.' %(self.pdbid, self.urlstr)
raise OstDownloadException, msg
except Exception, e:
raise OstDownloadException, str(e)
else:
self.content = f.read()
if __name__ == '__main__':
pdblist = ['1BTA', '3EAM', '1EGJ', '2BV9', '2X6A']
for i in xrange(len(pdblist)):
pdb = PDBDownloader(queue)
pdb.setDaemon(True)
pdb.start()
while pdblist:
pdbid = pdblist.pop()
queue.put(pdbid)
queue.join()
| [
"Using threads doesn't \"download files from the Internet faster\". You have only one network card and one internet connection so that's just not true.\nThe threads are being used to wait, and you can't wait faster.\nYou can use a single thread and be as fast, or even faster -- Just don't wait for the response of one file before starting another. In other words, use asynchronous, non-blocking network programming.\nHere's a complete script that uses twisted.internet.task.coiterate to start multiple downloads at the same time, without using any kind of threading, and respecting the pool size (I'm using 2 simultaneous downloads for the demonstration, but you can change the size):\nfrom twisted.internet import defer, task, reactor\nfrom twisted.web import client\nfrom twisted.python import log\n\n@defer.inlineCallbacks\ndef deferMap(job, dataSource, size=1):\n successes = []\n failures = []\n\n def _cbGather(result, dataUnit, succeeded):\n \"\"\"This will be called when any download finishes\"\"\"\n if succeeded:\n # you could save the file to disk here\n successes.append((dataUnit, result))\n else:\n failures.append((dataUnit, result))\n\n @apply\n def work():\n for dataUnit in dataSource:\n d = job(dataUnit).addCallbacks(_cbGather, _cbGather,\n callbackArgs=(dataUnit, True), errbackArgs=(dataUnit, False))\n yield d\n\n yield defer.DeferredList([task.coiterate(work) for i in xrange(size)])\n defer.returnValue((successes, failures))\n\ndef printResults(result):\n successes, failures = result\n print \"*** Got %d pages total:\" % (len(successes),)\n for url, page in successes:\n print ' * %s -> %d bytes' % (url, len(page))\n if failures:\n print \"*** %d pages failed download:\" % (len(failures),)\n for url, failure in failures:\n print ' * %s -> %s' % (url, failure.getErrorMessage())\n\nif __name__ == '__main__':\n import sys\n log.startLogging(sys.stdout)\n urls = ['http://twistedmatrix.com',\n 'XXX',\n 'http://debian.org',\n 'http://python.org',\n 'http://python.org/foo',\n 'https://launchpad.net',\n 'noway.com',\n 'somedata',\n ]\n pool = deferMap(client.getPage, urls, size=2) # download 2 at once\n pool.addCallback(printResults)\n pool.addErrback(log.err).addCallback(lambda ign: reactor.stop())\n reactor.run()\n\nNote that I included some bad urls on purpose so we can see some failures in the result:\n...\n2010-06-29 08:18:04-0300 [-] *** Got 4 pages total:\n2010-06-29 08:18:04-0300 [-] * http://twistedmatrix.com -> 16992 bytes\n2010-06-29 08:18:04-0300 [-] * http://python.org -> 17207 bytes\n2010-06-29 08:18:04-0300 [-] * http://debian.org -> 13820 bytes\n2010-06-29 08:18:04-0300 [-] * https://launchpad.net -> 18511 bytes\n2010-06-29 08:18:04-0300 [-] *** 4 pages failed download:\n2010-06-29 08:18:04-0300 [-] * XXX -> Connection was refused by other side: 111: Connection refused.\n2010-06-29 08:18:04-0300 [-] * http://python.org/foo -> 404 Not Found\n2010-06-29 08:18:04-0300 [-] * noway.com -> Connection was refused by other side: 111: Connection refused.\n2010-06-29 08:18:04-0300 [-] * somedata -> Connection was refused by other side: 111: Connection refused.\n...\n\n",
"Use a thread pool with a shared list of urls. Each thread tries to pop a url from the list and download it until none are left. pop() from a list is threadsafe\nwhile True:\n try:\n url = url_list.pop()\n # download URL here\n except IndexError:\n break\n\n"
] | [
4,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0003139513_multithreading_python.txt |
Q:
Converting from utf-16 to utf-8 in Python 3
I'm programming in Python 3 and I'm having a small problem which I can't find any reference to it on the net.
As far as I understand the default string in is utf-16, but I must work with utf-8, I can't find the command that will convert from the default one to utf-8.
I'd appreciate your help very much.
A:
In Python 3 there are two different datatypes important when you are working with string manipulation. First there is the string class, an object that represents unicode code points. Important to get is that this string is not some bytes, but really a sequence of characters. Secondly, there is the bytes class, which is just a sequence of bytes, often representing an string stored in an encoding (like utf-8 or iso-8859-15).
What does this mean for you? As far as I understand you want to read and write utf-8 files. Let's make a program that replaces all 'ć' with 'ç' characters
def main():
# Let's first open an output file. See how we give an encoding to let python know, that when we print something to the file, it should be encoded as utf-8
with open('output_file', 'w', encoding='utf-8') as out_file:
# read every line. We give open() the encoding so it will return a Unicode string.
for line in open('input_file', encoding='utf-8'):
#Replace the characters we want. When you define a string in python it also is automatically a unicode string. No worries about encoding there. Because we opened the file with the utf-8 encoding, the print statement will encode the whole string to utf-8.
print(line.replace('ć', 'ç'), out_file)
So when should you use bytes? Not often. An example I could think of would be when you read something from a socket. If you have this in an bytes object, you could make it a unicode string by doing bytes.decode('encoding') and visa versa with str.encode('encoding'). But as said, probably you won't need it.
Still, because it is interesting, here the hard way, where you encode everything yourself:
def main():
# Open the file in binary mode. So we are going to write bytes to it instead of strings
with open('output_file', 'wb') as out_file:
# read every line. Again, we open it binary, so we get bytes
for line_bytes in open('input_file', 'rb'):
#Convert the bytes to a string
line_string = bytes.decode('utf-8')
#Replace the characters we want.
line_string = line_string.replace('ć', 'ç')
#Make a bytes to print
out_bytes = line_string.encode('utf-8')
#Print the bytes
print(out_bytes, out_file)
Good reading about this topic (string encodings) is http://www.joelonsoftware.com/articles/Unicode.html. Really recommended read!
Source: http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit
(P.S. As you see, I didn't mention utf-16 in this post. I actually don't know whether python uses this as internal decoding or not, but it is totally irrelevant. At the moment you are working with a string, you work with characters (code points), not bytes.
| Converting from utf-16 to utf-8 in Python 3 | I'm programming in Python 3 and I'm having a small problem which I can't find any reference to it on the net.
As far as I understand the default string in is utf-16, but I must work with utf-8, I can't find the command that will convert from the default one to utf-8.
I'd appreciate your help very much.
| [
"In Python 3 there are two different datatypes important when you are working with string manipulation. First there is the string class, an object that represents unicode code points. Important to get is that this string is not some bytes, but really a sequence of characters. Secondly, there is the bytes class, which is just a sequence of bytes, often representing an string stored in an encoding (like utf-8 or iso-8859-15).\nWhat does this mean for you? As far as I understand you want to read and write utf-8 files. Let's make a program that replaces all 'ć' with 'ç' characters\ndef main():\n # Let's first open an output file. See how we give an encoding to let python know, that when we print something to the file, it should be encoded as utf-8\n with open('output_file', 'w', encoding='utf-8') as out_file:\n # read every line. We give open() the encoding so it will return a Unicode string. \n for line in open('input_file', encoding='utf-8'):\n #Replace the characters we want. When you define a string in python it also is automatically a unicode string. No worries about encoding there. Because we opened the file with the utf-8 encoding, the print statement will encode the whole string to utf-8.\n print(line.replace('ć', 'ç'), out_file)\n\nSo when should you use bytes? Not often. An example I could think of would be when you read something from a socket. If you have this in an bytes object, you could make it a unicode string by doing bytes.decode('encoding') and visa versa with str.encode('encoding'). But as said, probably you won't need it.\nStill, because it is interesting, here the hard way, where you encode everything yourself:\ndef main():\n # Open the file in binary mode. So we are going to write bytes to it instead of strings\n with open('output_file', 'wb') as out_file:\n # read every line. Again, we open it binary, so we get bytes \n for line_bytes in open('input_file', 'rb'):\n #Convert the bytes to a string\n line_string = bytes.decode('utf-8')\n #Replace the characters we want. \n line_string = line_string.replace('ć', 'ç')\n #Make a bytes to print\n out_bytes = line_string.encode('utf-8')\n #Print the bytes\n print(out_bytes, out_file)\n\nGood reading about this topic (string encodings) is http://www.joelonsoftware.com/articles/Unicode.html. Really recommended read!\nSource: http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit\n(P.S. As you see, I didn't mention utf-16 in this post. I actually don't know whether python uses this as internal decoding or not, but it is totally irrelevant. At the moment you are working with a string, you work with characters (code points), not bytes.\n"
] | [
7
] | [] | [] | [
"character_encoding",
"python",
"python_3.x",
"utf_16",
"utf_8"
] | stackoverflow_0003140010_character_encoding_python_python_3.x_utf_16_utf_8.txt |
Q:
appcfg.py: error: no such option: --dump on google-app-engine
Possible Duplicate:
How can I use the Google App engine bulkloader to back up all my data?
i follow this article :http://code.google.com/intl/en/appengine/docs/python/tools/uploadingdata.html
and want to download all data from my app ,
but when i use the next code,it show error:
D:\zjm_demo\app>appcfg.py --dump --app_id=zjm1126 --url=http://zjm1126.appspot.c
om/remote_api --filename=a.csv
Usage: appcfg.py [options] <action>
appcfg.py: error: no such option: --dump
why ?
thanks
updated
i use this :
appcfg.py download_data --application=zjm1126 --url=http://zjm1126.appspot.com/remote_api --filename=a.csv
A:
The documentation appears to be incorrect:
I found that I had to use download_data instead of --dump and --application instead of --app_id, for example:
appcfg.py download_data --application=app_id --url=http://etc --filename=file
This is a duplicate of How can I use the Google App engine bulkloader to back up all my data?
A:
I don't have a "why" answer, but it looks to me like you'll want to use the download_data action instead.
> appcfg help download_data
Usage: appcfg.py [options] download_data <directory>
Download entities from datastore.
The 'download_data' command downloads datastore entities and writes them to
file as CSV or developer defined format.
...
You may want to read the Configuring the Bulk Loader section for more information. I've never had a need to download my data, so I've no real experience with this.
A:
use appcfg.py download_data "Application Directory / --app_id" --config_file=etc.yaml --kind=etc --filename=etc.csv
| appcfg.py: error: no such option: --dump on google-app-engine |
Possible Duplicate:
How can I use the Google App engine bulkloader to back up all my data?
i follow this article :http://code.google.com/intl/en/appengine/docs/python/tools/uploadingdata.html
and want to download all data from my app ,
but when i use the next code,it show error:
D:\zjm_demo\app>appcfg.py --dump --app_id=zjm1126 --url=http://zjm1126.appspot.c
om/remote_api --filename=a.csv
Usage: appcfg.py [options] <action>
appcfg.py: error: no such option: --dump
why ?
thanks
updated
i use this :
appcfg.py download_data --application=zjm1126 --url=http://zjm1126.appspot.com/remote_api --filename=a.csv
| [
"The documentation appears to be incorrect:\nI found that I had to use download_data instead of --dump and --application instead of --app_id, for example:\nappcfg.py download_data --application=app_id --url=http://etc --filename=file \n\nThis is a duplicate of How can I use the Google App engine bulkloader to back up all my data?\n",
"I don't have a \"why\" answer, but it looks to me like you'll want to use the download_data action instead.\n> appcfg help download_data\nUsage: appcfg.py [options] download_data <directory>\n\nDownload entities from datastore.\n\nThe 'download_data' command downloads datastore entities and writes them to\nfile as CSV or developer defined format.\n\n...\n\nYou may want to read the Configuring the Bulk Loader section for more information. I've never had a need to download my data, so I've no real experience with this.\n",
"use appcfg.py download_data \"Application Directory / --app_id\" --config_file=etc.yaml --kind=etc --filename=etc.csv\n"
] | [
1,
0,
0
] | [] | [] | [
"dump",
"google_app_engine",
"python"
] | stackoverflow_0003066934_dump_google_app_engine_python.txt |
Q:
News sources for python django
I find myself continually sifting through the net to keep up with Python/Django/web development trends and news. Does anyone recommend any good news sites that focus on web development or they Python community? For example, what new Django modules are popular or interesting new jQuery plugins, etc. Just curious to know how others keep their knowledge up to date.
A:
The Django community aggregator is a great source of news and information about what people are doing with Django.
A:
Coder.io lists Django news too but Django's own community page is my primary source.
http://coder.io/tag/django
A:
Django Dose is great. They have a bit or erratic updates (but they're back to posting again), but when they do, they really pick up the most interesting developments, both in trunk and around the community. Also the django sub-reddit is pretty good too, most things tend to come that way.
A:
I run a Tumblr blog called Djangoed which picks out the best/interesting stories from various sources (including the community aggregator, Django Sites and Reddit amongst others).
| News sources for python django | I find myself continually sifting through the net to keep up with Python/Django/web development trends and news. Does anyone recommend any good news sites that focus on web development or they Python community? For example, what new Django modules are popular or interesting new jQuery plugins, etc. Just curious to know how others keep their knowledge up to date.
| [
"The Django community aggregator is a great source of news and information about what people are doing with Django.\n",
"Coder.io lists Django news too but Django's own community page is my primary source. \nhttp://coder.io/tag/django\n",
"Django Dose is great. They have a bit or erratic updates (but they're back to posting again), but when they do, they really pick up the most interesting developments, both in trunk and around the community. Also the django sub-reddit is pretty good too, most things tend to come that way.\n",
"I run a Tumblr blog called Djangoed which picks out the best/interesting stories from various sources (including the community aggregator, Django Sites and Reddit amongst others).\n"
] | [
4,
2,
1,
1
] | [] | [] | [
"django",
"feed",
"python"
] | stackoverflow_0003130494_django_feed_python.txt |
Q:
Templating and form processing toolkits to use with twisted.web
As the title states, I am looking for something, that will help me automate form processing (validation/rendering/etc) in twisted.web. I am also looking for a suitable templating toolkit to use with it.
As for templating, it is not so much of an issue as there are a lot of libraries in python, that do it. I was considering the following:
Nevow. Well, it is not only a templating toolkit, but a lot of other things that I may or may not need. It also plays nice with twisted's asynchronous nature (as far as I know, you can do incremental rendering with it, whether that is good or bad)
Jinja2. I haven't used it yet, but people seem to recommend it a lot. I've read about it and it seems to be a decent toolkit.
Genshi. same as the previous one
Django's templating engine. I've used it quite a lot. There are some drawbacks, but, well, it works. This is not a django project, so there is no need to restrict myself to django's components, though.
Hell, I can theoretically generate xhtml using xslt (but I won't :P), since almost all the data the project deals with is xml
As for form processing, I must say, that the only python web framework I am familiar with is django (quite familiar with it, actually) so I don't really know what I should be considering here.
I know nevow has some kind of form processing built-in, apparently (called formless), but I have no idea how good it is and I haven't found any documentation (besides the source) or usage examples (besides the completely trivial one in the turorial).
The other option I was considering is "bolting on" django's forms, since the forms are not really coupled to anything else in django, so it is possible to use them separately. I'd rather not do it, though, if it is at all possible.
Maybe someone with an existing twisted.web project can give me a hint or two.
A:
I really like Jinja2. It's an improved form of the django templating system. I use it pretty extensively in my projects.
For form processing, you may want to check out formosa.
A:
My experience of Nevow is that examples and documentation are hard to find on the web. There are some basic ones linked from the Nevow homepage (http://divmod.org/trac/wiki/DivmodNevow), but nothing like the volume of examples and questions/asnwers you would see with the larger Java frameworks (which I am more familiar with) for example.
This seems to be borne out with some simple google searches:
search for Python Nevow returns approx 155k results
search for Python twisted returns approx 1000k results
search for Python Django returns approx 19,700k results
search for Java Spring returns approx 13,000k results
I realise this is not too scientific but it does support my experience. I would be very happy for someone to correct this if I have missed something and point us all towards a rich source of Nevow (and especially Athena, the Ajax component) documentation...
| Templating and form processing toolkits to use with twisted.web | As the title states, I am looking for something, that will help me automate form processing (validation/rendering/etc) in twisted.web. I am also looking for a suitable templating toolkit to use with it.
As for templating, it is not so much of an issue as there are a lot of libraries in python, that do it. I was considering the following:
Nevow. Well, it is not only a templating toolkit, but a lot of other things that I may or may not need. It also plays nice with twisted's asynchronous nature (as far as I know, you can do incremental rendering with it, whether that is good or bad)
Jinja2. I haven't used it yet, but people seem to recommend it a lot. I've read about it and it seems to be a decent toolkit.
Genshi. same as the previous one
Django's templating engine. I've used it quite a lot. There are some drawbacks, but, well, it works. This is not a django project, so there is no need to restrict myself to django's components, though.
Hell, I can theoretically generate xhtml using xslt (but I won't :P), since almost all the data the project deals with is xml
As for form processing, I must say, that the only python web framework I am familiar with is django (quite familiar with it, actually) so I don't really know what I should be considering here.
I know nevow has some kind of form processing built-in, apparently (called formless), but I have no idea how good it is and I haven't found any documentation (besides the source) or usage examples (besides the completely trivial one in the turorial).
The other option I was considering is "bolting on" django's forms, since the forms are not really coupled to anything else in django, so it is possible to use them separately. I'd rather not do it, though, if it is at all possible.
Maybe someone with an existing twisted.web project can give me a hint or two.
| [
"I really like Jinja2. It's an improved form of the django templating system. I use it pretty extensively in my projects.\nFor form processing, you may want to check out formosa.\n",
"My experience of Nevow is that examples and documentation are hard to find on the web. There are some basic ones linked from the Nevow homepage (http://divmod.org/trac/wiki/DivmodNevow), but nothing like the volume of examples and questions/asnwers you would see with the larger Java frameworks (which I am more familiar with) for example.\nThis seems to be borne out with some simple google searches:\n\nsearch for Python Nevow returns approx 155k results\nsearch for Python twisted returns approx 1000k results\nsearch for Python Django returns approx 19,700k results\nsearch for Java Spring returns approx 13,000k results\n\nI realise this is not too scientific but it does support my experience. I would be very happy for someone to correct this if I have missed something and point us all towards a rich source of Nevow (and especially Athena, the Ajax component) documentation...\n"
] | [
1,
1
] | [] | [] | [
"forms",
"python",
"templates",
"twisted",
"twisted.web"
] | stackoverflow_0003128548_forms_python_templates_twisted_twisted.web.txt |
Q:
Do dictionaries in Python offer the best way to formulate switch-like statements?
I'm hoping there's no performance or other disadvantage in attempting to avoid long chains of conditional if/elif statements this way:
errstr = {404: "404 Not Found",
405: "405 Method Not Allowed"}
if code in errstr:
print errstr[code];
A:
Yes, they're the best solution, because they are implemented as hash tables, giving approximately constant lookup times (if the hash function is good). Binary trees would give logarithmic lookup time, if chains linear time. Hash tables are usually the way to go if one has to represent a mapping from a not-too-large finite set to some other set.
BTW, Python is a very good language for learning, because in Python, often the simplest solution is also the best one.
| Do dictionaries in Python offer the best way to formulate switch-like statements? | I'm hoping there's no performance or other disadvantage in attempting to avoid long chains of conditional if/elif statements this way:
errstr = {404: "404 Not Found",
405: "405 Method Not Allowed"}
if code in errstr:
print errstr[code];
| [
"Yes, they're the best solution, because they are implemented as hash tables, giving approximately constant lookup times (if the hash function is good). Binary trees would give logarithmic lookup time, if chains linear time. Hash tables are usually the way to go if one has to represent a mapping from a not-too-large finite set to some other set.\nBTW, Python is a very good language for learning, because in Python, often the simplest solution is also the best one.\n"
] | [
4
] | [] | [] | [
"conditional",
"dictionary",
"python",
"switch_statement"
] | stackoverflow_0003140928_conditional_dictionary_python_switch_statement.txt |
Q:
SSH Dynamic Port Forwarding ('ssh -D') in Python
I'm looking for a way to implement SSH Dynamic Port Forwarding ('ssh -D') under Python. The problem is that it has to work under Windows, i.e., running SSH with popen/pexec/etc. won't work. Any ideas?
cheers,
Bruno Nery.
A:
Have you tried Paramiko?
A:
There are ssh executables for Windows, so you can uses the subprocess.Popen approach. This is not exactly elegant, a pure Python approach would be better.
| SSH Dynamic Port Forwarding ('ssh -D') in Python | I'm looking for a way to implement SSH Dynamic Port Forwarding ('ssh -D') under Python. The problem is that it has to work under Windows, i.e., running SSH with popen/pexec/etc. won't work. Any ideas?
cheers,
Bruno Nery.
| [
"Have you tried Paramiko?\n",
"There are ssh executables for Windows, so you can uses the subprocess.Popen approach. This is not exactly elegant, a pure Python approach would be better.\n"
] | [
1,
1
] | [] | [] | [
"python",
"ssh",
"ssh_tunnel",
"tunneling",
"windows"
] | stackoverflow_0003141063_python_ssh_ssh_tunnel_tunneling_windows.txt |
Q:
Python DataError coming from stored procedure, but no error when run manually
I am getting this error:
DataError: (DataError) invalid input syntax for integer:
"1.50" CONTEXT: PL/pgSQL function "sp_aggregate_cart" line 82
at FOR over EXECUTE statement
'SELECT total_items, subtotal, is_shipping_required, discount_other,
is_shipping_discount FROM sp_aggregate_cart(8135)' {}
When running my application code. When I run that query manually, everything is fine. I happen to know the 1.50 is in this instance, and it is a value that is passed through a variable in the function that is declared as numeric(10,2). It is NOT returned by the function, just processed.
How can this query throw this error in the application code, but run fine in pgadmin?
Ok, here is the stored procedure. The discount_amount is the 1.50 you see the error on.
CREATE TYPE buy_object_info as (object_id integer, promo_id integer, buy_quantity integer, get_quantity integer, quantity integer, discount_amount numeric(10,2));
-- Function: sp_aggregate_cart(integer)
DROP FUNCTION sp_aggregate_cart(integer);
CREATE OR REPLACE FUNCTION sp_aggregate_cart(p_cart_id integer)
RETURNS SETOF cart AS
$BODY$
DECLARE
v_total_items int;
v_subtotal numeric;
v_discount_other record;
v_items_shipping integer;
v_shipping_required boolean;
buy_object_info buy_object_info%rowtype;
buy_object_price numeric;
buy_object_orginal_subtotal numeric;
other_promo_id integer;
buy_object_query text;
other_promo_buy_quantity integer;
BEGIN
-- Get the total number of items
SELECT sum(quantity) INTO v_total_items FROM cart_object WHERE cart_id = p_cart_id;
-- Get the subtotal
SELECT sum(unit_price) INTO v_subtotal FROM (
SELECT co.cart_id, co.object_id, co.quantity,
CASE
--When buy only cart quantity = buy quantity
WHEN (p.get_quantity = 0 or p.get_quantity IS NULL) AND (p.buy_quantity > 0 OR p.buy_quantity IS NOT NULL) AND pbo.object_id = co.object_id AND p.buy_quantity = co.quantity
THEN ((cast(oa.value AS numeric(10,2)) - COALESCE(pco.discount_amount, 0)) * p.buy_quantity)
--When buy only more than the buy quantity in cart
WHEN (p.get_quantity = 0 or p.get_quantity IS NULL) AND (p.buy_quantity > 0 OR p.buy_quantity IS NOT NULL) AND pbo.object_id = co.object_id AND p.buy_quantity < co.quantity
THEN (((cast(oa.value AS numeric(10,2)) - COALESCE(pco.discount_amount, 0))) * p.buy_quantity) + ((co.quantity - p.buy_quantity) * (cast(oa.value AS numeric(10,2))))
--When buy/get
WHEN (p.get_quantity > 0 or p.get_quantity IS NOT NULL) AND (p.buy_quantity > 0 OR p.buy_quantity IS NOT NULL) AND pgo.object_id = co.object_id
THEN ((cast(oa.value AS numeric(10,2)) - COALESCE(pco.discount_amount, 0)) + ((co.quantity - 1) * cast(oa.value AS numeric(10,2))))
WHEN (p.get_quantity = 0 or p.get_quantity IS NULL) AND (p.buy_quantity = 0 OR p.buy_quantity IS NULL)
THEN ((cast(oa.value AS numeric(10,2)) - COALESCE(pco.discount_amount, 0)) * co.quantity)
ELSE
(cast(oa.value AS numeric(10,2)) * co.quantity)
END AS "unit_price"
FROM cart_object co
JOIN object_attr oa ON oa.object_id=co.object_id AND oa.attr_id=50
LEFT JOIN promo_cart_objects pco ON pco.cart_id=co.cart_id AND pco.object_id=co.object_id
LEFT JOIN promos p ON p.promo_id=pco.promotion_id
LEFT JOIN promo_get_objects pgo ON pgo.object_id = co.object_id AND pgo.promo_id = pco.promotion_id
LEFT JOIN promo_buy_objects pbo ON pbo.object_id = co.object_id AND pbo.promo_id = pco.promotion_id
WHERE co.cart_id=p_cart_id
GROUP BY co.cart_id, co.object_id, oa.value, co.quantity, p.get_quantity, p.buy_quantity, pbo.object_id, pgo.object_id, pco.discount_amount, p.promo_id
) AS a;
--Get the buyobjects that are in the cart and need to have their line item subtotal recalculated
-- :)
buy_object_query :=
'SELECT DISTINCT ON(pbo.object_id)
pbo.object_id, p.promo_id, p.buy_quantity, p.get_quantity, pco.discount_amount, co.quantity
FROM
promo_buy_objects pbo
JOIN
promos p on p.promo_id = pbo.promo_id AND p.active = TRUE AND now() BETWEEN p.start_date AND p.end_date
JOIN
promo_cart_objects pco ON pco.object_id = pbo.object_id
JOIN
cart_object co ON co.cart_id = pco.cart_id AND co.object_id = pbo.object_id
WHERE
pco.cart_id = ' || p_cart_id || '
AND
pbo.object_id IN(SELECT
po.object_id
FROM
promo_objects po
JOIN
promos p on p.promo_id = po.promotion_id AND p.active = TRUE AND now() BETWEEN p.start_date AND p.end_date
JOIN
promo_cart_objects pco ON pco.object_id = po.object_id
WHERE
pco.cart_id = ' || p_cart_id || '
UNION
SELECT
pgo.object_id
FROM
promo_get_objects pgo
JOIN
promos p on p.promo_id = pgo.promo_id AND p.active = TRUE AND now() BETWEEN p.start_date AND p.end_date
JOIN
promo_cart_objects pco ON pco.object_id = pgo.object_id JOIN cart_object co ON co.cart_id = pco.cart_id
WHERE pco.cart_id = ' || p_cart_id || ')
AND
co.quantity > p.buy_quantity';
FOR buy_object_info IN EXECUTE buy_object_query LOOP
--Get the price
SELECT cast("value" as numeric(10,2)) INTO buy_object_price FROM object_attr WHERE object_id = buy_object_info.object_id AND attr_id = 50;
--What was that original price? Redundant I know ...I might get around to optimizing this function
IF (buy_object_info.get_quantity = 0 or buy_object_info.get_quantity IS NULL) AND (buy_object_info.buy_quantity > 0 OR buy_object_info.buy_quantity IS NOT NULL) AND buy_object_info.buy_quantity = buy_object_info.quantity
THEN buy_object_orginal_subtotal := ((buy_object_price - COALESCE(buy_object_info.discount_amount, 0)) * buy_object_info.buy_quantity);
--When buy only more than the buy quantity in cart
ELSIF (buy_object_info.get_quantity = 0 or buy_object_info.get_quantity IS NULL) AND (buy_object_info.buy_quantity > 0 OR buy_object_info.buy_quantity IS NOT NULL) AND buy_object_info.buy_quantity < buy_object_info.quantity
THEN buy_object_orginal_subtotal := (((buy_object_price - COALESCE(buy_object_info.discount_amount, 0))) * buy_object_info.buy_quantity) + ((buy_object_info.quantity - buy_object_info.buy_quantity) * (buy_object_price));
--When buy/get
ELSIF (buy_object_info.get_quantity > 0 or buy_object_info.get_quantity IS NOT NULL) AND (buy_object_info.buy_quantity > 0 OR buy_object_info.buy_quantity IS NOT NULL)
THEN buy_object_orginal_subtotal := ((buy_object_price - COALESCE(buy_object_info.discount_amount, 0)) + ((buy_object_info.quantity - 1) * buy_object_price));
ELSIF (buy_object_info.get_quantity = 0 or buy_object_info.get_quantity IS NULL) AND (buy_object_info.buy_quantity = 0 OR buy_object_info.buy_quantity IS NULL)
THEN buy_object_orginal_subtotal := ((buy_object_price - COALESCE(buy_object_info.discount_amount, 0)) * buy_object_info.quantity);
ELSE
buy_object_orginal_subtotal := (cast(oa.value AS numeric(10,2)) * buy_object_info.quantity);
END IF;
--Well now we need that other promotion...this is so lame
SELECT INTO other_promo_id, other_promo_buy_quantity promo_id, buy_quantity FROM(
SELECT
p.promo_id AS promo_id, p.buy_quantity AS buy_quantity
FROM
promo_objects po
JOIN
promos p on p.promo_id = po.promotion_id AND p.active = TRUE AND now() BETWEEN p.start_date AND p.end_date
JOIN
promo_cart_objects pco ON pco.object_id = po.object_id
WHERE
pco.cart_id = p_cart_id
UNION
SELECT
p.promo_id AS promo_id, p.buy_quantity AS buy_quantity
FROM
promo_get_objects pgo
JOIN
promos p on p.promo_id = pgo.promo_id AND p.active = TRUE AND now() BETWEEN p.start_date AND p.end_date
JOIN
promo_cart_objects pco ON pco.object_id = pgo.object_id JOIN cart_object co ON co.cart_id = pco.cart_id
WHERE pco.cart_id = p_cart_id AND pco.object_id = buy_object_info.object_id) AS foo;
--Alrighty now that we have everything we need, let's perform this funky ass math
v_subtotal := v_subtotal - buy_object_orginal_subtotal;
v_subtotal := v_subtotal + (other_promo_buy_quantity * buy_object_price) + ((buy_object_info.quantity - other_promo_buy_quantity) * (buy_object_price - COALESCE(buy_object_info.discount_amount, 0)));
END LOOP;
--Get Discount Other
--SELECT COALESCE(max(discount_amount), 0), is_shipping_discount INTO v_discount_other FROM cart_promotion WHERE cart_id=p_cart_id;
SELECT COALESCE(discount_amount, 0) as discount, COALESCE(is_shipping_discount, false) as is_shipping_discount INTO v_discount_other
FROM promo_carts WHERE cart_id=p_cart_id order by discount_amount desc limit 1;
-- Determine if shipping is required
SELECT count(*) INTO v_items_shipping
FROM object o, object_attr oa, cart_object co
WHERE oa.object_id = o.object_id AND co.object_id = o.object_id
AND attr_id = 74 and cart_id = p_cart_id AND oa.value = 'true';
IF v_items_shipping > 0 THEN
v_shipping_required := True;
ELSE
v_shipping_required := False;
END IF;
-- Update the cart
UPDATE cart SET
total_items = COALESCE(v_total_items, 0),
subtotal = COALESCE(v_subtotal, 0),
is_shipping_required = v_shipping_required,
discount_other = COALESCE(v_discount_other.discount, 0),
is_shipping_discount = COALESCE(v_discount_other.is_shipping_discount, false)
WHERE id = p_cart_id;
RETURN QUERY SELECT * from cart WHERE id = p_cart_id;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE
COST 100
ROWS 1000;
ALTER FUNCTION sp_aggregate_cart(integer) OWNER TO postgres;
A:
the buy_object_query was selecting things in the wrong order. It selects into the type I created at the beginning of that code buy_object_info. I was selecting the decimal into the integer
| Python DataError coming from stored procedure, but no error when run manually | I am getting this error:
DataError: (DataError) invalid input syntax for integer:
"1.50" CONTEXT: PL/pgSQL function "sp_aggregate_cart" line 82
at FOR over EXECUTE statement
'SELECT total_items, subtotal, is_shipping_required, discount_other,
is_shipping_discount FROM sp_aggregate_cart(8135)' {}
When running my application code. When I run that query manually, everything is fine. I happen to know the 1.50 is in this instance, and it is a value that is passed through a variable in the function that is declared as numeric(10,2). It is NOT returned by the function, just processed.
How can this query throw this error in the application code, but run fine in pgadmin?
Ok, here is the stored procedure. The discount_amount is the 1.50 you see the error on.
CREATE TYPE buy_object_info as (object_id integer, promo_id integer, buy_quantity integer, get_quantity integer, quantity integer, discount_amount numeric(10,2));
-- Function: sp_aggregate_cart(integer)
DROP FUNCTION sp_aggregate_cart(integer);
CREATE OR REPLACE FUNCTION sp_aggregate_cart(p_cart_id integer)
RETURNS SETOF cart AS
$BODY$
DECLARE
v_total_items int;
v_subtotal numeric;
v_discount_other record;
v_items_shipping integer;
v_shipping_required boolean;
buy_object_info buy_object_info%rowtype;
buy_object_price numeric;
buy_object_orginal_subtotal numeric;
other_promo_id integer;
buy_object_query text;
other_promo_buy_quantity integer;
BEGIN
-- Get the total number of items
SELECT sum(quantity) INTO v_total_items FROM cart_object WHERE cart_id = p_cart_id;
-- Get the subtotal
SELECT sum(unit_price) INTO v_subtotal FROM (
SELECT co.cart_id, co.object_id, co.quantity,
CASE
--When buy only cart quantity = buy quantity
WHEN (p.get_quantity = 0 or p.get_quantity IS NULL) AND (p.buy_quantity > 0 OR p.buy_quantity IS NOT NULL) AND pbo.object_id = co.object_id AND p.buy_quantity = co.quantity
THEN ((cast(oa.value AS numeric(10,2)) - COALESCE(pco.discount_amount, 0)) * p.buy_quantity)
--When buy only more than the buy quantity in cart
WHEN (p.get_quantity = 0 or p.get_quantity IS NULL) AND (p.buy_quantity > 0 OR p.buy_quantity IS NOT NULL) AND pbo.object_id = co.object_id AND p.buy_quantity < co.quantity
THEN (((cast(oa.value AS numeric(10,2)) - COALESCE(pco.discount_amount, 0))) * p.buy_quantity) + ((co.quantity - p.buy_quantity) * (cast(oa.value AS numeric(10,2))))
--When buy/get
WHEN (p.get_quantity > 0 or p.get_quantity IS NOT NULL) AND (p.buy_quantity > 0 OR p.buy_quantity IS NOT NULL) AND pgo.object_id = co.object_id
THEN ((cast(oa.value AS numeric(10,2)) - COALESCE(pco.discount_amount, 0)) + ((co.quantity - 1) * cast(oa.value AS numeric(10,2))))
WHEN (p.get_quantity = 0 or p.get_quantity IS NULL) AND (p.buy_quantity = 0 OR p.buy_quantity IS NULL)
THEN ((cast(oa.value AS numeric(10,2)) - COALESCE(pco.discount_amount, 0)) * co.quantity)
ELSE
(cast(oa.value AS numeric(10,2)) * co.quantity)
END AS "unit_price"
FROM cart_object co
JOIN object_attr oa ON oa.object_id=co.object_id AND oa.attr_id=50
LEFT JOIN promo_cart_objects pco ON pco.cart_id=co.cart_id AND pco.object_id=co.object_id
LEFT JOIN promos p ON p.promo_id=pco.promotion_id
LEFT JOIN promo_get_objects pgo ON pgo.object_id = co.object_id AND pgo.promo_id = pco.promotion_id
LEFT JOIN promo_buy_objects pbo ON pbo.object_id = co.object_id AND pbo.promo_id = pco.promotion_id
WHERE co.cart_id=p_cart_id
GROUP BY co.cart_id, co.object_id, oa.value, co.quantity, p.get_quantity, p.buy_quantity, pbo.object_id, pgo.object_id, pco.discount_amount, p.promo_id
) AS a;
--Get the buyobjects that are in the cart and need to have their line item subtotal recalculated
-- :)
buy_object_query :=
'SELECT DISTINCT ON(pbo.object_id)
pbo.object_id, p.promo_id, p.buy_quantity, p.get_quantity, pco.discount_amount, co.quantity
FROM
promo_buy_objects pbo
JOIN
promos p on p.promo_id = pbo.promo_id AND p.active = TRUE AND now() BETWEEN p.start_date AND p.end_date
JOIN
promo_cart_objects pco ON pco.object_id = pbo.object_id
JOIN
cart_object co ON co.cart_id = pco.cart_id AND co.object_id = pbo.object_id
WHERE
pco.cart_id = ' || p_cart_id || '
AND
pbo.object_id IN(SELECT
po.object_id
FROM
promo_objects po
JOIN
promos p on p.promo_id = po.promotion_id AND p.active = TRUE AND now() BETWEEN p.start_date AND p.end_date
JOIN
promo_cart_objects pco ON pco.object_id = po.object_id
WHERE
pco.cart_id = ' || p_cart_id || '
UNION
SELECT
pgo.object_id
FROM
promo_get_objects pgo
JOIN
promos p on p.promo_id = pgo.promo_id AND p.active = TRUE AND now() BETWEEN p.start_date AND p.end_date
JOIN
promo_cart_objects pco ON pco.object_id = pgo.object_id JOIN cart_object co ON co.cart_id = pco.cart_id
WHERE pco.cart_id = ' || p_cart_id || ')
AND
co.quantity > p.buy_quantity';
FOR buy_object_info IN EXECUTE buy_object_query LOOP
--Get the price
SELECT cast("value" as numeric(10,2)) INTO buy_object_price FROM object_attr WHERE object_id = buy_object_info.object_id AND attr_id = 50;
--What was that original price? Redundant I know ...I might get around to optimizing this function
IF (buy_object_info.get_quantity = 0 or buy_object_info.get_quantity IS NULL) AND (buy_object_info.buy_quantity > 0 OR buy_object_info.buy_quantity IS NOT NULL) AND buy_object_info.buy_quantity = buy_object_info.quantity
THEN buy_object_orginal_subtotal := ((buy_object_price - COALESCE(buy_object_info.discount_amount, 0)) * buy_object_info.buy_quantity);
--When buy only more than the buy quantity in cart
ELSIF (buy_object_info.get_quantity = 0 or buy_object_info.get_quantity IS NULL) AND (buy_object_info.buy_quantity > 0 OR buy_object_info.buy_quantity IS NOT NULL) AND buy_object_info.buy_quantity < buy_object_info.quantity
THEN buy_object_orginal_subtotal := (((buy_object_price - COALESCE(buy_object_info.discount_amount, 0))) * buy_object_info.buy_quantity) + ((buy_object_info.quantity - buy_object_info.buy_quantity) * (buy_object_price));
--When buy/get
ELSIF (buy_object_info.get_quantity > 0 or buy_object_info.get_quantity IS NOT NULL) AND (buy_object_info.buy_quantity > 0 OR buy_object_info.buy_quantity IS NOT NULL)
THEN buy_object_orginal_subtotal := ((buy_object_price - COALESCE(buy_object_info.discount_amount, 0)) + ((buy_object_info.quantity - 1) * buy_object_price));
ELSIF (buy_object_info.get_quantity = 0 or buy_object_info.get_quantity IS NULL) AND (buy_object_info.buy_quantity = 0 OR buy_object_info.buy_quantity IS NULL)
THEN buy_object_orginal_subtotal := ((buy_object_price - COALESCE(buy_object_info.discount_amount, 0)) * buy_object_info.quantity);
ELSE
buy_object_orginal_subtotal := (cast(oa.value AS numeric(10,2)) * buy_object_info.quantity);
END IF;
--Well now we need that other promotion...this is so lame
SELECT INTO other_promo_id, other_promo_buy_quantity promo_id, buy_quantity FROM(
SELECT
p.promo_id AS promo_id, p.buy_quantity AS buy_quantity
FROM
promo_objects po
JOIN
promos p on p.promo_id = po.promotion_id AND p.active = TRUE AND now() BETWEEN p.start_date AND p.end_date
JOIN
promo_cart_objects pco ON pco.object_id = po.object_id
WHERE
pco.cart_id = p_cart_id
UNION
SELECT
p.promo_id AS promo_id, p.buy_quantity AS buy_quantity
FROM
promo_get_objects pgo
JOIN
promos p on p.promo_id = pgo.promo_id AND p.active = TRUE AND now() BETWEEN p.start_date AND p.end_date
JOIN
promo_cart_objects pco ON pco.object_id = pgo.object_id JOIN cart_object co ON co.cart_id = pco.cart_id
WHERE pco.cart_id = p_cart_id AND pco.object_id = buy_object_info.object_id) AS foo;
--Alrighty now that we have everything we need, let's perform this funky ass math
v_subtotal := v_subtotal - buy_object_orginal_subtotal;
v_subtotal := v_subtotal + (other_promo_buy_quantity * buy_object_price) + ((buy_object_info.quantity - other_promo_buy_quantity) * (buy_object_price - COALESCE(buy_object_info.discount_amount, 0)));
END LOOP;
--Get Discount Other
--SELECT COALESCE(max(discount_amount), 0), is_shipping_discount INTO v_discount_other FROM cart_promotion WHERE cart_id=p_cart_id;
SELECT COALESCE(discount_amount, 0) as discount, COALESCE(is_shipping_discount, false) as is_shipping_discount INTO v_discount_other
FROM promo_carts WHERE cart_id=p_cart_id order by discount_amount desc limit 1;
-- Determine if shipping is required
SELECT count(*) INTO v_items_shipping
FROM object o, object_attr oa, cart_object co
WHERE oa.object_id = o.object_id AND co.object_id = o.object_id
AND attr_id = 74 and cart_id = p_cart_id AND oa.value = 'true';
IF v_items_shipping > 0 THEN
v_shipping_required := True;
ELSE
v_shipping_required := False;
END IF;
-- Update the cart
UPDATE cart SET
total_items = COALESCE(v_total_items, 0),
subtotal = COALESCE(v_subtotal, 0),
is_shipping_required = v_shipping_required,
discount_other = COALESCE(v_discount_other.discount, 0),
is_shipping_discount = COALESCE(v_discount_other.is_shipping_discount, false)
WHERE id = p_cart_id;
RETURN QUERY SELECT * from cart WHERE id = p_cart_id;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE
COST 100
ROWS 1000;
ALTER FUNCTION sp_aggregate_cart(integer) OWNER TO postgres;
| [
"the buy_object_query was selecting things in the wrong order. It selects into the type I created at the beginning of that code buy_object_info. I was selecting the decimal into the integer\n"
] | [
1
] | [] | [] | [
"plpgsql",
"postgresql",
"python",
"stored_procedures"
] | stackoverflow_0003132893_plpgsql_postgresql_python_stored_procedures.txt |
Q:
Keyword argument in unpacking argument list/dict cases in Python
For python, I could use unpacking arguments as follows.
def hello(x, *y, **z):
print 'x', x
print 'y', y
print 'z', z
hello(1, *[1,2,3], a=1,b=2,c=3)
hello(1, *(1,2,3), **{'a':1,'b':2,'c':3})
x = 1
y = (1, 2, 3)
z = {'a': 1, 'c': 3, 'b': 2}
But, I got an error if I use keyword argument as follows.
hello(x=1, *(1,2,3), **{'a':1,'b':2,'c':3})
TypeError: hello() got multiple values for keyword argument 'x'
Why is this?
A:
Regardless of the order in which they are specified, positional arguments get assigned prior to keyword arguments. In your case, the positional arguments are (1, 2, 3) and the keyword arguments are x=1, a=1, b=2, c=3. Because positional arguments get assigned first, the parameter x receives 1 and is not eligible for keyword arguments any more. This sounds a bit weird because syntactically your positional arguments are specified after the keyword argument, but nonetheless the order “positional arguments → keyword arguments” is always adhered to.
Here is a simpler example:
>>> def f(x): pass
...
>>> f(1, x=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'x'
>>> f(x=2, *(1,))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'x'
| Keyword argument in unpacking argument list/dict cases in Python | For python, I could use unpacking arguments as follows.
def hello(x, *y, **z):
print 'x', x
print 'y', y
print 'z', z
hello(1, *[1,2,3], a=1,b=2,c=3)
hello(1, *(1,2,3), **{'a':1,'b':2,'c':3})
x = 1
y = (1, 2, 3)
z = {'a': 1, 'c': 3, 'b': 2}
But, I got an error if I use keyword argument as follows.
hello(x=1, *(1,2,3), **{'a':1,'b':2,'c':3})
TypeError: hello() got multiple values for keyword argument 'x'
Why is this?
| [
"Regardless of the order in which they are specified, positional arguments get assigned prior to keyword arguments. In your case, the positional arguments are (1, 2, 3) and the keyword arguments are x=1, a=1, b=2, c=3. Because positional arguments get assigned first, the parameter x receives 1 and is not eligible for keyword arguments any more. This sounds a bit weird because syntactically your positional arguments are specified after the keyword argument, but nonetheless the order “positional arguments → keyword arguments” is always adhered to.\nHere is a simpler example:\n>>> def f(x): pass\n... \n>>> f(1, x=2)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: f() got multiple values for keyword argument 'x'\n>>> f(x=2, *(1,))\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: f() got multiple values for keyword argument 'x'\n\n"
] | [
9
] | [] | [] | [
"argument_passing",
"python"
] | stackoverflow_0003141152_argument_passing_python.txt |
Q:
Checking when shutil.copyfile is done
I have a such code:
for file in file_list:
shutil.copyfile(file,newpath)
#do further actions
And here is the question, at #do further actions I use the copied f iles thus I need to make sure the shutil.copyfile functions finish their task. How can I make sure of this ?
A:
The shutil functions should return only after the operation is finished. If nothing funny is going on on the OS level it should be safe this way.
If you know the size of the file you could check if that is correct.
A:
copyfile is a blocking function. By the time you get to #do further actions it should always be done. Are you having issues where it isn't?
| Checking when shutil.copyfile is done | I have a such code:
for file in file_list:
shutil.copyfile(file,newpath)
#do further actions
And here is the question, at #do further actions I use the copied f iles thus I need to make sure the shutil.copyfile functions finish their task. How can I make sure of this ?
| [
"The shutil functions should return only after the operation is finished. If nothing funny is going on on the OS level it should be safe this way.\nIf you know the size of the file you could check if that is correct.\n",
"copyfile is a blocking function. By the time you get to #do further actions it should always be done. Are you having issues where it isn't?\n"
] | [
5,
3
] | [] | [] | [
"file_copying",
"python",
"shutil"
] | stackoverflow_0003141296_file_copying_python_shutil.txt |
Q:
In Eclipse PyDev is there a way to exclude arbitrary file-types from the Pydev Package explorer?
If you click on the icon resembling a downard-pointing triangle in the PyDev Package Explorer and then select "Customize View", The "Available Customizations" pop-down allows the user to select which of a standard set of files are visible in the package explorer.
That's great if you wish to exlude or include certain standard types of file from the view, however I'd like to exclude a type which is currently unknown to PyDev.
In this case, I'd like to exclude "*,cover" - that's any automatically generated coverage report file. PyDev creates these files any time you try to run a coverage analysis but does not seem to have a way of excluding these files from the views. I'd love to hide all the ",cover" files in order to reduce the clutter in my package explorer.
A:
To the left of the down arrow is the "Setup custom filters" button. You can enter custom filters delimited by commas. If that file name indeed has a comma in it, then you will have to enter the filter as *cover since *,cover is treated as two separate filters.
| In Eclipse PyDev is there a way to exclude arbitrary file-types from the Pydev Package explorer? | If you click on the icon resembling a downard-pointing triangle in the PyDev Package Explorer and then select "Customize View", The "Available Customizations" pop-down allows the user to select which of a standard set of files are visible in the package explorer.
That's great if you wish to exlude or include certain standard types of file from the view, however I'd like to exclude a type which is currently unknown to PyDev.
In this case, I'd like to exclude "*,cover" - that's any automatically generated coverage report file. PyDev creates these files any time you try to run a coverage analysis but does not seem to have a way of excluding these files from the views. I'd love to hide all the ",cover" files in order to reduce the clutter in my package explorer.
| [
"To the left of the down arrow is the \"Setup custom filters\" button. You can enter custom filters delimited by commas. If that file name indeed has a comma in it, then you will have to enter the filter as *cover since *,cover is treated as two separate filters.\n"
] | [
7
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0003138677_eclipse_pydev_python.txt |
Q:
associative list python
i am parsing some html form with Beautiful soup. Basically i´ve around 60 input fields mostly radio buttons and checkboxes. So far this works with the following code:
from BeautifulSoup import BeautifulSoup
x = open('myfile.html','r').read()
out = open('outfile.csv','w')
soup = BeautifulSoup(x)
values = soup.findAll('input',checked="checked")
# echoes some output like ('name',1) and ('value',4)
for cell in values:
# the following line is my problem!
statement = cell.attrs[0][1] + ';' + cell.attrs[1][1] + ';\r'
out.write(statement)
out.close()
x.close()
As indicating in the code my problem ist where the attributes are selected, because the HTML template is ugly, mixing up the sequence of arguments that belong to a input field. I am interested in name="somenumber" value="someothernumber" . Unfortunately my attrs[1] approach does not work, since name and value do not occur in the same sequence in my html.
Is there any way to access the resulting BeautifulSoup list associatively?
Thx in advance for any suggestions!
A:
I'm fairly sure you can use the attribute name like a key for a hash:
print cell['name']
A:
My suggestion is to make values a dict. If soup.findAll returns a list of tuples as you seem to imply, then it's as simple as:
values = dict(soup.findAll('input',checked="checked"))
After that you can simply refer to the values by their attribute name, like what Peter said.
Of course, if soup.findAll doesn't return a list of tuples as you've implied, or if your problem is that the tuples themselves are being returned in some weird way (such that instead of ('name', 1) it would be (1, 'name')), then it could be a bit more complicated.
On the other hand, if soup.findAll returns one of a certain set of data types (dict or list of dicts, namedtuple or list of namedtuples), then you'll actually be better off because you won't have to do any conversion in the first place.
...Yeah, after checking the BeautifulSoup documentation, it seems that findAll returns an object that can be treated like a list of dicts, so you can just do as Peter says.
http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20attributes%20of%20Tags
Oh yeah, if you want to enumerate through the attributes, just do something like this:
for cell in values:
for attribute in cell:
out.write(attribute + ';' + str(cell[attribute]) + ';\r')
| associative list python | i am parsing some html form with Beautiful soup. Basically i´ve around 60 input fields mostly radio buttons and checkboxes. So far this works with the following code:
from BeautifulSoup import BeautifulSoup
x = open('myfile.html','r').read()
out = open('outfile.csv','w')
soup = BeautifulSoup(x)
values = soup.findAll('input',checked="checked")
# echoes some output like ('name',1) and ('value',4)
for cell in values:
# the following line is my problem!
statement = cell.attrs[0][1] + ';' + cell.attrs[1][1] + ';\r'
out.write(statement)
out.close()
x.close()
As indicating in the code my problem ist where the attributes are selected, because the HTML template is ugly, mixing up the sequence of arguments that belong to a input field. I am interested in name="somenumber" value="someothernumber" . Unfortunately my attrs[1] approach does not work, since name and value do not occur in the same sequence in my html.
Is there any way to access the resulting BeautifulSoup list associatively?
Thx in advance for any suggestions!
| [
"I'm fairly sure you can use the attribute name like a key for a hash:\nprint cell['name']\n\n",
"My suggestion is to make values a dict. If soup.findAll returns a list of tuples as you seem to imply, then it's as simple as:\nvalues = dict(soup.findAll('input',checked=\"checked\"))\n\nAfter that you can simply refer to the values by their attribute name, like what Peter said.\nOf course, if soup.findAll doesn't return a list of tuples as you've implied, or if your problem is that the tuples themselves are being returned in some weird way (such that instead of ('name', 1) it would be (1, 'name')), then it could be a bit more complicated.\nOn the other hand, if soup.findAll returns one of a certain set of data types (dict or list of dicts, namedtuple or list of namedtuples), then you'll actually be better off because you won't have to do any conversion in the first place.\n...Yeah, after checking the BeautifulSoup documentation, it seems that findAll returns an object that can be treated like a list of dicts, so you can just do as Peter says.\nhttp://www.crummy.com/software/BeautifulSoup/documentation.html#The%20attributes%20of%20Tags\nOh yeah, if you want to enumerate through the attributes, just do something like this:\nfor cell in values:\n for attribute in cell:\n out.write(attribute + ';' + str(cell[attribute]) + ';\\r')\n\n"
] | [
2,
2
] | [] | [] | [
"associative",
"beautifulsoup",
"list",
"python"
] | stackoverflow_0003141530_associative_beautifulsoup_list_python.txt |
Q:
Django one database for each application in the same project
I have a Django project that contains two applications App1 and App2
I have configured two databases DB1 and DB2
when I use python manage.py syncdb the tables corresponding to model of the two application are created in the first database
How can I configure Django to make the model of the first application goes to the first database and the model of the second application goes to the second database
A:
You need to implement Automatic database routing.
| Django one database for each application in the same project | I have a Django project that contains two applications App1 and App2
I have configured two databases DB1 and DB2
when I use python manage.py syncdb the tables corresponding to model of the two application are created in the first database
How can I configure Django to make the model of the first application goes to the first database and the model of the second application goes to the second database
| [
"You need to implement Automatic database routing.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003141785_django_python.txt |
Q:
Increment a Version Number using Regular Expression
I am trying to increment a version number using regex but I can't seem to get the hang of regex at all. I'm having trouple with the symbols in the string I am trying to read and change. The code I have so far is:
version_file = "AssemblyInfo.cs"
read_file = open(version_file).readlines()
write_file = open(version_file, "w")
r = re.compile(r'(AssemblyFileVersion\s*(\s*"\s*)(\S+))\s*"\s*')
for l in read_file:
m1 = r.match(l)
if m1:
VERSION_ID=map(int,m1.group(2).split("."))
VERSION_ID[2]+=1 # increment version
l = r.sub(r'\g<1>' + '.'.join(['%s' % (v) for v in VERSION_ID]), l)
write_file.write(l)
write_file.close()
The string I am trying to read and change is:
[assembly: AssemblyFileVersion("1.0.0.0")]
What I would like written to the file is:
[assembly: AssemblyFileVersion("1.0.0.1")]
So basically I want to increment the build number by one.
Can anyone help me fix my regualr expression. I seem to have trouble getting to grips with regular expression that have to get around symbols.
Thanks for any help.
A:
If you specify the version as "1.0.0.*" then AFAIK it gets updated on each build automagically, at least if you're using Visual Studio.NET.
I'm not sure regex is your best bet, but one way of doing it would be this:
import re
# Don't bother matching everything, just the bits that matter.
pat = re.compile(r'AssemblyFileVersion.*\.(\d+)"')
# ... lines omitted which set up read_file, write_file etc.
for line in read_file:
m = pat.search(line)
if m:
start, end = m.span(1)
line = line[:start] + str(int(line[start:end]) + 1) + line[end:]
write_file.write(line)
A:
Good luck with regex.
If I had to do the same, I'd convert the string to int by removing the dots, add one and convert back to string.
Well, I'd have also used a integer version number in the first place.
| Increment a Version Number using Regular Expression | I am trying to increment a version number using regex but I can't seem to get the hang of regex at all. I'm having trouple with the symbols in the string I am trying to read and change. The code I have so far is:
version_file = "AssemblyInfo.cs"
read_file = open(version_file).readlines()
write_file = open(version_file, "w")
r = re.compile(r'(AssemblyFileVersion\s*(\s*"\s*)(\S+))\s*"\s*')
for l in read_file:
m1 = r.match(l)
if m1:
VERSION_ID=map(int,m1.group(2).split("."))
VERSION_ID[2]+=1 # increment version
l = r.sub(r'\g<1>' + '.'.join(['%s' % (v) for v in VERSION_ID]), l)
write_file.write(l)
write_file.close()
The string I am trying to read and change is:
[assembly: AssemblyFileVersion("1.0.0.0")]
What I would like written to the file is:
[assembly: AssemblyFileVersion("1.0.0.1")]
So basically I want to increment the build number by one.
Can anyone help me fix my regualr expression. I seem to have trouble getting to grips with regular expression that have to get around symbols.
Thanks for any help.
| [
"If you specify the version as \"1.0.0.*\" then AFAIK it gets updated on each build automagically, at least if you're using Visual Studio.NET.\nI'm not sure regex is your best bet, but one way of doing it would be this:\nimport re\n\n# Don't bother matching everything, just the bits that matter.\npat = re.compile(r'AssemblyFileVersion.*\\.(\\d+)\"')\n\n\n# ... lines omitted which set up read_file, write_file etc.\n\nfor line in read_file:\n m = pat.search(line)\n if m:\n start, end = m.span(1)\n line = line[:start] + str(int(line[start:end]) + 1) + line[end:]\n write_file.write(line)\n\n",
"Good luck with regex.\nIf I had to do the same, I'd convert the string to int by removing the dots, add one and convert back to string.\nWell, I'd have also used a integer version number in the first place.\n"
] | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003141642_python_regex.txt |
Q:
In Django, how do I set the default so that every model is created with INNODB?
Right now, Django defaults to MYISAM...but I want to change it so that everytime I create a new table it is innodb.
A:
Put that in settings.py:
DATABASE_ENGINE = 'mysql'
DATABASE_OPTIONS = {"init_command": "SET storage_engine=INNODB"}
UPDATE
For Django >= 1.2 this should be write like this:
DATABASES = {
'default': {
'ENGINE': 'mysql',
'OPTIONS': {'init_command': 'SET storage_engine=INNODB'}
}
}
| In Django, how do I set the default so that every model is created with INNODB? | Right now, Django defaults to MYISAM...but I want to change it so that everytime I create a new table it is innodb.
| [
"Put that in settings.py:\nDATABASE_ENGINE = 'mysql'\nDATABASE_OPTIONS = {\"init_command\": \"SET storage_engine=INNODB\"}\n\nUPDATE\nFor Django >= 1.2 this should be write like this:\nDATABASES = {\n 'default': {\n 'ENGINE': 'mysql',\n 'OPTIONS': {'init_command': 'SET storage_engine=INNODB'}\n }\n }\n\n"
] | [
2
] | [] | [] | [
"database",
"django",
"mysql",
"python"
] | stackoverflow_0003136417_database_django_mysql_python.txt |
Q:
Can python share info like .net remoting?
I known python can use pipe to communicate between two process of py.
But, data and functions of this method are not clear.
I like .net remoting better.
So, can python realize that approach?
A:
Yes, you can do this using (for example) PYRO (Python Remote Objects).
A:
The ability to share "data and functions" is better known as a web service or remote procedure call (RPC). This has the benefit of working between nearly any computer language on any operating system, whereas ".net remoting" will mainly only work on a Windows computer between programs written in a .net technology.
There are many Python libraries supporting various web service and RPC protocols.
http://docs.python.org/library/xmlrpclib.html
http://wiki.python.org/moin/WebServices
| Can python share info like .net remoting? | I known python can use pipe to communicate between two process of py.
But, data and functions of this method are not clear.
I like .net remoting better.
So, can python realize that approach?
| [
"Yes, you can do this using (for example) PYRO (Python Remote Objects).\n",
"The ability to share \"data and functions\" is better known as a web service or remote procedure call (RPC). This has the benefit of working between nearly any computer language on any operating system, whereas \".net remoting\" will mainly only work on a Windows computer between programs written in a .net technology.\nThere are many Python libraries supporting various web service and RPC protocols.\nhttp://docs.python.org/library/xmlrpclib.html\nhttp://wiki.python.org/moin/WebServices\n"
] | [
1,
0
] | [] | [] | [
"communication",
"process",
"python",
"remoting"
] | stackoverflow_0003141844_communication_process_python_remoting.txt |
Q:
Project Euler - Problem 160
For any N, let f(N) be the last five
digits before the trailing zeroes in
N!. For example,
9! = 362880 so f(9)=36288
10! = 3628800 so f(10)=36288
20! = 2432902008176640000 so f(20)=17664
Find f(1,000,000,000,000)
I've successfully tackled this question for the given examples, my function can correctly find f(9), f(10), etc. However it struggles with larger numbers, especially the number the problem asks for - f(10^12).
My current optimizations are as follows: I remove trailing zeros from the multiplier and the sum, and shorten the sum to 5 digits after each multiplication. The code in python is as follows:
def SFTR (n):
sum, a = 1, 2
while a < n+1:
mul = int(re.sub("0+$","",str(a)))
sum *= mul
sum = int(re.sub("0+$","",str(sum))[-5:])
a += 1
return sum
Can anyone tell me why this function is scaling so largely, and why its taking so long. Also, if anyone could hint me in the correct direction to optimize my algorithm. (a name of the general topic will suffice) Thank you.
Update:
I have made some changes for optimization and it is significantly faster, but it is still not fast enough for f(10^12). Can anyone tell me whats making my code slow or how to make it faster?
def SFTR (n):
sum, a = 1, 2
while a < n+1:
mul = a
while(mul % 10 == 0): mul = mul/10
mul = mul % 100000
sum *= mul
while(sum % 10 == 0): sum = sum/10
sum = sum % 100000
a += 1
return sum
A:
mul can get very big. Is that necessary? If I asked you to compute the last 5 non-zero digits of 1278348572934847283948561278387487189900038 * 38758
by hand, exactly how many digits of the first number do you actually need to know?
A:
Building strings frequently is expensive. I'd rather use the modulo operator when truncating to the last five digits.
python -m timeit 'x = str(111111111111111111111111111111111)[-5:]'
1000000 loops, best of 3: 1.09 usec per loop
python -m timeit 'x = 111111111111111111111111111111111 % 100000'
1000000 loops, best of 3: 0.277 usec per loop
The same applies to stripping the trailing zeros. There should be a more efficient way to do this, and you probably don't have to do it in every single step.
I didn't check your algorithm for correctness, though, it's just a hint for optimization.
A:
In fact, you might even note that there are only a restricted set of possible trailing non-zero digits. If I recall correctly, there are only a few thousand possible trailing non-zero digit combinations, when you look only at the last 5 digits. For example, is it possible for the final non-zero digit ever to be odd? (Ignore the special cases of 0! and 1! here.)
| Project Euler - Problem 160 |
For any N, let f(N) be the last five
digits before the trailing zeroes in
N!. For example,
9! = 362880 so f(9)=36288
10! = 3628800 so f(10)=36288
20! = 2432902008176640000 so f(20)=17664
Find f(1,000,000,000,000)
I've successfully tackled this question for the given examples, my function can correctly find f(9), f(10), etc. However it struggles with larger numbers, especially the number the problem asks for - f(10^12).
My current optimizations are as follows: I remove trailing zeros from the multiplier and the sum, and shorten the sum to 5 digits after each multiplication. The code in python is as follows:
def SFTR (n):
sum, a = 1, 2
while a < n+1:
mul = int(re.sub("0+$","",str(a)))
sum *= mul
sum = int(re.sub("0+$","",str(sum))[-5:])
a += 1
return sum
Can anyone tell me why this function is scaling so largely, and why its taking so long. Also, if anyone could hint me in the correct direction to optimize my algorithm. (a name of the general topic will suffice) Thank you.
Update:
I have made some changes for optimization and it is significantly faster, but it is still not fast enough for f(10^12). Can anyone tell me whats making my code slow or how to make it faster?
def SFTR (n):
sum, a = 1, 2
while a < n+1:
mul = a
while(mul % 10 == 0): mul = mul/10
mul = mul % 100000
sum *= mul
while(sum % 10 == 0): sum = sum/10
sum = sum % 100000
a += 1
return sum
| [
"mul can get very big. Is that necessary? If I asked you to compute the last 5 non-zero digits of 1278348572934847283948561278387487189900038 * 38758\nby hand, exactly how many digits of the first number do you actually need to know?\n",
"Building strings frequently is expensive. I'd rather use the modulo operator when truncating to the last five digits.\npython -m timeit 'x = str(111111111111111111111111111111111)[-5:]'\n1000000 loops, best of 3: 1.09 usec per loop\npython -m timeit 'x = 111111111111111111111111111111111 % 100000'\n1000000 loops, best of 3: 0.277 usec per loop\n\nThe same applies to stripping the trailing zeros. There should be a more efficient way to do this, and you probably don't have to do it in every single step.\nI didn't check your algorithm for correctness, though, it's just a hint for optimization.\n",
"In fact, you might even note that there are only a restricted set of possible trailing non-zero digits. If I recall correctly, there are only a few thousand possible trailing non-zero digit combinations, when you look only at the last 5 digits. For example, is it possible for the final non-zero digit ever to be odd? (Ignore the special cases of 0! and 1! here.)\n"
] | [
7,
2,
1
] | [] | [] | [
"math",
"optimization",
"python"
] | stackoverflow_0003140533_math_optimization_python.txt |
Q:
Passing variables/functions between imported modules
I'm going to throw out some pseudocode. Then explain what I want, because I am not sure how to otherwise.
File_A
class Panel_A(wx.Panel)
def __init__(self):
button_a = wx.Button(parent=self)
def onButton(self, event):
pass to list view
File_B
class Panel_B(wx.panel):
def __init__(self):
listview_a = wx.ListView(parent=self)
File_C
import File_A
import File_B
panel_a = Panel_A()
panel_b = Panel_B()
OK, I have a panel in one module, that searches a database when I push button_a. The second module has a listview in it. Both modules are imported into a third module. I need to be able to pass the information from the search to listview_a in another module. I am not sure how to do this, since all the objects are declared in File_C but I need to use them in File_A.
A:
Use the delegate design pattern:
(Pass in panel_b as an argument when instantiating Panel_A objects):
# File_A
class Panel_A(wx.Panel)
def __init__(self,panel_b):
self.panel_b=panel_b
button_a = wx.Button(parent=self)
def onButton(self, event):
pass to self.panel_b.listview_a
# File_B
class Panel_B(wx.panel):
def __init__(self):
listview_a = wx.ListView(parent=self)
# File_C
import File_A
import File_B
panel_b = Panel_B()
panel_a = Panel_A(panel_b)
You may want to pass in just the ListView, instead of the whole panel. I don't know enough about your situation to know what one would be best.
A:
You can use a simplified version of the Observer pattern: the Panel_A class has a listener field with a fillView method that gets the list, the Panel_B implements such a method.
After the construction of both Panel_A and Panel_B, just assign to the Panel_A object's field
and call self.listener.fillView(list) from inside the onButton method
| Passing variables/functions between imported modules | I'm going to throw out some pseudocode. Then explain what I want, because I am not sure how to otherwise.
File_A
class Panel_A(wx.Panel)
def __init__(self):
button_a = wx.Button(parent=self)
def onButton(self, event):
pass to list view
File_B
class Panel_B(wx.panel):
def __init__(self):
listview_a = wx.ListView(parent=self)
File_C
import File_A
import File_B
panel_a = Panel_A()
panel_b = Panel_B()
OK, I have a panel in one module, that searches a database when I push button_a. The second module has a listview in it. Both modules are imported into a third module. I need to be able to pass the information from the search to listview_a in another module. I am not sure how to do this, since all the objects are declared in File_C but I need to use them in File_A.
| [
"Use the delegate design pattern:\n(Pass in panel_b as an argument when instantiating Panel_A objects):\n# File_A\nclass Panel_A(wx.Panel)\n def __init__(self,panel_b):\n self.panel_b=panel_b\n button_a = wx.Button(parent=self)\n\n def onButton(self, event):\n pass to self.panel_b.listview_a\n\n# File_B\nclass Panel_B(wx.panel):\n def __init__(self):\n listview_a = wx.ListView(parent=self)\n\n# File_C\nimport File_A\nimport File_B\n\npanel_b = Panel_B()\npanel_a = Panel_A(panel_b)\n\nYou may want to pass in just the ListView, instead of the whole panel. I don't know enough about your situation to know what one would be best.\n",
"You can use a simplified version of the Observer pattern: the Panel_A class has a listener field with a fillView method that gets the list, the Panel_B implements such a method.\nAfter the construction of both Panel_A and Panel_B, just assign to the Panel_A object's field\nand call self.listener.fillView(list) from inside the onButton method\n"
] | [
1,
0
] | [] | [] | [
"import",
"module",
"python",
"wxpython"
] | stackoverflow_0003142031_import_module_python_wxpython.txt |
Q:
Optimising memory usage in numpy
The following program loads two images with PyGame, converts them to Numpy arrays, and then performs some other Numpy operations (such as FFT) to emit a final result (of a few numbers). The inputs can be large, but at any moment only one or two large objects should be live.
A test image is about 10M pixels, which translates to 10MB once it's greyscaled. It gets converted to a Numpy array of dtype uint8, which after some processing (applying Hamming windows), is an array of dtype float64. Two images are loaded into arrays this way; later FFT steps result in an array of dtype complex128. Prior to adding the excessive gc.collect calls, the program memory size tended to increase with each step. Additionally, it seems most Numpy operations will give a result in the highest precision available.
Running the test (sans the gc.collect calls) on my 1GB Linux machine results in prolonged thrashing, which I have not waited for. I don't yet have detailed memory use stats -- I tried some Python modules and the time command to no avail; now I'm looking into valgrind. Watching PS (and dealing with machine unresponsiveness in the later stages of the test) suggests a maximum memory usage of about 800 MB.
A 10 million cell array of complex128 should occupy 160 MB. Having (ideally) at most two of these live at one time, plus the not-insubstantial Python and Numpy libraries and other paraphernalia, probably means allowing for 500 MB.
I can think of two angles from which to attack the problem:
Discarding intermediate arrays as soon as possible. That's what the gc.collect calls are for -- they seem to have improved the situation, as it now completes with only a few minutes of thrashing ;-). I think one can expect that memory-intensive programming in a language like Python will require some manual intervention.
Using less-precise Numpy arrays at each step. Unfortunately the operations that return arrays, like fft2, do not appear to allow the type to be specified.
So my main question is: is there a way of specifying output precision in Numpy array operations?
More generally, are there other common memory-conserving techniques when using Numpy?
Additionally, does Numpy have a more idiomatic way of freeing array memory? (I imagine this would leave the array object live in Python, but in an unusable state.) Explicit deletion followed by immediate GC feels hacky.
import sys
import numpy
import pygame
import gc
def get_image_data(filename):
im = pygame.image.load(filename)
im2 = im.convert(8)
a = pygame.surfarray.array2d(im2)
hw1 = numpy.hamming(a.shape[0])
hw2 = numpy.hamming(a.shape[1])
a = a.transpose()
a = a*hw1
a = a.transpose()
a = a*hw2
return a
def check():
gc.collect()
print 'check'
def main(args):
pygame.init()
pygame.sndarray.use_arraytype('numpy')
filename1 = args[1]
filename2 = args[2]
im1 = get_image_data(filename1)
im2 = get_image_data(filename2)
check()
out1 = numpy.fft.fft2(im1)
del im1
check()
out2 = numpy.fft.fft2(im2)
del im2
check()
out3 = out1.conjugate() * out2
del out1, out2
check()
correl = numpy.fft.ifft2(out3)
del out3
check()
maxs = correl.argmax()
maxpt = maxs % correl.shape[0], maxs / correl.shape[0]
print correl[maxpt], maxpt, (correl.shape[0] - maxpt[0], correl.shape[1] - maxpt[1])
if __name__ == '__main__':
args = sys.argv
exit(main(args))
A:
if I understand correctly, you are calculating a convolution between two images. The Scipy package contains a dedicated module for that (ndimage), which might be more memory efficient than the "manual" approach via Fourier transforms. It would be good to try using it instead of going through Numpy.
A:
This
on SO says "Scipy 0.8 will have single precision support for almost all the fft code",
and SciPy 0.8.0 beta 1 is just out.
(Haven't tried it myself, cowardly.)
| Optimising memory usage in numpy | The following program loads two images with PyGame, converts them to Numpy arrays, and then performs some other Numpy operations (such as FFT) to emit a final result (of a few numbers). The inputs can be large, but at any moment only one or two large objects should be live.
A test image is about 10M pixels, which translates to 10MB once it's greyscaled. It gets converted to a Numpy array of dtype uint8, which after some processing (applying Hamming windows), is an array of dtype float64. Two images are loaded into arrays this way; later FFT steps result in an array of dtype complex128. Prior to adding the excessive gc.collect calls, the program memory size tended to increase with each step. Additionally, it seems most Numpy operations will give a result in the highest precision available.
Running the test (sans the gc.collect calls) on my 1GB Linux machine results in prolonged thrashing, which I have not waited for. I don't yet have detailed memory use stats -- I tried some Python modules and the time command to no avail; now I'm looking into valgrind. Watching PS (and dealing with machine unresponsiveness in the later stages of the test) suggests a maximum memory usage of about 800 MB.
A 10 million cell array of complex128 should occupy 160 MB. Having (ideally) at most two of these live at one time, plus the not-insubstantial Python and Numpy libraries and other paraphernalia, probably means allowing for 500 MB.
I can think of two angles from which to attack the problem:
Discarding intermediate arrays as soon as possible. That's what the gc.collect calls are for -- they seem to have improved the situation, as it now completes with only a few minutes of thrashing ;-). I think one can expect that memory-intensive programming in a language like Python will require some manual intervention.
Using less-precise Numpy arrays at each step. Unfortunately the operations that return arrays, like fft2, do not appear to allow the type to be specified.
So my main question is: is there a way of specifying output precision in Numpy array operations?
More generally, are there other common memory-conserving techniques when using Numpy?
Additionally, does Numpy have a more idiomatic way of freeing array memory? (I imagine this would leave the array object live in Python, but in an unusable state.) Explicit deletion followed by immediate GC feels hacky.
import sys
import numpy
import pygame
import gc
def get_image_data(filename):
im = pygame.image.load(filename)
im2 = im.convert(8)
a = pygame.surfarray.array2d(im2)
hw1 = numpy.hamming(a.shape[0])
hw2 = numpy.hamming(a.shape[1])
a = a.transpose()
a = a*hw1
a = a.transpose()
a = a*hw2
return a
def check():
gc.collect()
print 'check'
def main(args):
pygame.init()
pygame.sndarray.use_arraytype('numpy')
filename1 = args[1]
filename2 = args[2]
im1 = get_image_data(filename1)
im2 = get_image_data(filename2)
check()
out1 = numpy.fft.fft2(im1)
del im1
check()
out2 = numpy.fft.fft2(im2)
del im2
check()
out3 = out1.conjugate() * out2
del out1, out2
check()
correl = numpy.fft.ifft2(out3)
del out3
check()
maxs = correl.argmax()
maxpt = maxs % correl.shape[0], maxs / correl.shape[0]
print correl[maxpt], maxpt, (correl.shape[0] - maxpt[0], correl.shape[1] - maxpt[1])
if __name__ == '__main__':
args = sys.argv
exit(main(args))
| [
"if I understand correctly, you are calculating a convolution between two images. The Scipy package contains a dedicated module for that (ndimage), which might be more memory efficient than the \"manual\" approach via Fourier transforms. It would be good to try using it instead of going through Numpy.\n",
"This\non SO says \"Scipy 0.8 will have single precision support for almost all the fft code\",\nand SciPy 0.8.0 beta 1 is just out.\n(Haven't tried it myself, cowardly.)\n"
] | [
1,
1
] | [] | [] | [
"memory_management",
"numpy",
"pygame",
"python"
] | stackoverflow_0003138669_memory_management_numpy_pygame_python.txt |
Q:
Python base64.decode does not seem to work on windows
I am consuming a webservice (written in java) - that basically returns a byte[] array (the SOAP equivalent is base64 encoded binary data).
I am using the python suds library and the following code works for me on my mac (and on cygwin under windows), but the decoding does not work on vanilla windows (python 2.6.5). I am primarily a java developer so any help will be really helpful.
from suds.client import Client
import base64,os,shutil,tarfile,StringIO
u = "user"
p = "password"
url = "https://xxxx/?wsdl"
client = Client(url, username=u, password=p)
bin = client.service.getTargz("test")
f = open("tools.tar.gz", "w")
f.write(base64.b64decode(bin.encode('ASCII')))
f.close()
print "finished writing"
tarfile.open("tools.tar.gz").extractall()
Works great on a mac - but on windows gives me this error:
C:\client>python client.py
xml
Getting the sysprep file from the webservice
finished writing
Traceback (most recent call last):
File "client.py", line 28, in
tarfile.open("tools.tar.gz").extractall()
File "C:\Python26\lib\tarfile.py", line 1653, in open
return func(name, "r", fileobj, **kwargs)
File "C:\Python26\lib\tarfile.py", line 1720, in gzopen
**kwargs)
File "C:\Python26\lib\tarfile.py", line 1698, in taropen
return cls(name, mode, fileobj, **kwargs)
File "C:\Python26\lib\tarfile.py", line 1571, in __init__
self.firstmember = self.next()
File "C:\Python26\lib\tarfile.py", line 2317, in next
tarinfo = self.tarinfo.fromtarfile(self)
File "C:\Python26\lib\tarfile.py", line 1235, in fromtarfile
buf = tarfile.fileobj.read(BLOCKSIZE)
File "C:\Python26\lib\gzip.py", line 219, in read
self._read(readsize)
File "C:\Python26\lib\gzip.py", line 271, in _read
uncompress = self.decompress.decompress(buf)
zlib.error: Error -3 while decompressing: invalid distance too far back
A:
Try
f = open("tools.tar.gz", "wb")
It's crucial to tell Python that it's a binary file (in Py3, it also becomes crucial on Unixy systems, but in Py2 it's not strictly needed on them, which is why your code works on MacOSX): the default is text, which, on Windows, translates each \n written into \r\n on disk upon writing.
| Python base64.decode does not seem to work on windows | I am consuming a webservice (written in java) - that basically returns a byte[] array (the SOAP equivalent is base64 encoded binary data).
I am using the python suds library and the following code works for me on my mac (and on cygwin under windows), but the decoding does not work on vanilla windows (python 2.6.5). I am primarily a java developer so any help will be really helpful.
from suds.client import Client
import base64,os,shutil,tarfile,StringIO
u = "user"
p = "password"
url = "https://xxxx/?wsdl"
client = Client(url, username=u, password=p)
bin = client.service.getTargz("test")
f = open("tools.tar.gz", "w")
f.write(base64.b64decode(bin.encode('ASCII')))
f.close()
print "finished writing"
tarfile.open("tools.tar.gz").extractall()
Works great on a mac - but on windows gives me this error:
C:\client>python client.py
xml
Getting the sysprep file from the webservice
finished writing
Traceback (most recent call last):
File "client.py", line 28, in
tarfile.open("tools.tar.gz").extractall()
File "C:\Python26\lib\tarfile.py", line 1653, in open
return func(name, "r", fileobj, **kwargs)
File "C:\Python26\lib\tarfile.py", line 1720, in gzopen
**kwargs)
File "C:\Python26\lib\tarfile.py", line 1698, in taropen
return cls(name, mode, fileobj, **kwargs)
File "C:\Python26\lib\tarfile.py", line 1571, in __init__
self.firstmember = self.next()
File "C:\Python26\lib\tarfile.py", line 2317, in next
tarinfo = self.tarinfo.fromtarfile(self)
File "C:\Python26\lib\tarfile.py", line 1235, in fromtarfile
buf = tarfile.fileobj.read(BLOCKSIZE)
File "C:\Python26\lib\gzip.py", line 219, in read
self._read(readsize)
File "C:\Python26\lib\gzip.py", line 271, in _read
uncompress = self.decompress.decompress(buf)
zlib.error: Error -3 while decompressing: invalid distance too far back
| [
"Try\nf = open(\"tools.tar.gz\", \"wb\")\n\nIt's crucial to tell Python that it's a binary file (in Py3, it also becomes crucial on Unixy systems, but in Py2 it's not strictly needed on them, which is why your code works on MacOSX): the default is text, which, on Windows, translates each \\n written into \\r\\n on disk upon writing.\n"
] | [
7
] | [] | [] | [
"encoding",
"python"
] | stackoverflow_0003142107_encoding_python.txt |
Q:
Python Syntax Problem
I'm just getting back into Project Euler and have lost my account and solutions, so I'm back on problem 7. However, my code doesn't work. It seems fairly elementary to me, can someone help me debug my (short) script?
Should find the 10001st Prime.
#!/usr/bin/env python
#encoding: utf-8
"""
P7.py
Created by Andrew Levenson on 2010-06-29.
Copyright (c) 2010 __ME__. All rights reserved.
"""
import sys
import os
from math import sqrt
def isPrime(num):
flag = True
for x in range(2,int(sqrt(num))):
if( num % x == 0 ):
flag = False
if flag == True:
return True
else:
return False
def main():
i, n = 1, 3
p = False
end = 6
while end - i >= 0:
p = isPrime(n)
if p == True:
i = i + 1
print n
n = n + 1
if __name__ == '__main__':
main()
Edit*: Sorry, the issue is it says every number is prime. :/
A:
The syntax is fine (in Python 2). The semantics has some avoidable complications, and this off-by-one bug:
for x in range(2,int(sqrt(num))):
if( num % x == 0 ):
flag = False
range(2, Y) goes from 2 included to Y excluded -- so you're often not checking the last possible divisor and thereby deeming "primes" many numbers that aren't. As the simplest fix, try a 1 + int(... in that range. After which, removing those avoidable complications is advisable: for example,
if somebool: return True
else: return False
is never warranted, as the simpler return somebool does the same job.
A simplified version of your entire code (with just indispensable optimizations, but otherwise exactly the same algorithm) might be, for example:
from math import sqrt
def isPrime(num):
for x in range(3, int(1 + sqrt(num)), 2):
if num % x == 0: return False
return True
def main():
i, n = 0, 3
end = 6
while i < end:
if isPrime(n):
i += 1
print n
n += 2
if __name__ == '__main__':
main()
"Return as soon as you know the answer" was already explained, I've added one more crucial optimization (+= 2, instead of 1, for n, as we "know" even numbers > 3 are not primes, and a tweak of the range for the same reason).
It's possible to get cuter, e.g.:
def isPrime(num):
return all(num % x for x n range(3, int(1 + sqrt(num)), 2))
though this may not look "simpler" if you're unfamiliar with the all built-in, it really is, because it saves you having to do (and readers of the code having to follow) low level logic, in favor of an appropriate level of abstraction to express the function's key idea, that is, "num is prime iff all possible odd divisors have a [[non-0]] remainder when the division is tried" (i.e., express the concept directly in precise, executable form). The algorithm within is actually still identical.
Going further...:
import itertools as it
def odd():
for n in it.count(1):
yield n + n + 1
def main():
end = 5
for i, n in enumerate(it.ifilter(isPrime, odd())):
print n
if i >= end: break
Again, this is just the same algorithm as before, just expressed at a more appropriate level of abstraction: the generation of the sequence of odd numbers (from 3 included upwards) placed into its own odd generator, and some use of the enumerate built-in and itertools functionality to avoid inappropriate (and unneeded) low-level expression / reasoning.
I repeat: no fundamental optimization applied yet -- just suitable abstraction. Optimization of unbounded successive primes generation in Python (e.g. via an open-ended Eratosthenes Sieve approach) has been discussed in depth elsewhere, e.g. here (be sure to check the comments too!). Here I was focusing on showing how (with built-ins such as enumerate, all, and any, the crucial itertools, plus generators and generator expressions) many "looping" problems can be expressed in modern Python at more appropriate levels of abstraction than the "C-inspired" ones that may appear most natural to most programmers reared on C programming and the like. (Perhaps surprisingly to scholars used to C++'s "abstraction penalty" first identified by Stepanov, Python usually tends to have an "abstraction premium" instead, especially if itertools, well known for its blazing speed, is used extensively and appropriately... but, that's really a different subject;-).
A:
Isn't this better?
def isPrime(num):
for x in range(2,int(sqrt(num))):
if( num % x == 0 ):
return False
return True
And this:
def main():
i, n = 1, 3
while i <= 6:
if isPrime(n):
i = i + 1
print n
n = n + 1
Also, I'm not seeing a 10001 anywhere in there...
| Python Syntax Problem | I'm just getting back into Project Euler and have lost my account and solutions, so I'm back on problem 7. However, my code doesn't work. It seems fairly elementary to me, can someone help me debug my (short) script?
Should find the 10001st Prime.
#!/usr/bin/env python
#encoding: utf-8
"""
P7.py
Created by Andrew Levenson on 2010-06-29.
Copyright (c) 2010 __ME__. All rights reserved.
"""
import sys
import os
from math import sqrt
def isPrime(num):
flag = True
for x in range(2,int(sqrt(num))):
if( num % x == 0 ):
flag = False
if flag == True:
return True
else:
return False
def main():
i, n = 1, 3
p = False
end = 6
while end - i >= 0:
p = isPrime(n)
if p == True:
i = i + 1
print n
n = n + 1
if __name__ == '__main__':
main()
Edit*: Sorry, the issue is it says every number is prime. :/
| [
"The syntax is fine (in Python 2). The semantics has some avoidable complications, and this off-by-one bug:\nfor x in range(2,int(sqrt(num))):\n if( num % x == 0 ):\n flag = False\n\nrange(2, Y) goes from 2 included to Y excluded -- so you're often not checking the last possible divisor and thereby deeming \"primes\" many numbers that aren't. As the simplest fix, try a 1 + int(... in that range. After which, removing those avoidable complications is advisable: for example,\nif somebool: return True\nelse: return False\n\nis never warranted, as the simpler return somebool does the same job.\nA simplified version of your entire code (with just indispensable optimizations, but otherwise exactly the same algorithm) might be, for example:\nfrom math import sqrt\n\ndef isPrime(num):\n for x in range(3, int(1 + sqrt(num)), 2):\n if num % x == 0: return False\n return True\n\ndef main():\n i, n = 0, 3\n end = 6\n while i < end:\n if isPrime(n):\n i += 1\n print n\n n += 2\n\nif __name__ == '__main__':\n main()\n\n\"Return as soon as you know the answer\" was already explained, I've added one more crucial optimization (+= 2, instead of 1, for n, as we \"know\" even numbers > 3 are not primes, and a tweak of the range for the same reason).\nIt's possible to get cuter, e.g.:\ndef isPrime(num):\n return all(num % x for x n range(3, int(1 + sqrt(num)), 2))\n\nthough this may not look \"simpler\" if you're unfamiliar with the all built-in, it really is, because it saves you having to do (and readers of the code having to follow) low level logic, in favor of an appropriate level of abstraction to express the function's key idea, that is, \"num is prime iff all possible odd divisors have a [[non-0]] remainder when the division is tried\" (i.e., express the concept directly in precise, executable form). The algorithm within is actually still identical.\nGoing further...:\nimport itertools as it\n\ndef odd():\n for n in it.count(1):\n yield n + n + 1\n\ndef main():\n end = 5 \n for i, n in enumerate(it.ifilter(isPrime, odd())):\n print n\n if i >= end: break\n\nAgain, this is just the same algorithm as before, just expressed at a more appropriate level of abstraction: the generation of the sequence of odd numbers (from 3 included upwards) placed into its own odd generator, and some use of the enumerate built-in and itertools functionality to avoid inappropriate (and unneeded) low-level expression / reasoning.\nI repeat: no fundamental optimization applied yet -- just suitable abstraction. Optimization of unbounded successive primes generation in Python (e.g. via an open-ended Eratosthenes Sieve approach) has been discussed in depth elsewhere, e.g. here (be sure to check the comments too!). Here I was focusing on showing how (with built-ins such as enumerate, all, and any, the crucial itertools, plus generators and generator expressions) many \"looping\" problems can be expressed in modern Python at more appropriate levels of abstraction than the \"C-inspired\" ones that may appear most natural to most programmers reared on C programming and the like. (Perhaps surprisingly to scholars used to C++'s \"abstraction penalty\" first identified by Stepanov, Python usually tends to have an \"abstraction premium\" instead, especially if itertools, well known for its blazing speed, is used extensively and appropriately... but, that's really a different subject;-).\n",
"Isn't this better?\ndef isPrime(num):\n for x in range(2,int(sqrt(num))):\n if( num % x == 0 ):\n return False\n return True\n\nAnd this:\ndef main():\n i, n = 1, 3\n while i <= 6:\n if isPrime(n):\n i = i + 1\n print n\n n = n + 1\n\nAlso, I'm not seeing a 10001 anywhere in there...\n"
] | [
5,
1
] | [] | [] | [
"primes",
"python"
] | stackoverflow_0003142318_primes_python.txt |
Q:
ZeroConf Chat with Python
I am trying to set up a Bonjour (or Ahavi) chatbot for our helpdesk system that would answer basic questions based on a menu system. The basis of my question is how do I get python to create the bot so that it connects to the network as a chat client.
Basically, anyone on my network with iChat or Empathy (or any chat program able to view users over the local network) should see the bot just as they see another user. The actual bot part would be quite simple to program, but I have no idea how to get it on the network.
I have looked into ZeroConf, but I'm not exactly sure how it works, or how to get a chat service running with python. I have seen references to pybonjour, python bindings for avahi, and pyzeroconf, but again, I have no idea how to set them up.
If anyone could give an example, or reference, or even a good article to read on the subject, it would be much appreciated. Thanks!
Kory
A:
What you have here is a disconnect between what you want to do and how to do it. Zeroconf/Avahi are about service discovery. What you describe is a chat bot. Chat bots connect to an existing chat server. Apple with iChat has slightly blurred these lines.
iChat (and presumably other chat clients that implement the protocol) uses Bonjour to provide a means of avoiding outside server connections.
Essentially what you would need to do is to implement a chat server that also utilizes Bonjour. The Bonjour part advertises the service, and the chat portion handles the actual communication. You would likely want to use python libraries for telepathy such as python-telepathy or python-empathy [Telepathy][1]. iChat seems to speak AIM, so that would be the protocol to look into. IIRC it also supports XMPP so so the XMPP python libraries might be an option.
I'd look at using [bonjour-py][2] to advertise the service. It might be a bit tricky, but does sound interesting. The bonjour-py page has numerous other terms you can search on if it doesn't meet your needs.
[1]: http://telepathy.freedesktop.org/wiki/ Telepathy Home
[2]: http://www.mcs.anl.gov/research/projects/accessgrid/bonjour-py/ bonjour-py
A:
The easiest thing to do is to use Telepathy Salut or Pidgin/libpurple, and talk with it over D-Bus.
| ZeroConf Chat with Python | I am trying to set up a Bonjour (or Ahavi) chatbot for our helpdesk system that would answer basic questions based on a menu system. The basis of my question is how do I get python to create the bot so that it connects to the network as a chat client.
Basically, anyone on my network with iChat or Empathy (or any chat program able to view users over the local network) should see the bot just as they see another user. The actual bot part would be quite simple to program, but I have no idea how to get it on the network.
I have looked into ZeroConf, but I'm not exactly sure how it works, or how to get a chat service running with python. I have seen references to pybonjour, python bindings for avahi, and pyzeroconf, but again, I have no idea how to set them up.
If anyone could give an example, or reference, or even a good article to read on the subject, it would be much appreciated. Thanks!
Kory
| [
"What you have here is a disconnect between what you want to do and how to do it. Zeroconf/Avahi are about service discovery. What you describe is a chat bot. Chat bots connect to an existing chat server. Apple with iChat has slightly blurred these lines.\niChat (and presumably other chat clients that implement the protocol) uses Bonjour to provide a means of avoiding outside server connections. \nEssentially what you would need to do is to implement a chat server that also utilizes Bonjour. The Bonjour part advertises the service, and the chat portion handles the actual communication. You would likely want to use python libraries for telepathy such as python-telepathy or python-empathy [Telepathy][1]. iChat seems to speak AIM, so that would be the protocol to look into. IIRC it also supports XMPP so so the XMPP python libraries might be an option. \nI'd look at using [bonjour-py][2] to advertise the service. It might be a bit tricky, but does sound interesting. The bonjour-py page has numerous other terms you can search on if it doesn't meet your needs.\n[1]: http://telepathy.freedesktop.org/wiki/ Telepathy Home\n[2]: http://www.mcs.anl.gov/research/projects/accessgrid/bonjour-py/ bonjour-py\n",
"The easiest thing to do is to use Telepathy Salut or Pidgin/libpurple, and talk with it over D-Bus.\n"
] | [
1,
0
] | [] | [] | [
"bonjour",
"chatbot",
"linux",
"python",
"zeroconf"
] | stackoverflow_0003072934_bonjour_chatbot_linux_python_zeroconf.txt |
Q:
Lookahead assertions seem to short-circuit ordering of alternates in regular expressions
I'm working with a (Python-flavored) regular expression to recognize common and idiosyncratic forms and abbreviations of scripture references. Given the following verbose snippet:
>>> cp = re.compile(ur"""
(?:(
# Numbered books
(?:(?:Third|Thir|Thi|III|3rd|Th|3)\ ?
(?:John|Joh|Jhn|Jo|Jn|Jn|J))
# Other books
|Thessalonians|John|Th|Jn)\ ?
# Lookahead for numbers or punctuation
(?=[\d:., ]))
|
# Do the same check, this time at the end of the string.
(
(?:(?:Third|Thir|Thi|III|3rd|Th|3)\ ?
(?:John|Joh|Jhn|Jo|Jn|Jn|J))
|Thessalonians|John|Th|Jn)\.?$
""", re.IGNORECASE | re.VERBOSE)
>>> cp.match("Third John").group()
'Third John'
>>> cp.match("Th Jn").group()
'Th'
>>> cp.match("Th Jn ").group()
'Th Jn'
The intention of this snippet is to match various forms of "Third John", as well as forms of "Thessalonians" and "John" by themselves. In most cases this works fine, but it does not match "Th Jn" (or "Th John"), rather matching "Th" by itself.
I've ordered the appearance of each abbreviation in the expression from longest to shortest expressly to avoid a situation like this, relying on a regular expression's typically greedy behavior. But the positive lookahead assertion seems to be short-circuiting this order, picking the shortest match instead of the greediest match.
Of course, removing the lookahead assertion makes this case work, but breaks a bunch of other tests. How might I go about fixing this?
A:
I've given up after a little try to follow what _sre.so is doing in this case (too complicated!) but a "blind fix" I tried seemed to work -- switch to a negative lookahead assertion for the complementary character set...:
cp = re.compile(ur"""
(?:(
# Numbered books
(?:(?:Third|Thir|Thi|III|3rd|Th|3)\ ?
(?:John|Joh|Jhn|Jo|Jn|Jn|J))
# Other books
|Thessalonians|John|Th|Jn)\ ?
# Lookahead for numbers or punctuation
(?![^\d:., ]))
|
etc. I.e. I changed the original (?=[\d:., ])) positive lookahead into a "double negation" form (negative lookahead for complement) (?![^\d:., ])) and this seems to remove the perturbation. Does this work correctly for you?
I think it's an implementation anomaly in this corner case of _sre.so -- it might be interesting to see what other RE engines do in these two cases, just as a sanity check.
A:
The lookahead isn't really short circuiting anything. The regex is only greedy up to a point. It'll prefer a match in your first big block because it doesn't want to cross that "|" boundary to the second part of the regex and have to check that as well.
Since the whole string doesn't match the first big block (because the lookeahead says it needs to be followed by a particular character rather than end of line) it just matches the "Th" from the "Thessalonians" group and the lookahead sees a space following "Th" in "Th Jn" so it considers this a valid match.
What you'll probably want to do is move the "|Thessalonians|John|Th|Jn)\ ? " group out to another large "|" block. Check your two word books at the beginning of text OR at the end of text OR check for one word books in a third group.
Hope this explanation made sense.
A:
Another alternate solution I discovered while asking the question: switch the order of the blocks, putting the end-of-line check first, then the lookahead assertion last. However, I prefer Alex's double negative solution, and have implemented that.
| Lookahead assertions seem to short-circuit ordering of alternates in regular expressions | I'm working with a (Python-flavored) regular expression to recognize common and idiosyncratic forms and abbreviations of scripture references. Given the following verbose snippet:
>>> cp = re.compile(ur"""
(?:(
# Numbered books
(?:(?:Third|Thir|Thi|III|3rd|Th|3)\ ?
(?:John|Joh|Jhn|Jo|Jn|Jn|J))
# Other books
|Thessalonians|John|Th|Jn)\ ?
# Lookahead for numbers or punctuation
(?=[\d:., ]))
|
# Do the same check, this time at the end of the string.
(
(?:(?:Third|Thir|Thi|III|3rd|Th|3)\ ?
(?:John|Joh|Jhn|Jo|Jn|Jn|J))
|Thessalonians|John|Th|Jn)\.?$
""", re.IGNORECASE | re.VERBOSE)
>>> cp.match("Third John").group()
'Third John'
>>> cp.match("Th Jn").group()
'Th'
>>> cp.match("Th Jn ").group()
'Th Jn'
The intention of this snippet is to match various forms of "Third John", as well as forms of "Thessalonians" and "John" by themselves. In most cases this works fine, but it does not match "Th Jn" (or "Th John"), rather matching "Th" by itself.
I've ordered the appearance of each abbreviation in the expression from longest to shortest expressly to avoid a situation like this, relying on a regular expression's typically greedy behavior. But the positive lookahead assertion seems to be short-circuiting this order, picking the shortest match instead of the greediest match.
Of course, removing the lookahead assertion makes this case work, but breaks a bunch of other tests. How might I go about fixing this?
| [
"I've given up after a little try to follow what _sre.so is doing in this case (too complicated!) but a \"blind fix\" I tried seemed to work -- switch to a negative lookahead assertion for the complementary character set...:\ncp = re.compile(ur\"\"\"\n(?:(\n # Numbered books\n (?:(?:Third|Thir|Thi|III|3rd|Th|3)\\ ? \n (?:John|Joh|Jhn|Jo|Jn|Jn|J))\n # Other books\n |Thessalonians|John|Th|Jn)\\ ? \n # Lookahead for numbers or punctuation\n (?![^\\d:., ]))\n\n|\n\netc. I.e. I changed the original (?=[\\d:., ])) positive lookahead into a \"double negation\" form (negative lookahead for complement) (?![^\\d:., ])) and this seems to remove the perturbation. Does this work correctly for you?\nI think it's an implementation anomaly in this corner case of _sre.so -- it might be interesting to see what other RE engines do in these two cases, just as a sanity check.\n",
"The lookahead isn't really short circuiting anything. The regex is only greedy up to a point. It'll prefer a match in your first big block because it doesn't want to cross that \"|\" boundary to the second part of the regex and have to check that as well.\nSince the whole string doesn't match the first big block (because the lookeahead says it needs to be followed by a particular character rather than end of line) it just matches the \"Th\" from the \"Thessalonians\" group and the lookahead sees a space following \"Th\" in \"Th Jn\" so it considers this a valid match.\nWhat you'll probably want to do is move the \"|Thessalonians|John|Th|Jn)\\ ? \" group out to another large \"|\" block. Check your two word books at the beginning of text OR at the end of text OR check for one word books in a third group.\nHope this explanation made sense.\n",
"Another alternate solution I discovered while asking the question: switch the order of the blocks, putting the end-of-line check first, then the lookahead assertion last. However, I prefer Alex's double negative solution, and have implemented that.\n"
] | [
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003142148_python_regex.txt |
Q:
os.path.getmtime of shared files in Dropbox
I want to run a script to check whether certain files in my Dropbox folder have changed. I am currently using os.path.getmtime() to check that the modified time is in some window of time.time(). The problem is that if I modify a file in my Dropbox folder from a different computer than where the script is set to run, the modified time does not change on that latter computer. Is there a good way to watch shared files that doesn't run into this problem?
Thanks for any help! I am just getting into python.
*******UPDATE*******
I have been playing more with how Dropbox handles file timestamping. It only updates the mtime if the file changes. If you open a file, modify it, but save it unchanged, the mtime stays the same.
A:
It looks that Dropbox preserves mtime when synchronizing files. Try to detect changed file by changed file size and/or checksum (MD5, SHA1 or so) instead of modification time. Or just ask Dropbox :) (I don't know if it has any API for this).
| os.path.getmtime of shared files in Dropbox | I want to run a script to check whether certain files in my Dropbox folder have changed. I am currently using os.path.getmtime() to check that the modified time is in some window of time.time(). The problem is that if I modify a file in my Dropbox folder from a different computer than where the script is set to run, the modified time does not change on that latter computer. Is there a good way to watch shared files that doesn't run into this problem?
Thanks for any help! I am just getting into python.
*******UPDATE*******
I have been playing more with how Dropbox handles file timestamping. It only updates the mtime if the file changes. If you open a file, modify it, but save it unchanged, the mtime stays the same.
| [
"It looks that Dropbox preserves mtime when synchronizing files. Try to detect changed file by changed file size and/or checksum (MD5, SHA1 or so) instead of modification time. Or just ask Dropbox :) (I don't know if it has any API for this).\n"
] | [
1
] | [] | [] | [
"dropbox",
"python"
] | stackoverflow_0003142770_dropbox_python.txt |
Q:
What is the best way to do a list[0] with a default value in python?
I am looking for a list functionnality in Python.
I am doing this :
abcd = [1, 2, 3, 4]
try:
item = list[5]
except:
item = 0
How can I make it looks like :
item = abcd.get(5, 0)
Thanks for your help
A:
You cannot add a get method to the list class, but you can use either a function:
def get(alist, index, default):
try: return alist[index]
except IndexError: return default
which gives you the usage example:
abcd = [1, 2, 3, 4]
item = get(abcd, 5, 0)
or a subclass of list:
class mylist(list):
def get(self, index, default):
try: return self[index]
except IndexError: return default
which gives you the usage example:
abcd = mylist([1, 2, 3, 4])
item = abcd.get(5, 0)
A:
Personally I would not want to dedicate more than one line to this operation. As such I would go for something like item = len(abcd) > 5 and abcd[5] or 0.
A very important note on this technique, though, is that the element you want (abcd[5] in this case) must not evaluate to a boolean False value. If it does, the above statement will be evaluated to 0 in stead of the actual (False) value in the list (None, (), {}, etc).
| What is the best way to do a list[0] with a default value in python? | I am looking for a list functionnality in Python.
I am doing this :
abcd = [1, 2, 3, 4]
try:
item = list[5]
except:
item = 0
How can I make it looks like :
item = abcd.get(5, 0)
Thanks for your help
| [
"You cannot add a get method to the list class, but you can use either a function:\ndef get(alist, index, default):\n try: return alist[index]\n except IndexError: return default\n\nwhich gives you the usage example:\nabcd = [1, 2, 3, 4]\nitem = get(abcd, 5, 0)\n\nor a subclass of list:\nclass mylist(list):\n def get(self, index, default):\n try: return self[index]\n except IndexError: return default\n\nwhich gives you the usage example:\nabcd = mylist([1, 2, 3, 4])\nitem = abcd.get(5, 0)\n\n",
"Personally I would not want to dedicate more than one line to this operation. As such I would go for something like item = len(abcd) > 5 and abcd[5] or 0.\nA very important note on this technique, though, is that the element you want (abcd[5] in this case) must not evaluate to a boolean False value. If it does, the above statement will be evaluated to 0 in stead of the actual (False) value in the list (None, (), {}, etc).\n"
] | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003142533_python.txt |
Q:
I want to rank document and store them in a list in python
I am just a beginner in python. I have document score= {1:0.98876, 8:0.12245, 13:0.57689} which is stored in dictionary. The keys are corresponding to a series of document id and the values are corresponding to the score for each document id. How do I rank the document based on the scores?
inverse=[(value, key) for key, value in score.items()]
fmax=max(inverse)
I already found the maximum values by using the method above which return:
(0.98876,1)
But what I want is to rank the documents and store in a list:
{(0.98876,1),(0.57689,13),(0.12245,8)}
A:
sorted(score.items(), key=lambda x:-x[1])
should do the trick
The order of the elements in a dictionary is not defined, so the result of the sorting has to be stored in a list (or an OrderedDict).
You should convert it to a list of tuples using items(). With sorted() you can sort them, the key parameter tells it to sort according to the inverse of the second tuple element.
Full example:
>>> score= {1:0.98876, 8:0.12245, 13:0.57689}
>>> sorted(score.items(), key=lambda x:-x[1])
[(1, 0.98875999999999997), (13, 0.57689000000000001), (8, 0.12245)]
>>> print [(y,x) for (x,y) in _]
[(0.98875999999999997, 1), (0.57689000000000001, 13), (0.12245, 8)]
This also shows how to reverse the elements in the tuple if you really want to do that.
A:
if you want to modify original list inverse then use inverse.sort(reverse=True).
If you want to produce a new list and leave original list untouched, use sorted(inverse, reverse=True).
You don't need an intermediate list, however, just use score:
>>> sorted(score.items(), key=lambda x: x[1], reverse=True)
[(1, 0.98876), (13, 0.57689), (8, 0.12245)]
A:
After your inverse method, this would do the trick:
ranked = inverse.sort()
And here's some more info on sorting in python: http://wiki.python.org/moin/HowTo/Sorting/
A:
Sort the inverse list:
inverse.sort()
This will return the list in ascending order, if you want it in reverse order, reverse it also:
inverse.reverse()
A:
use this:
inverse.sort(reverse=True)
have a look here for more info on sorting
A:
if you want rank itens in dict:
score = {1:0.98876, 8:0.12245, 13:0.57689}
# get a list of items...
list = score.items()
print list
[(8, 0.12245), (1, 0.98875999999999997), (13, 0.57689000000000001)]
# Sort items.
list.sort()
print list
[(1, 0.98875999999999997), (8, 0.12245), (13, 0.57689000000000001)]
# reverse order
list.reverse()
print list
[(13, 0.57689000000000001), (8, 0.12245), (1, 0.98875999999999997)]
| I want to rank document and store them in a list in python | I am just a beginner in python. I have document score= {1:0.98876, 8:0.12245, 13:0.57689} which is stored in dictionary. The keys are corresponding to a series of document id and the values are corresponding to the score for each document id. How do I rank the document based on the scores?
inverse=[(value, key) for key, value in score.items()]
fmax=max(inverse)
I already found the maximum values by using the method above which return:
(0.98876,1)
But what I want is to rank the documents and store in a list:
{(0.98876,1),(0.57689,13),(0.12245,8)}
| [
"sorted(score.items(), key=lambda x:-x[1])\n\nshould do the trick\nThe order of the elements in a dictionary is not defined, so the result of the sorting has to be stored in a list (or an OrderedDict).\nYou should convert it to a list of tuples using items(). With sorted() you can sort them, the key parameter tells it to sort according to the inverse of the second tuple element.\nFull example:\n>>> score= {1:0.98876, 8:0.12245, 13:0.57689}\n>>> sorted(score.items(), key=lambda x:-x[1])\n[(1, 0.98875999999999997), (13, 0.57689000000000001), (8, 0.12245)]\n>>> print [(y,x) for (x,y) in _]\n[(0.98875999999999997, 1), (0.57689000000000001, 13), (0.12245, 8)]\n\nThis also shows how to reverse the elements in the tuple if you really want to do that.\n",
"if you want to modify original list inverse then use inverse.sort(reverse=True).\nIf you want to produce a new list and leave original list untouched, use sorted(inverse, reverse=True).\nYou don't need an intermediate list, however, just use score:\n>>> sorted(score.items(), key=lambda x: x[1], reverse=True)\n[(1, 0.98876), (13, 0.57689), (8, 0.12245)]\n\n",
"After your inverse method, this would do the trick:\nranked = inverse.sort()\n\nAnd here's some more info on sorting in python: http://wiki.python.org/moin/HowTo/Sorting/\n",
"Sort the inverse list:\ninverse.sort()\n\nThis will return the list in ascending order, if you want it in reverse order, reverse it also:\ninverse.reverse()\n\n",
"use this:\n\ninverse.sort(reverse=True)\n\nhave a look here for more info on sorting\n",
"if you want rank itens in dict:\nscore = {1:0.98876, 8:0.12245, 13:0.57689}\n# get a list of items...\nlist = score.items()\nprint list\n[(8, 0.12245), (1, 0.98875999999999997), (13, 0.57689000000000001)]\n\n# Sort items.\nlist.sort()\nprint list \n[(1, 0.98875999999999997), (8, 0.12245), (13, 0.57689000000000001)]\n# reverse order\nlist.reverse()\nprint list\n[(13, 0.57689000000000001), (8, 0.12245), (1, 0.98875999999999997)]\n\n"
] | [
3,
2,
0,
0,
0,
0
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0003142987_python_sorting.txt |
Q:
PyGTK/GIO: monitor directory for changes recursively
Take the following demo code (from the GIO answer to this question), which uses a GIO FileMonitor to monitor a directory for changes:
import gio
def directory_changed(monitor, file1, file2, evt_type):
print "Changed:", file1, file2, evt_type
gfile = gio.File(".")
monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)
monitor.connect("changed", directory_changed)
import glib
ml = glib.MainLoop()
ml.run()
After running this code, I can then create and modify child nodes and be notified of the changes. However, this only works for immediate children (I am aware that the docs don't say otherwise). The last of the following shell commands will not result in a notification:
touch one
mkdir two
touch two/three
Is there an easy way to make it recursive? I'd rather not manually code something that looks for directory creation and adds a monitor, removing them on deletion, etc.
The intended use is for a VCS file browser extension, to be able to cache the statuses of files in a working copy and update them individually on changes. So there might by anywhere from tens to thousands (or more) directories to monitor. I'd like to just find the root of the working copy and add the file monitor there.
I know about pyinotify, but I'm avoiding it so that this works under non-Linux kernels such as FreeBSD or... others. As far as I'm aware, the GIO FileMonitor uses inotify underneath where available, and I can understand not emphasising the implementation to maintain some degree of abstraction, but it suggested to me that it should be possible.
(In case it matters, I originally posted this on the PyGTK mailing list.)
A:
"Is there an easy way to make it
recursive?"
I'm not aware of any "easy way" to achieve this. The underlying systems, such as inotify on Linux or kqueue on BSDs don't provide facilities to automatically add recursive watches. I'm also not aware of any library layering what you want atop GIO.
So you'll most likely have to build this yourself. As this can be a bit trick in some corner cases (e.g. mkdir -p foo/bar/baz) I would suggest looking at how pynotify implements its auto_add functionality (grep through the pynotify source) and porting that over to GIO.
A:
I'm not sure if GIO allows you to have more than one monitor at once, but if it does there's no* reason you can't do something like this:
import gio
import os
def directory_changed(monitor, file1, file2, evt_type):
if os.path.isdir(file2): #maybe this needs to be file1?
add_monitor(file2)
print "Changed:", file1, file2, evt_type
def add_monitor(dir):
gfile = gio.File(dir)
monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)
monitor.connect("changed", directory_changed)
add_monitor('.')
import glib
ml = glib.MainLoop()
ml.run()
*when I say no reason, there's the possibility that this could become a resource hog, though with nearly zero knowledge about GIO I couldn't really say. It's also entirely possible to roll your own in Python with a few commands (os.listdir among others). It might look something like this
import time
import os
class Watcher(object):
def __init__(self):
self.dirs = []
self.snapshots = {}
def add_dir(self, dir):
self.dirs.append(dir)
def check_for_changes(self, dir):
snapshot = self.snapshots.get(dir)
curstate = os.listdir(dir)
if not snapshot:
self.snapshots[dir] = curstate
else:
if not snapshot == curstate:
print 'Changes: ',
for change in set(curstate).symmetric_difference(set(snapshot)):
if os.path.isdir(change):
print "isdir"
self.add_dir(change)
print change,
self.snapshots[dir] = curstate
print
def mainloop(self):
if len(self.dirs) < 1:
print "ERROR: Please add a directory with add_dir()"
return
while True:
for dir in self.dirs:
self.check_for_changes(dir)
time.sleep(4) # Don't want to be a resource hog
w = Watcher()
w.add_dir('.')
w.mainloop()
| PyGTK/GIO: monitor directory for changes recursively | Take the following demo code (from the GIO answer to this question), which uses a GIO FileMonitor to monitor a directory for changes:
import gio
def directory_changed(monitor, file1, file2, evt_type):
print "Changed:", file1, file2, evt_type
gfile = gio.File(".")
monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)
monitor.connect("changed", directory_changed)
import glib
ml = glib.MainLoop()
ml.run()
After running this code, I can then create and modify child nodes and be notified of the changes. However, this only works for immediate children (I am aware that the docs don't say otherwise). The last of the following shell commands will not result in a notification:
touch one
mkdir two
touch two/three
Is there an easy way to make it recursive? I'd rather not manually code something that looks for directory creation and adds a monitor, removing them on deletion, etc.
The intended use is for a VCS file browser extension, to be able to cache the statuses of files in a working copy and update them individually on changes. So there might by anywhere from tens to thousands (or more) directories to monitor. I'd like to just find the root of the working copy and add the file monitor there.
I know about pyinotify, but I'm avoiding it so that this works under non-Linux kernels such as FreeBSD or... others. As far as I'm aware, the GIO FileMonitor uses inotify underneath where available, and I can understand not emphasising the implementation to maintain some degree of abstraction, but it suggested to me that it should be possible.
(In case it matters, I originally posted this on the PyGTK mailing list.)
| [
"\n\"Is there an easy way to make it\n recursive?\"\n\nI'm not aware of any \"easy way\" to achieve this. The underlying systems, such as inotify on Linux or kqueue on BSDs don't provide facilities to automatically add recursive watches. I'm also not aware of any library layering what you want atop GIO.\nSo you'll most likely have to build this yourself. As this can be a bit trick in some corner cases (e.g. mkdir -p foo/bar/baz) I would suggest looking at how pynotify implements its auto_add functionality (grep through the pynotify source) and porting that over to GIO.\n",
"I'm not sure if GIO allows you to have more than one monitor at once, but if it does there's no* reason you can't do something like this:\nimport gio\nimport os\n\ndef directory_changed(monitor, file1, file2, evt_type):\n if os.path.isdir(file2): #maybe this needs to be file1?\n add_monitor(file2) \n print \"Changed:\", file1, file2, evt_type\n\ndef add_monitor(dir):\n gfile = gio.File(dir)\n monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)\n monitor.connect(\"changed\", directory_changed) \n\nadd_monitor('.')\n\nimport glib\nml = glib.MainLoop()\nml.run()\n\n*when I say no reason, there's the possibility that this could become a resource hog, though with nearly zero knowledge about GIO I couldn't really say. It's also entirely possible to roll your own in Python with a few commands (os.listdir among others). It might look something like this\nimport time\nimport os\n\nclass Watcher(object):\n def __init__(self):\n self.dirs = []\n self.snapshots = {}\n\n def add_dir(self, dir):\n self.dirs.append(dir)\n\n def check_for_changes(self, dir):\n snapshot = self.snapshots.get(dir)\n curstate = os.listdir(dir)\n if not snapshot:\n self.snapshots[dir] = curstate\n else:\n if not snapshot == curstate:\n print 'Changes: ',\n for change in set(curstate).symmetric_difference(set(snapshot)):\n if os.path.isdir(change):\n print \"isdir\"\n self.add_dir(change)\n print change,\n\n self.snapshots[dir] = curstate\n print\n\n def mainloop(self):\n if len(self.dirs) < 1:\n print \"ERROR: Please add a directory with add_dir()\"\n return\n\n while True:\n for dir in self.dirs:\n self.check_for_changes(dir)\n time.sleep(4) # Don't want to be a resource hog\n\nw = Watcher()\nw.add_dir('.')\n\n\nw.mainloop()\n\n"
] | [
2,
1
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003068839_pygtk_python.txt |
Q:
How to send file to serial port using kermit protocol in python
I have device connected through serial port to PC. Using c-kermit I can send commands to device and read output. I can also send files using kermit protocol.
In python we have pretty nice library - pySerial. I can use it to send/receive data from device. But is there some nice solution to send files using kermit protocol?
A:
You should be able to do it via the subprocess module. The following assumes that you can send commands to your remote machine and parse out the results already. :-)
I don't have anything to test this on at the moment, so I'm going to be pretty general.
Roughly:
use pyserial to connect to the remote system through the serial port.
run the kermit client on the remote system using switches that will send the file or files you wish to transfer over the remote systems serial port (the serial line you are using.)
disconnect your pyserial instance
start your kermit client with subprocess and accept the files.
reconnect your pyserial instance and clean everything up.
I'm willing to bet this isn't much help, but when I actually did this a few years ago (using os.system, rather than subprocess on a hideous, hideous SuperDOS system) it took me a while to get my fat head around the fact that I had to start a kermit client remotely to send the file to my client!
If I have some time this week I'll break out one of my old geode boards and see if I can post some actual working code.
| How to send file to serial port using kermit protocol in python | I have device connected through serial port to PC. Using c-kermit I can send commands to device and read output. I can also send files using kermit protocol.
In python we have pretty nice library - pySerial. I can use it to send/receive data from device. But is there some nice solution to send files using kermit protocol?
| [
"You should be able to do it via the subprocess module. The following assumes that you can send commands to your remote machine and parse out the results already. :-)\nI don't have anything to test this on at the moment, so I'm going to be pretty general.\nRoughly:\n\nuse pyserial to connect to the remote system through the serial port.\nrun the kermit client on the remote system using switches that will send the file or files you wish to transfer over the remote systems serial port (the serial line you are using.)\ndisconnect your pyserial instance\nstart your kermit client with subprocess and accept the files.\nreconnect your pyserial instance and clean everything up.\n\nI'm willing to bet this isn't much help, but when I actually did this a few years ago (using os.system, rather than subprocess on a hideous, hideous SuperDOS system) it took me a while to get my fat head around the fact that I had to start a kermit client remotely to send the file to my client!\nIf I have some time this week I'll break out one of my old geode boards and see if I can post some actual working code.\n"
] | [
1
] | [] | [] | [
"kermit",
"pyserial",
"python",
"serial_port"
] | stackoverflow_0002237483_kermit_pyserial_python_serial_port.txt |
Q:
"/1/2/3/".split("/")
It's too hot & I'm probably being retarded.
>>> "/1/2/3/".split("/")
['', '1', '2', '3','']
Whats with the empty elements at the start and end?
Edit: Thanks all, im putting this down to heat induced brain failure. The docs aren't quite the clearest though, from http://docs.python.org/library/stdtypes.html
"Return a list of the words in the string, using sep as the delimiter string"
Is there a word before the first, or after the last "/"?
A:
Compare with:
"1/2/3".split("/")
Empty elements are still elements.
You could use strip('/') to trim the delimiter from the beginning/end of your string.
A:
As JLWarlow says, you have an extra '/' in the string. Here's another example:
>>> "//2//3".split('/')
['', '', '2', '', '3']
A:
Slashes are separators, so there are empty elements before the first and after the last.
A:
you're splitting on /. You have 4 /, so, the list returned will have 5 elements.
A:
That is exactly what I would expect, but we are all different :)
What would you expect from: : "1,,2,3".split(",") ?
A:
You can use strip() to get rid of the leading and trailing fields... Then call split() as before.
A:
[x for x in "//1///2/3///".split("/") if x != ""]
| "/1/2/3/".split("/") | It's too hot & I'm probably being retarded.
>>> "/1/2/3/".split("/")
['', '1', '2', '3','']
Whats with the empty elements at the start and end?
Edit: Thanks all, im putting this down to heat induced brain failure. The docs aren't quite the clearest though, from http://docs.python.org/library/stdtypes.html
"Return a list of the words in the string, using sep as the delimiter string"
Is there a word before the first, or after the last "/"?
| [
"Compare with:\n\"1/2/3\".split(\"/\")\n\nEmpty elements are still elements.\nYou could use strip('/') to trim the delimiter from the beginning/end of your string.\n",
"As JLWarlow says, you have an extra '/' in the string. Here's another example:\n>>> \"//2//3\".split('/')\n['', '', '2', '', '3']\n\n",
"Slashes are separators, so there are empty elements before the first and after the last.\n",
"you're splitting on /. You have 4 /, so, the list returned will have 5 elements.\n",
"That is exactly what I would expect, but we are all different :)\nWhat would you expect from: : \"1,,2,3\".split(\",\") ?\n",
"You can use strip() to get rid of the leading and trailing fields... Then call split() as before.\n",
"[x for x in \"//1///2/3///\".split(\"/\") if x != \"\"]\n\n"
] | [
18,
4,
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003142428_python_string.txt |
Q:
python import depth
I've noticed that importing a module will import its functions and methods, and the functions and methods of those as well. Is there a set rule for how many levels down python will import when you import an upper-level module?
edit
sorry, I think I've been misunderstood by the answers so far responding about multiple imports of some dependencies. I'm thinking of nested folders e.g. in django, if you import django, you can access django.contrib.auth, but you can't access django.contrib.auth.views unless you import that specifically. I was just wondering if it's always two levels down in such a case
second edit
to clarify again.. in the django example, the layout is /django/contrib/auth/views.py, where each of the subfolders has a "init.py" making it a module, none of which define any "all" attributes. Is my example bad, since maybe you can't use the dot syntax to navigate to a file within a module designated folder?
A:
No, python will import what it needs to import. However, each module is only imported once. For example, if one module does import sys and another module does import sys, it will not physically do it twice.
A:
Not really. A module imports stuff from other modules because it needs to use them in that module, otherwise it'll break.
A:
There is no pre-defined import depth level. Import statements are executed, just like any other python statement.
But, you may wonder, how are cycles avoided? Modules are added to sys.modules (i.e., cached) when they get imported for the first time, and that is the first location examined when an import statement is executed. So each module is loaded just once, although it may appear in many import statements.
| python import depth | I've noticed that importing a module will import its functions and methods, and the functions and methods of those as well. Is there a set rule for how many levels down python will import when you import an upper-level module?
edit
sorry, I think I've been misunderstood by the answers so far responding about multiple imports of some dependencies. I'm thinking of nested folders e.g. in django, if you import django, you can access django.contrib.auth, but you can't access django.contrib.auth.views unless you import that specifically. I was just wondering if it's always two levels down in such a case
second edit
to clarify again.. in the django example, the layout is /django/contrib/auth/views.py, where each of the subfolders has a "init.py" making it a module, none of which define any "all" attributes. Is my example bad, since maybe you can't use the dot syntax to navigate to a file within a module designated folder?
| [
"No, python will import what it needs to import. However, each module is only imported once. For example, if one module does import sys and another module does import sys, it will not physically do it twice.\n",
"Not really. A module imports stuff from other modules because it needs to use them in that module, otherwise it'll break.\n",
"There is no pre-defined import depth level. Import statements are executed, just like any other python statement. \nBut, you may wonder, how are cycles avoided? Modules are added to sys.modules (i.e., cached) when they get imported for the first time, and that is the first location examined when an import statement is executed. So each module is loaded just once, although it may appear in many import statements.\n"
] | [
3,
1,
1
] | [] | [] | [
"depth",
"import",
"python"
] | stackoverflow_0003143106_depth_import_python.txt |
Q:
How to get Field names from a SQL database into a list in python
Here is a the code I have so far:
from ConfigParser import *
import MySQLdb
configuration = ConfigParser()
configuration.read('someconfigfile.conf')
db = MySQLdb.connect(
host = configuration.get('DATABASE', 'MYSQL_HOST'),
user = configuration.get('DATABASE', 'MYSQL_USER'),
passwd = configuration.get('DATABASE', 'MYSQL_PASS'),
db = configuration.get('DATABASE', 'MYSQL_DB'),
port = configuration.getint('DATABASE', 'MYSQL_PORT'),
ssl = {
'ca': configuration.get('SSL_SETTINGS', 'SSL_CA'),
'cert': configuration.get('SSL_SETTINGS', 'SSL_CERT'),
'key': configuration.get('SSL_SETTINGS', 'SSL_KEY')
},
)
cursor = db.cursor()
sql = "SELECT column_name FROM information_schema.columns WHERE table_name='met';"
cursor.execute(sql)
list = cursor.fetchall()
print list
this is what prints:
(('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('pk_wind_spd2',), ('field',))
And I am getting a tuple instead of a list. I would prefer to have a list of strings
A:
Don't shadow built-ins (list), change to
alist = cursor.fetchall()
This generator expression will get you the column names in a tuple:
tuple(i[0] for i in alist)
| How to get Field names from a SQL database into a list in python | Here is a the code I have so far:
from ConfigParser import *
import MySQLdb
configuration = ConfigParser()
configuration.read('someconfigfile.conf')
db = MySQLdb.connect(
host = configuration.get('DATABASE', 'MYSQL_HOST'),
user = configuration.get('DATABASE', 'MYSQL_USER'),
passwd = configuration.get('DATABASE', 'MYSQL_PASS'),
db = configuration.get('DATABASE', 'MYSQL_DB'),
port = configuration.getint('DATABASE', 'MYSQL_PORT'),
ssl = {
'ca': configuration.get('SSL_SETTINGS', 'SSL_CA'),
'cert': configuration.get('SSL_SETTINGS', 'SSL_CERT'),
'key': configuration.get('SSL_SETTINGS', 'SSL_KEY')
},
)
cursor = db.cursor()
sql = "SELECT column_name FROM information_schema.columns WHERE table_name='met';"
cursor.execute(sql)
list = cursor.fetchall()
print list
this is what prints:
(('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('field',), ('pk_wind_spd2',), ('field',))
And I am getting a tuple instead of a list. I would prefer to have a list of strings
| [
"Don't shadow built-ins (list), change to \nalist = cursor.fetchall()\nThis generator expression will get you the column names in a tuple:\ntuple(i[0] for i in alist)\n"
] | [
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003143150_mysql_python.txt |
Q:
What's an elegant way to create a dictionary from another dictionary's keys and an array of values?
How can I create another dictionary using the keys of another dictionary, and an array of values?
I thought about doing this:
zipped = zip(theExistingDict.keys(), arrayOfValues)
myNewDict = dict(zipped)
However, this doesn't quite work, each value from arrayOfValues are paired with an arbitrary key in the resulting dictionary. I don't have any control over which element from arrayOfValues is paired with which key in theExistingDict.keys().
theExistingDict looks like this:
{u'actual bitrate': 4, u'Suggested Bitrate': 3, u'title': 2, u'id': 1, u'game slot': 0}
arrayOfValues looks like this:
1.0, u'GOLD_Spider Solitaire', u'Spider\\nSolitaire', 120000.0, 120000.0
So: I would like arrayOfValues[0] to map to game slot (because in the dictionary it has value 0).
Is there an easy and elegant way to do this?
A:
As others have mentioned, a Dictionary doesn't have any order defined in it. The python docs say, "Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions."
If you're looking to use the original order that you added the items into the dictionary, you can try looking for an alternative implementation of dictionary that preserves this order -- e.g. http://www.voidspace.org.uk/python/odict.html
A:
Since your existing dictionary itself contains information on the positions of the elements in the list: you could do:
>>> exist = {u'title': 2, u'actual bitrate': 4, u'id': 1, u'game slot': 0, u'Suggested Bitrate': 3}
>>> l = [1.0, u'GOLD_Spider Solitaire', u'Spider\\nSolitaire', 120000.0, 120000.0]
>>> dict((k, l[v]) for k, v in exist.iteritems())
{u'Suggested Bitrate': 120000.0, u'game slot': 1.0, u'actual bitrate': 120000.0, u'id': u'GOLD_Spider Solitaire', u'title': u'Spider\\nSolitaire'}
or in py3k/python 2.7+:
>>> {k: l[v] for k, v in exist.items()}
{'Suggested Bitrate': 120000.0, 'game slot': 1.0, 'actual bitrate': 120000.0, 'id': 'GOLD_Spider Solitaire', 'title': 'Spider\\nSolitaire'}
A:
In light of the comments above, it's possible that a dictionary for theExistingDict may not be the structure you are looking for.
You may be interested in an ordered dictionary.
See also the answers to "What’s the way to keep the dictionary parameter order in Python?"
A:
perhaps something more like:
from operator import itemgetter
zip( array_of_values, [ a for a, _ in sorted(existing_dict.iteritems(), key=itemgetter(1)) ] )
it can be modified further if you'd like to match index with integer, possibly with unused values...
zipped = [ (k, a) for i, a in enumerate(array_of_values) for k, v in existing_dict.iteritems() if i == v ]
new_dict = dict(zipped)
| What's an elegant way to create a dictionary from another dictionary's keys and an array of values? | How can I create another dictionary using the keys of another dictionary, and an array of values?
I thought about doing this:
zipped = zip(theExistingDict.keys(), arrayOfValues)
myNewDict = dict(zipped)
However, this doesn't quite work, each value from arrayOfValues are paired with an arbitrary key in the resulting dictionary. I don't have any control over which element from arrayOfValues is paired with which key in theExistingDict.keys().
theExistingDict looks like this:
{u'actual bitrate': 4, u'Suggested Bitrate': 3, u'title': 2, u'id': 1, u'game slot': 0}
arrayOfValues looks like this:
1.0, u'GOLD_Spider Solitaire', u'Spider\\nSolitaire', 120000.0, 120000.0
So: I would like arrayOfValues[0] to map to game slot (because in the dictionary it has value 0).
Is there an easy and elegant way to do this?
| [
"As others have mentioned, a Dictionary doesn't have any order defined in it. The python docs say, \"Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.\"\nIf you're looking to use the original order that you added the items into the dictionary, you can try looking for an alternative implementation of dictionary that preserves this order -- e.g. http://www.voidspace.org.uk/python/odict.html\n",
"Since your existing dictionary itself contains information on the positions of the elements in the list: you could do:\n>>> exist = {u'title': 2, u'actual bitrate': 4, u'id': 1, u'game slot': 0, u'Suggested Bitrate': 3}\n>>> l = [1.0, u'GOLD_Spider Solitaire', u'Spider\\\\nSolitaire', 120000.0, 120000.0]\n>>> dict((k, l[v]) for k, v in exist.iteritems())\n{u'Suggested Bitrate': 120000.0, u'game slot': 1.0, u'actual bitrate': 120000.0, u'id': u'GOLD_Spider Solitaire', u'title': u'Spider\\\\nSolitaire'}\n\nor in py3k/python 2.7+:\n>>> {k: l[v] for k, v in exist.items()}\n{'Suggested Bitrate': 120000.0, 'game slot': 1.0, 'actual bitrate': 120000.0, 'id': 'GOLD_Spider Solitaire', 'title': 'Spider\\\\nSolitaire'}\n\n",
"In light of the comments above, it's possible that a dictionary for theExistingDict may not be the structure you are looking for.\nYou may be interested in an ordered dictionary.\nSee also the answers to \"What’s the way to keep the dictionary parameter order in Python?\" \n",
"perhaps something more like:\nfrom operator import itemgetter\nzip( array_of_values, [ a for a, _ in sorted(existing_dict.iteritems(), key=itemgetter(1)) ] )\n\nit can be modified further if you'd like to match index with integer, possibly with unused values...\n zipped = [ (k, a) for i, a in enumerate(array_of_values) for k, v in existing_dict.iteritems() if i == v ]\n new_dict = dict(zipped)\n\n"
] | [
4,
4,
0,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003142012_dictionary_python.txt |
Q:
implementing chop() using iterators
Current version:
def chop(ar,size):
p=len(ar)/size
for i in xrange(p):
yield ar[(i*size):((i+1)*size)]
ar is type of list().
What i want is that chop() takes iterator and return iterator.
for i in chop(xrange(9),3):
for j in i:
print j,
print
prints
0 1 2
3 4 5
6 7 8
A:
There's an implementation in the itertools documentation:
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
| implementing chop() using iterators | Current version:
def chop(ar,size):
p=len(ar)/size
for i in xrange(p):
yield ar[(i*size):((i+1)*size)]
ar is type of list().
What i want is that chop() takes iterator and return iterator.
for i in chop(xrange(9),3):
for j in i:
print j,
print
prints
0 1 2
3 4 5
6 7 8
| [
"There's an implementation in the itertools documentation:\ndef grouper(n, iterable, fillvalue=None):\n \"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return izip_longest(fillvalue=fillvalue, *args)\n\n"
] | [
2
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0003143371_iterator_python.txt |
Q:
retrieving uploaded images with django's ImageField
this is the code in my models file:
from django.db import models
class Studio(models.Model):
.....
.....
metroimage = models.ImageField(upload_to='images', blank=True)
this is the code on the template file:
{% for place in studio %}
.....
.....
<img class="metro" src="{{ place.metroimage.url }}"><b>{{ place.metro }}</b><br>
{% endif %}
but when the page displays i get this (this is source-code)
.....
.....
<img class="metro" src="/http://momo.webfactional.com/media/images/m3.png"><b>Zara</b><br>
what's with the forward slash before http? i can't get the uploaded image to display...
A:
I'd guess your MEDIA_URL settings (in settings.py) is to blame for the extra slash.
| retrieving uploaded images with django's ImageField | this is the code in my models file:
from django.db import models
class Studio(models.Model):
.....
.....
metroimage = models.ImageField(upload_to='images', blank=True)
this is the code on the template file:
{% for place in studio %}
.....
.....
<img class="metro" src="{{ place.metroimage.url }}"><b>{{ place.metro }}</b><br>
{% endif %}
but when the page displays i get this (this is source-code)
.....
.....
<img class="metro" src="/http://momo.webfactional.com/media/images/m3.png"><b>Zara</b><br>
what's with the forward slash before http? i can't get the uploaded image to display...
| [
"I'd guess your MEDIA_URL settings (in settings.py) is to blame for the extra slash. \n"
] | [
1
] | [] | [] | [
"django",
"imagefield",
"python"
] | stackoverflow_0003142883_django_imagefield_python.txt |
Q:
py-amqp/flopsy: Waiting for a single AMQP message in Python
I have a similar question to this one: It's very easy in py-amqp/flopsy to say "I'm going to wait forever, and I want this callback to be called whenever a message comes in," but I can't find any way of saying "OK, I got the message I want now stop waiting." (Maybe a GOTO? Just kidding...) Is there an elegant way of doing this?
A:
OK, maybe this should have been obvious to me: If you register a callback in flopsy (which is a thin wrapper around amqplib) with
consumer.register('kind', callback_func)
consumer.wait()
# more code goes here...
then you can raise an Exception in callback_func to get to the rest of the code.
Bonus question: How do I set a maximum timeout for the wait() in case a response is never received? Let's say that this is in the context of a unittest test case.
| py-amqp/flopsy: Waiting for a single AMQP message in Python | I have a similar question to this one: It's very easy in py-amqp/flopsy to say "I'm going to wait forever, and I want this callback to be called whenever a message comes in," but I can't find any way of saying "OK, I got the message I want now stop waiting." (Maybe a GOTO? Just kidding...) Is there an elegant way of doing this?
| [
"OK, maybe this should have been obvious to me: If you register a callback in flopsy (which is a thin wrapper around amqplib) with\nconsumer.register('kind', callback_func)\nconsumer.wait()\n# more code goes here...\n\nthen you can raise an Exception in callback_func to get to the rest of the code.\nBonus question: How do I set a maximum timeout for the wait() in case a response is never received? Let's say that this is in the context of a unittest test case.\n"
] | [
1
] | [] | [] | [
"amqp",
"flopsy",
"py_amqplib",
"python"
] | stackoverflow_0003135629_amqp_flopsy_py_amqplib_python.txt |
Q:
How can I use google app engine?
I've begun planning a kind of web store interface that I want to work on soon. I'm starting to import products from China and want to have a completely unique feel for my site. Now I'm kinda a google fanboy and have heard alot about google app engine. Mostly I like the hosting available with google more then anything though. But I wanted to know, would the App Engine be good for what I'm making?
Namely a web store with an app like feel. I've decided, to help if I ever need to move my host, to work in web2py hosted in the App Engine. Or would I be better with django or something on a normal host?
Is google best for webapps? Or is it pretty well suited for webstores as well?
Thanks
A:
It is hard to say if App Engine is suited to your particular needs without more details about what functionality you want your web store to present. It also depends a little bit on your background and experience.
However, the "app like feel" and crafting a "completely unique feel" for your site is something you can accomplish on any reasonable platform - I expect the presentation style will be relatively independent of the backend you choose.
A:
You can build almost anything on GAE. As Monk would say that is a blessing and a curse. GAE is relatively new and so e commerce ventures are relatively rare. This means you would be responsible for every piece of the site. Other dedicated e commerce technologies trade some of the control and look and feel for ease of use/setup.
So in short yes you could use GAE to create an e commerce site, but you would be spending a lot of time getting it up and running and then managing it. Time you may find better spent on sales and marketing.
| How can I use google app engine? | I've begun planning a kind of web store interface that I want to work on soon. I'm starting to import products from China and want to have a completely unique feel for my site. Now I'm kinda a google fanboy and have heard alot about google app engine. Mostly I like the hosting available with google more then anything though. But I wanted to know, would the App Engine be good for what I'm making?
Namely a web store with an app like feel. I've decided, to help if I ever need to move my host, to work in web2py hosted in the App Engine. Or would I be better with django or something on a normal host?
Is google best for webapps? Or is it pretty well suited for webstores as well?
Thanks
| [
"It is hard to say if App Engine is suited to your particular needs without more details about what functionality you want your web store to present. It also depends a little bit on your background and experience.\nHowever, the \"app like feel\" and crafting a \"completely unique feel\" for your site is something you can accomplish on any reasonable platform - I expect the presentation style will be relatively independent of the backend you choose.\n",
"You can build almost anything on GAE. As Monk would say that is a blessing and a curse. GAE is relatively new and so e commerce ventures are relatively rare. This means you would be responsible for every piece of the site. Other dedicated e commerce technologies trade some of the control and look and feel for ease of use/setup. \nSo in short yes you could use GAE to create an e commerce site, but you would be spending a lot of time getting it up and running and then managing it. Time you may find better spent on sales and marketing. \n"
] | [
0,
0
] | [] | [] | [
"google_app_engine",
"python",
"web_applications",
"webstore"
] | stackoverflow_0003143703_google_app_engine_python_web_applications_webstore.txt |
Q:
Python profiler usage with objects
I have a specific question regarding the usage of profiler. I am new to python programming
I am trying to profile a function which I want to invoke as a class method, something like this
import profile
class Class:
def doSomething():
do here ..
def callMethod():
self.doSomething()
instead of this I want to use
profile.run(self.doSomething())
but the profile.run expects the string inside it and I get error
TypeError: exec: arg 1 must be a string, file, or code object
Can somebody please help?
Thank you
A:
Fixed!!!
Instead of profile, I used cProfile module that as per the python docs has much lesser overhead
Ref : http://docs.python.org/library/profile.html#introduction-to-the-profilers
with cProfiler, one can actually pass the local and global params using the runctx module
so for the same problem, I did the following:
import cProfile
cProfile.runctx('self.doSomething()',globals(),locals())
and it worked :)
also, if you have more params to pass you can like
import cProfile
cProfile.runctx('self.doSomething(x,y,z)',globals(),locals())
Thanks for all help
A:
You need to fix various imprecisions (missing self, saying you're using class methods when there's no classmethod in sight, failing to inherit from object, ...) then make profile happy by giving it a string as it wants -- and the name of the instance must be made globally visible so that profile can actually use that string. For example:
import profile
import time
class Class(object):
def doSomething(self):
time.sleep(0.1)
def callMethod(self):
global _o
_o = self
profile.run('_o.doSomething()')
o = Class()
o.callMethod()
| Python profiler usage with objects | I have a specific question regarding the usage of profiler. I am new to python programming
I am trying to profile a function which I want to invoke as a class method, something like this
import profile
class Class:
def doSomething():
do here ..
def callMethod():
self.doSomething()
instead of this I want to use
profile.run(self.doSomething())
but the profile.run expects the string inside it and I get error
TypeError: exec: arg 1 must be a string, file, or code object
Can somebody please help?
Thank you
| [
"Fixed!!!\nInstead of profile, I used cProfile module that as per the python docs has much lesser overhead\nRef : http://docs.python.org/library/profile.html#introduction-to-the-profilers\nwith cProfiler, one can actually pass the local and global params using the runctx module\nso for the same problem, I did the following:\nimport cProfile\ncProfile.runctx('self.doSomething()',globals(),locals())\n\nand it worked :)\nalso, if you have more params to pass you can like\nimport cProfile\ncProfile.runctx('self.doSomething(x,y,z)',globals(),locals())\n\nThanks for all help\n",
"You need to fix various imprecisions (missing self, saying you're using class methods when there's no classmethod in sight, failing to inherit from object, ...) then make profile happy by giving it a string as it wants -- and the name of the instance must be made globally visible so that profile can actually use that string. For example:\nimport profile\nimport time\n\nclass Class(object):\n\n def doSomething(self):\n time.sleep(0.1)\n\n def callMethod(self):\n global _o\n _o = self\n profile.run('_o.doSomething()')\n\no = Class()\no.callMethod()\n\n"
] | [
13,
3
] | [] | [] | [
"profiler",
"python"
] | stackoverflow_0003142901_profiler_python.txt |
Q:
Python code refactoring question. Simplification
I have code that looks something like this:
self.ui.foo = False
self.ui.bar = False
self.ui.item = False
self.ui.item2 = False
self.ui.item3 = False
And I would like to turn it into something like this:
items = [foo,bar,item,item2,item3]
for elm in items:
self.ui.elm = False
But obviously just having the variables in the list with out the 'self.ui' part is invalid, and I would rather not type out 'self.ui' for every element in the list, because that really isn't to much better. How could I rewrite my first code to make it something like what I'm talking about?
A:
Here's how you do that:
items = ['foo','bar','item','item2','item3']
for elm in items:
setattr(self.ui, elm, False)
A:
items needs to be a list of strings.
items = ['foo', 'bar', 'item', 'item2', 'item3']
for elm in items:
setattr(self.ui, elm, False)
| Python code refactoring question. Simplification | I have code that looks something like this:
self.ui.foo = False
self.ui.bar = False
self.ui.item = False
self.ui.item2 = False
self.ui.item3 = False
And I would like to turn it into something like this:
items = [foo,bar,item,item2,item3]
for elm in items:
self.ui.elm = False
But obviously just having the variables in the list with out the 'self.ui' part is invalid, and I would rather not type out 'self.ui' for every element in the list, because that really isn't to much better. How could I rewrite my first code to make it something like what I'm talking about?
| [
"Here's how you do that:\nitems = ['foo','bar','item','item2','item3']\nfor elm in items:\n setattr(self.ui, elm, False)\n\n",
"items needs to be a list of strings.\nitems = ['foo', 'bar', 'item', 'item2', 'item3']\nfor elm in items:\n setattr(self.ui, elm, False)\n\n"
] | [
6,
4
] | [] | [] | [
"list",
"python",
"refactoring"
] | stackoverflow_0003143844_list_python_refactoring.txt |
Q:
Is there a way to view the source code of a function, class, or module from the python interpreter?
Is there a way to view the source code of a function, class, or module from the python interpreter? (in addition to using help to view the docs and dir to view the attributes/methods)
A:
If you plan to use python interactively it is hard to beat ipython. To print the source of any known function you can then use %psource.
In [1]: import ctypes
In [2]: %psource ctypes.c_bool
class c_bool(_SimpleCData):
_type_ = "?"
The output is even colorized. You can also directly invoke your $EDITOR on the defining source file with %edit.
In [3]: %edit ctypes.c_bool
A:
>>> import inspect
>>> print(''.join(inspect.getsourcelines(inspect.getsourcelines)[0]))
def getsourcelines(object):
"""Return a list of source lines and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of the lines
corresponding to the object and the line number indicates where in the
original source file the first line of code was found. An IOError is
raised if the source code cannot be retrieved."""
lines, lnum = findsource(object)
if ismodule(object): return lines, 0
else: return getblock(lines[lnum:]), lnum + 1
| Is there a way to view the source code of a function, class, or module from the python interpreter? | Is there a way to view the source code of a function, class, or module from the python interpreter? (in addition to using help to view the docs and dir to view the attributes/methods)
| [
"If you plan to use python interactively it is hard to beat ipython. To print the source of any known function you can then use %psource.\nIn [1]: import ctypes\nIn [2]: %psource ctypes.c_bool\nclass c_bool(_SimpleCData):\n_type_ = \"?\"\n\nThe output is even colorized. You can also directly invoke your $EDITOR on the defining source file with %edit.\nIn [3]: %edit ctypes.c_bool\n\n",
">>> import inspect\n>>> print(''.join(inspect.getsourcelines(inspect.getsourcelines)[0]))\ndef getsourcelines(object):\n \"\"\"Return a list of source lines and starting line number for an object.\n\n The argument may be a module, class, method, function, traceback, frame,\n or code object. The source code is returned as a list of the lines\n corresponding to the object and the line number indicates where in the\n original source file the first line of code was found. An IOError is\n raised if the source code cannot be retrieved.\"\"\"\n lines, lnum = findsource(object)\n\n if ismodule(object): return lines, 0\n else: return getblock(lines[lnum:]), lnum + 1\n\n"
] | [
19,
11
] | [] | [] | [
"python"
] | stackoverflow_0003143888_python.txt |
Q:
Parent/Child(ren) Hierarchy / "Nested Sets", in Python/Django
I'm using Django/Python, but pseudo-code is definitely acceptable here.
Working with some models that already exist, I have Employees that each have a Supervisor, which is essentially a Foreign Key type relationship to another Employee.
Where the Employee/Supervisor hierarchy is something like this:
Any given Employee has ONE Supervisor. That Supervisor may have one or more Employees "beneath", and has his/her own Supervisor as well. Retrieving my "upline" should return my supervisor, his supervisor, her supervisor, etc., until reaching an employee that has no supervisor.
Without going hog-wild and installing new apps to manage these relationships, as this is an existing codebase and project, I'm wondering the "pythonic" or correct way to implement the following functions:
def get_upline(employee):
# Get a flat list of Employee objects that are
# 'supervisors' to eachother, starting with
# the given Employee.
pass
def get_downline(employee):
# Starting with the given Employee, find and
# return a flat list of all other Employees
# that are "below".
pass
I feel like there may be a somewhat simple way to do this with the Django ORM, but if not, I'll take any suggestions.
I haven't thoroughly checked out Django-MPTT, but if I can leave the models in tact, and simply gain more functionality, it would be worth it.
A:
You don't have to touch your models to be able to use django-mptt; you just have to create a parent field on your model, django-mptt creates all the other attributes for mptt automaitcally, when you register your model: mptt.register(MyModel).
Though if you just need the 'upline' hierarchy you wouldn't need nested sets. The bigger performance problem is going the opposite direction and collect eg. children/leaves etc, which makes it necessary to work on a nested set model!
A:
Relational databases are not good for this kind of graph queries, so your only option is to do a bunch of query. Here is a recursive implementation:
def get_upline(employee):
if self.supervisor:
return [employee] + self.supervisor.get_upline()
else:
return [employee]
def get_download(employee):
l = [employee]
for minion in self.minion_set.all():
l.extend(minion.get_download())
return l
| Parent/Child(ren) Hierarchy / "Nested Sets", in Python/Django | I'm using Django/Python, but pseudo-code is definitely acceptable here.
Working with some models that already exist, I have Employees that each have a Supervisor, which is essentially a Foreign Key type relationship to another Employee.
Where the Employee/Supervisor hierarchy is something like this:
Any given Employee has ONE Supervisor. That Supervisor may have one or more Employees "beneath", and has his/her own Supervisor as well. Retrieving my "upline" should return my supervisor, his supervisor, her supervisor, etc., until reaching an employee that has no supervisor.
Without going hog-wild and installing new apps to manage these relationships, as this is an existing codebase and project, I'm wondering the "pythonic" or correct way to implement the following functions:
def get_upline(employee):
# Get a flat list of Employee objects that are
# 'supervisors' to eachother, starting with
# the given Employee.
pass
def get_downline(employee):
# Starting with the given Employee, find and
# return a flat list of all other Employees
# that are "below".
pass
I feel like there may be a somewhat simple way to do this with the Django ORM, but if not, I'll take any suggestions.
I haven't thoroughly checked out Django-MPTT, but if I can leave the models in tact, and simply gain more functionality, it would be worth it.
| [
"You don't have to touch your models to be able to use django-mptt; you just have to create a parent field on your model, django-mptt creates all the other attributes for mptt automaitcally, when you register your model: mptt.register(MyModel). \nThough if you just need the 'upline' hierarchy you wouldn't need nested sets. The bigger performance problem is going the opposite direction and collect eg. children/leaves etc, which makes it necessary to work on a nested set model!\n",
"Relational databases are not good for this kind of graph queries, so your only option is to do a bunch of query. Here is a recursive implementation:\ndef get_upline(employee):\n if self.supervisor:\n return [employee] + self.supervisor.get_upline()\n else:\n return [employee]\n\ndef get_download(employee):\n l = [employee]\n for minion in self.minion_set.all():\n l.extend(minion.get_download())\n return l\n\n"
] | [
2,
0
] | [] | [] | [
"django",
"hierarchy",
"parent_child",
"python"
] | stackoverflow_0003143898_django_hierarchy_parent_child_python.txt |
Q:
using Blobstore Python API with ajax
there is any sample showing how to use the blobstore api with ajax?
when i use forms works fine, but if i use jquery i don't know how to send the file and i get this error:
blob_info = upload_files[0]
IndexError: list index out of range
I have this code in javascript
function TestAjax()
{
var nombre="Some random name";
ajax={
type: "POST",
async:true,
//dataType:"json",
url:"{{upload_url}}",
data:"nombreEstudio="+nombre,
error: function ()
{
alert("Some error");
$("#buscando").html("");
},
success: function()
{ alert("it's ok") }
};
$.ajax(ajax);
}
When i use forms the file it's sended with a input tag (exactly like the doc's sample)
A:
I wrote a series of posts about exactly this.
A:
Somehow you still need to get the multipart form data request to the server... so when you're using forms, I assume your <form> tag has something like this on it: enctype="multipart/form-data", right?
When you're just sending a "POST" via ajax, you're losing that multipart request, which is where your file is.
There are some jQuery "ajax file upload" plugins out there that may help you out.
Hope this helps!
** EDIT **
I guess one thing I can add to this is usually ajax file uploads (on the client) are implemented by either creating a hidden iframe, and using that iframe to submit a form, or using a form and posting it via JavaScript.
| using Blobstore Python API with ajax | there is any sample showing how to use the blobstore api with ajax?
when i use forms works fine, but if i use jquery i don't know how to send the file and i get this error:
blob_info = upload_files[0]
IndexError: list index out of range
I have this code in javascript
function TestAjax()
{
var nombre="Some random name";
ajax={
type: "POST",
async:true,
//dataType:"json",
url:"{{upload_url}}",
data:"nombreEstudio="+nombre,
error: function ()
{
alert("Some error");
$("#buscando").html("");
},
success: function()
{ alert("it's ok") }
};
$.ajax(ajax);
}
When i use forms the file it's sended with a input tag (exactly like the doc's sample)
| [
"I wrote a series of posts about exactly this.\n",
"Somehow you still need to get the multipart form data request to the server... so when you're using forms, I assume your <form> tag has something like this on it: enctype=\"multipart/form-data\", right?\nWhen you're just sending a \"POST\" via ajax, you're losing that multipart request, which is where your file is.\nThere are some jQuery \"ajax file upload\" plugins out there that may help you out.\nHope this helps!\n** EDIT **\nI guess one thing I can add to this is usually ajax file uploads (on the client) are implemented by either creating a hidden iframe, and using that iframe to submit a form, or using a form and posting it via JavaScript.\n"
] | [
4,
2
] | [] | [] | [
"blobstore",
"google_app_engine",
"javascript",
"jquery",
"python"
] | stackoverflow_0003143337_blobstore_google_app_engine_javascript_jquery_python.txt |
Q:
Machine Learning Algorithm for Predicting Order of Events?
Simple machine learning question. Probably numerous ways to solve this:
There is an infinite stream of 4 possible events:
'event_1', 'event_2', 'event_4', 'event_4'
The events do not come in in completely random order. We will assume that there are some complex patterns to the order that most events come in, and the rest of the events are just random. We do not know the patterns ahead of time though.
After each event is received, I want to predict what the next event will be based on the order that events have come in in the past. So my question is: What machine learning algorithm should I use for this predictor?
The predictor will then be told what the next event actually was:
Predictor=new_predictor()
prev_event=False
while True:
event=get_event()
if prev_event is not False:
Predictor.last_event_was(prev_event)
predicted_event=Predictor.predict_next_event(event)
The question arises of how long of a history that the predictor should maintain, since maintaining infinite history will not be possible. I'll leave this up to you to answer. The answer can't be infinte though for practicality.
So I believe that the predictions will have to be done with some kind of rolling history. Adding a new event and expiring an old event should therefore be rather efficient, and not require rebuilding the entire predictor model, for example.
Specific code, instead of research papers, would add for me immense value to your responses. Python or C libraries are nice, but anything will do.
Update: And what if more than one event can happen simultaneously on each round. Does that change the solution?
A:
This is essentially a sequence prediction problem, so you want Recurrent neural networks or hidden Markov models.
If you only have a fixed time to look back, time window approaches might suffice. You take the sequence data and split it into overlapping windows of length n. (eg. you split a sequence ABCDEFG into ABC, BCD, CDE, DEF, EFG). Then you train a function approximator (e.g. neural network or linear regression) to map the first n-1 parts of that window onto the nth part.
Your predictor will not be able to look back in time longer than the size of your window. RNNs and HMMs can do so in theory, but are hard to tune or sometimes just don't work.
(State of the art RNN implementations can be found in PyBrain http://pybrain.org)
Update: Here is the pybrain code for your problem. (I haven't tested it, there might be some typos and stuff, but the overall structure should work.)
from pybrain.datasets import SequentialDataSet
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.tools.shortcuts import buildNetwork
from pybrain.structure import SigmoidLayer
INPUTS = 4
HIDDEN = 10
OUTPUTS = 4
net = buildNetwork(INPUTS, HIDDEN, OUTPUTS, hiddenclass=LSTMLayer, outclass=SigmoidLayer, recurrent=True)
ds = SequentialDataSet(INPUTS, OUTPUTS)
# your_sequences is a list of lists of tuples which each are a bitmask
# indicating the event (so 1.0 at position i if event i happens, 0.0 otherwise)
for sequence in your_sequences:
for (inpt, target) in zip(sequence, sequence[1:]):
ds.newSequence()
ds.appendLinked(inpt, target)
net.randomize()
trainer = BackpropTrainer(net, ds, learningrate=0.05, momentum=0.99)
for _ in range(1000):
print trainer.train()
This will train the recurrent network for 1000 epochs and print out the error after every epochs. Afterwards you can check for correct predictions like this:
net.reset()
for i in sequence:
next_item = net.activate(i) > 0.5
print next_item
This will print an array of booleans for every event.
A:
Rather than keeping a full history, one can keep aggregated information about the past (along with a relatively short sliding history, to be used as input to the Predictor logic).
A tentative implementation could go like this:
In a nutshell: Managing a set of Markov chains of increasing order, and grading and averaging their predictions
keep a table of individual event counts, the purpose is to calculate the probability of any of the 4 different events, without regards to any sequence.
keep a table of bigram counts, i.e. a cumulative count the events observed [so far]
Table starts empty, upon the second event observe, we can store the first bigram, with a count of 1. upond the third event, the bigram made of the 2nd and 3rd events is "added" to the table: either incrementing the count of an existing bigram or added with original count 1, as a new (never-seen-so-far) bigram. etc.
In parallel, keep a total count of bigrams in the table.
This table and the total tally allow calculating the probability of a given event, based on the one preceding event.
In a similar fashion keep a table of trigram counts, and a running tally of total trigram seen (note that this would be equal to the number of bigrams, minus one, since the first trigram is added one event after the first bigram, and after that one of each is added with each new event). This trigram table allows calculating the probability of a given event based on the two preceding events.
likewise, keep tables for N-Grams, up to, say, 10-grams (the algorithm will tell if we need to increase or decrease this).
keep an sliding windows into the last 10 events.
The above tables provide the basis for prediction; the general idea are to:
use a formula which expresses the probabilities of the next event as a weighed average of the individual probabilities based on the different N-grams.
reward the better individual N-gram length by increasing the corresponding weight in the formula; punish the worse lengths in the reverse fashion. (Beware the marginal probability of individual events needs to be taken into account lest we favor N-grams which happen to predict the most frequent events, regardless of the relative poor predicting value associated with them them)
Once the system has "seen" enough events, see the current values for the weights associated with the long N-Grams, and if these are relatively high, consider adding tables to keep aggregate info about bigger N-Grams. (This unfortunately hurts the algorightm both in terms of space and time)
There can be several variations on the general logic described above. In particular in the choice of the particular metric used to "grade" the quality of prediction of the individual N-Gram lengths.
Other considerations should be put with regards to detecting and adapting to possible shifts in the events distribution (the above assumes a generally ergodic event source). One possible approach is to use two sets of tables (combining the probabilities accordingly), and periodically dropping the contents of all tables of one of the sets. Choosing the right period for these resets is a tricky business, essentially balancing the need for statistically significant volumes of history and the need for short enough period lest me miss on the shorter modulations...
A:
The question arises of how long of a history that the predictor should maintain
The only answer is "it depends".
It depends on how accurate this needs to be. I don't believe this strategy could ever be 100% accurate even with an infinite history. Try out a history of 10 and you'll get x% accuracy, then try 100 and you'll get y% accuracy, etc etc...
Eventually you should find either the system is as accurate as you desire it to be or you will find the rise in accuracy will not be worth the increase in history length (and increased memory usage, processing time etc...). At this point either job done, or you need to find a new strategy.
For what it is worth i think looking into a simple "soft" neural net might be a better plan.
A:
We just studied about branch-predictors in computer architecture (Because the processor would take too long to actually evaluate a condition if(EXPRESSION), it tries to 'guess' and save some time that way). I am sure more research has been done in this area, but that's all I can think of at the moment.
I haven't seen a unique setup like yours, so I think you might need to do some preliminary experimentation on your own. Try running your solution for X number of seconds with a history of N slots, what is the correctness ratio? And compare that with the same fixed X and varying N history slots to try to find the best memory-history ratio (graphing them out ).
If more than one event can happen simulataneously... that's a little mind bending, there has to be some constraints there : what if infinite number of events happen at a time? Uhoh, that's computationally impossible for you. I'd try the same approach as just one event at a time, except where the predictor is enabled predict multiple events at a time.
A:
Processors use a few really lightweight tricks to predict whether a branch statement will branch or not. This helps them with efficient pipe-lining. They may not be as general as Markov models for instance, but they are interesting because of their simplicity. Here is the Wikipedia article on branch prediction. See the Saturating Counter, and the Two-Level Adaptive Predictor
| Machine Learning Algorithm for Predicting Order of Events? | Simple machine learning question. Probably numerous ways to solve this:
There is an infinite stream of 4 possible events:
'event_1', 'event_2', 'event_4', 'event_4'
The events do not come in in completely random order. We will assume that there are some complex patterns to the order that most events come in, and the rest of the events are just random. We do not know the patterns ahead of time though.
After each event is received, I want to predict what the next event will be based on the order that events have come in in the past. So my question is: What machine learning algorithm should I use for this predictor?
The predictor will then be told what the next event actually was:
Predictor=new_predictor()
prev_event=False
while True:
event=get_event()
if prev_event is not False:
Predictor.last_event_was(prev_event)
predicted_event=Predictor.predict_next_event(event)
The question arises of how long of a history that the predictor should maintain, since maintaining infinite history will not be possible. I'll leave this up to you to answer. The answer can't be infinte though for practicality.
So I believe that the predictions will have to be done with some kind of rolling history. Adding a new event and expiring an old event should therefore be rather efficient, and not require rebuilding the entire predictor model, for example.
Specific code, instead of research papers, would add for me immense value to your responses. Python or C libraries are nice, but anything will do.
Update: And what if more than one event can happen simultaneously on each round. Does that change the solution?
| [
"This is essentially a sequence prediction problem, so you want Recurrent neural networks or hidden Markov models.\nIf you only have a fixed time to look back, time window approaches might suffice. You take the sequence data and split it into overlapping windows of length n. (eg. you split a sequence ABCDEFG into ABC, BCD, CDE, DEF, EFG). Then you train a function approximator (e.g. neural network or linear regression) to map the first n-1 parts of that window onto the nth part.\nYour predictor will not be able to look back in time longer than the size of your window. RNNs and HMMs can do so in theory, but are hard to tune or sometimes just don't work.\n(State of the art RNN implementations can be found in PyBrain http://pybrain.org)\nUpdate: Here is the pybrain code for your problem. (I haven't tested it, there might be some typos and stuff, but the overall structure should work.)\nfrom pybrain.datasets import SequentialDataSet\nfrom pybrain.supervised.trainers import BackpropTrainer\nfrom pybrain.tools.shortcuts import buildNetwork\nfrom pybrain.structure import SigmoidLayer\n\nINPUTS = 4\nHIDDEN = 10\nOUTPUTS = 4\n\nnet = buildNetwork(INPUTS, HIDDEN, OUTPUTS, hiddenclass=LSTMLayer, outclass=SigmoidLayer, recurrent=True)\n\nds = SequentialDataSet(INPUTS, OUTPUTS)\n\n# your_sequences is a list of lists of tuples which each are a bitmask\n# indicating the event (so 1.0 at position i if event i happens, 0.0 otherwise)\n\nfor sequence in your_sequences:\n for (inpt, target) in zip(sequence, sequence[1:]):\n ds.newSequence()\n ds.appendLinked(inpt, target)\n\nnet.randomize()\n\ntrainer = BackpropTrainer(net, ds, learningrate=0.05, momentum=0.99)\nfor _ in range(1000):\n print trainer.train()\n\nThis will train the recurrent network for 1000 epochs and print out the error after every epochs. Afterwards you can check for correct predictions like this:\nnet.reset()\nfor i in sequence:\n next_item = net.activate(i) > 0.5\n print next_item\n\nThis will print an array of booleans for every event.\n",
"Rather than keeping a full history, one can keep aggregated information about the past (along with a relatively short sliding history, to be used as input to the Predictor logic).\nA tentative implementation could go like this:\nIn a nutshell: Managing a set of Markov chains of increasing order, and grading and averaging their predictions\n\nkeep a table of individual event counts, the purpose is to calculate the probability of any of the 4 different events, without regards to any sequence.\nkeep a table of bigram counts, i.e. a cumulative count the events observed [so far]\nTable starts empty, upon the second event observe, we can store the first bigram, with a count of 1. upond the third event, the bigram made of the 2nd and 3rd events is \"added\" to the table: either incrementing the count of an existing bigram or added with original count 1, as a new (never-seen-so-far) bigram. etc.\nIn parallel, keep a total count of bigrams in the table.\nThis table and the total tally allow calculating the probability of a given event, based on the one preceding event. \nIn a similar fashion keep a table of trigram counts, and a running tally of total trigram seen (note that this would be equal to the number of bigrams, minus one, since the first trigram is added one event after the first bigram, and after that one of each is added with each new event). This trigram table allows calculating the probability of a given event based on the two preceding events.\nlikewise, keep tables for N-Grams, up to, say, 10-grams (the algorithm will tell if we need to increase or decrease this).\nkeep an sliding windows into the last 10 events.\nThe above tables provide the basis for prediction; the general idea are to:\n\n\nuse a formula which expresses the probabilities of the next event as a weighed average of the individual probabilities based on the different N-grams. \nreward the better individual N-gram length by increasing the corresponding weight in the formula; punish the worse lengths in the reverse fashion. (Beware the marginal probability of individual events needs to be taken into account lest we favor N-grams which happen to predict the most frequent events, regardless of the relative poor predicting value associated with them them)\nOnce the system has \"seen\" enough events, see the current values for the weights associated with the long N-Grams, and if these are relatively high, consider adding tables to keep aggregate info about bigger N-Grams. (This unfortunately hurts the algorightm both in terms of space and time)\n\n\nThere can be several variations on the general logic described above. In particular in the choice of the particular metric used to \"grade\" the quality of prediction of the individual N-Gram lengths. \nOther considerations should be put with regards to detecting and adapting to possible shifts in the events distribution (the above assumes a generally ergodic event source). One possible approach is to use two sets of tables (combining the probabilities accordingly), and periodically dropping the contents of all tables of one of the sets. Choosing the right period for these resets is a tricky business, essentially balancing the need for statistically significant volumes of history and the need for short enough period lest me miss on the shorter modulations...\n",
"\nThe question arises of how long of a history that the predictor should maintain\n\nThe only answer is \"it depends\".\nIt depends on how accurate this needs to be. I don't believe this strategy could ever be 100% accurate even with an infinite history. Try out a history of 10 and you'll get x% accuracy, then try 100 and you'll get y% accuracy, etc etc...\nEventually you should find either the system is as accurate as you desire it to be or you will find the rise in accuracy will not be worth the increase in history length (and increased memory usage, processing time etc...). At this point either job done, or you need to find a new strategy.\nFor what it is worth i think looking into a simple \"soft\" neural net might be a better plan.\n",
"We just studied about branch-predictors in computer architecture (Because the processor would take too long to actually evaluate a condition if(EXPRESSION), it tries to 'guess' and save some time that way). I am sure more research has been done in this area, but that's all I can think of at the moment.\nI haven't seen a unique setup like yours, so I think you might need to do some preliminary experimentation on your own. Try running your solution for X number of seconds with a history of N slots, what is the correctness ratio? And compare that with the same fixed X and varying N history slots to try to find the best memory-history ratio (graphing them out ). \nIf more than one event can happen simulataneously... that's a little mind bending, there has to be some constraints there : what if infinite number of events happen at a time? Uhoh, that's computationally impossible for you. I'd try the same approach as just one event at a time, except where the predictor is enabled predict multiple events at a time.\n",
"Processors use a few really lightweight tricks to predict whether a branch statement will branch or not. This helps them with efficient pipe-lining. They may not be as general as Markov models for instance, but they are interesting because of their simplicity. Here is the Wikipedia article on branch prediction. See the Saturating Counter, and the Two-Level Adaptive Predictor\n"
] | [
23,
13,
0,
0,
0
] | [] | [] | [
"compression",
"evolutionary_algorithm",
"machine_learning",
"neural_network",
"python"
] | stackoverflow_0002524608_compression_evolutionary_algorithm_machine_learning_neural_network_python.txt |
Q:
simple fetch is really slow
I am fetching all the instances for a given linkname but I want to call all their values(rating2) to perform a calculation, I debugged and all my time is in the query and fetch lines, I only have a table with 100 items and it is taking 2 seconds!!!!! How can it be this slow to fetch a few items out of a 100 item table and how can I speed this up? I am running this in the command console and calling the appengine_console.py and running my script that way, is it possible that would cause any sort of delay?
class LinkRating2(db.Model):
user = db.StringProperty()
link = db.StringProperty()
rating2 = db.FloatProperty()
def sim_distance(link1,link2,tabl):
# Get the list of shared_items
si={}
query = tabl.all()
query2 = tabl.all()
a = query.filter('link = ', link1)
b = query2.filter('link = ', link2)
adic ={}
bdic= {}
aa = a.fetch(10000)
bb = b.fetch(10000)
UPDATE/EDIT
Hi guys, I put a call to the sim distance function on my main loading page, I am calling sim_distance thousands of times in another function and to my amazement it is taking only 15ms to execute! Here is what I don't understand, why does it take 2 seconds per call when I am running it in the appengine_console.py in the command window? I took an hour to run in the cmd window but instantaneously about when running it from explorer window.
A:
Have you tried using appstats? That will give you a breakdown on what parts of your page are specifically taking the most time, based on RPC information.
| simple fetch is really slow | I am fetching all the instances for a given linkname but I want to call all their values(rating2) to perform a calculation, I debugged and all my time is in the query and fetch lines, I only have a table with 100 items and it is taking 2 seconds!!!!! How can it be this slow to fetch a few items out of a 100 item table and how can I speed this up? I am running this in the command console and calling the appengine_console.py and running my script that way, is it possible that would cause any sort of delay?
class LinkRating2(db.Model):
user = db.StringProperty()
link = db.StringProperty()
rating2 = db.FloatProperty()
def sim_distance(link1,link2,tabl):
# Get the list of shared_items
si={}
query = tabl.all()
query2 = tabl.all()
a = query.filter('link = ', link1)
b = query2.filter('link = ', link2)
adic ={}
bdic= {}
aa = a.fetch(10000)
bb = b.fetch(10000)
UPDATE/EDIT
Hi guys, I put a call to the sim distance function on my main loading page, I am calling sim_distance thousands of times in another function and to my amazement it is taking only 15ms to execute! Here is what I don't understand, why does it take 2 seconds per call when I am running it in the appengine_console.py in the command window? I took an hour to run in the cmd window but instantaneously about when running it from explorer window.
| [
"Have you tried using appstats? That will give you a breakdown on what parts of your page are specifically taking the most time, based on RPC information.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003143969_google_app_engine_python.txt |
Q:
Ruby version of to String method
This question is about formatting ruby's strings.
In Python, built-in data structures have a built-in to-string method, and so when a variable is printed, the string is conveniently formatted to be reflective of the data structure used. For example:
>>>$ python
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
$>>> a = [1,2,3,4]
$>>> str(a)
'[1, 2, 3, 4]'
$>>> print a
[1, 2, 3, 4]
$>>> d = { "a":"a", "b":"b", 1:5 }
$>>> str(d)
"{'a': 'a', 1: 5, 'b': 'b'}"
$>>> print d
{'a': 'a', 1: 5, 'b': 'b'}
$>>> x = [1, 23, 4]
$>>> print x
[1, 23, 4]
notice that when i print a, the value is [1, 2, 3, 4]
However, in ruby, when i try to do the same things, i get this result:
>>>$ irb
irb(main):001:0> x = [1,23,4]
=> [1, 23, 4]
irb(main):002:0> x.to_s
=> "1234"
irb(main):003:0> puts x
1
23
4
=> nil
irb(main):004:0> print x
1234=> nil
irb(main):005:0> h = { "a" => "a", 1 => 5, 'b'=>'b' }
=> {"a"=>"a", "b"=>"b", 1=>5}
irb(main):006:0> print h
aabb15=> nil
irb(main):007:0> h.to_s
=> "aabb15"
irb(main):008:0> puts h
aabb15
=> nil
irb(main):009:0>
As you can see, there is no formatting with the to_s method. Furthermore, there's a uniqueness problem if i call to_s on [1,2,3,4] and [1,23,4] and [1234] because the to_s clumps all elements together so they all end up being "1234". I know that i can try to emulate the python built-in to-string methods for every native data structure by overriding the to_s method ( "[" + a.join(",") + "]" #just for arrays), but i was wondering if there is a better alternative since hacking it would seem to break the convention-over-configuration concept.
So is there a ruby equivalent of python's built-in to-string method?
A:
[1,23,4].inspect #=> "[1, 23, 4]"
p [1,23,4] # Same as puts [1,23,4].inspect
A:
In Ruby, there are four methods that are typically available for getting a string representation of an object.
#to_str: this is part of Ruby's standard type conversion protocols (similar to to_int, to_ary, to_float, …). It is used if and only if the object really actually is a string but for whatever reason is not an instance of the String class. It is extremely unusual. In fact, in the entire core library, there is only the no-op implementation in the String class itself.
#to_s: this is also part of Ruby's standard type conversion protocols (similar to to_i, to_a, to_f, …). It is used if the object has some sort of sensible string representation. It does not actually need to be a string. Almost all objects should respond to this.
Kernel#String(obj): this is also part of Ruby's standard type conversion protocols (similar to Kernel#Integer(obj), Kernel#Array(obj), Kernel#Float(obj), …). It is the same as obj.to_s.
#inspect: it is supposed to return a human-readable description of the object for debugging purposes. In other words: it is for inspecting an object (duh).
There are three methods for printing objects:
Kernel#print(obj, ...): prints all objs separated by $, and terminated by $\. If an obj is not a String, print will call obj.to_s first.
Kernel#puts(obj, ...): is basically equivalent to $stdout.puts(obj, ...). It also prints the objs, but it typically separates them with newlines. However, it also has some special case behavior, in particular it treats arrays specially by printing each item on a new line.
Kernel#p(obj, ...): similar to puts but calls #inspect on all objs.
In addition to those, there is also the pp (pretty print) library in the standard library which adds a Kernel#pp(obj, ...) method.
Then, there's the awesome_print library and hirb.
A:
Use inspect
irb(main):001:0> h = { "a" => "a", 1 => 5, 'b'=>'b' }
=> {"a"=>"a", "b"=>"b", 1=>5}
irb(main):003:0> puts h.inspect
{"a"=>"a", "b"=>"b", 1=>5}
=> nil
irb(main):004:0>
| Ruby version of to String method | This question is about formatting ruby's strings.
In Python, built-in data structures have a built-in to-string method, and so when a variable is printed, the string is conveniently formatted to be reflective of the data structure used. For example:
>>>$ python
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
$>>> a = [1,2,3,4]
$>>> str(a)
'[1, 2, 3, 4]'
$>>> print a
[1, 2, 3, 4]
$>>> d = { "a":"a", "b":"b", 1:5 }
$>>> str(d)
"{'a': 'a', 1: 5, 'b': 'b'}"
$>>> print d
{'a': 'a', 1: 5, 'b': 'b'}
$>>> x = [1, 23, 4]
$>>> print x
[1, 23, 4]
notice that when i print a, the value is [1, 2, 3, 4]
However, in ruby, when i try to do the same things, i get this result:
>>>$ irb
irb(main):001:0> x = [1,23,4]
=> [1, 23, 4]
irb(main):002:0> x.to_s
=> "1234"
irb(main):003:0> puts x
1
23
4
=> nil
irb(main):004:0> print x
1234=> nil
irb(main):005:0> h = { "a" => "a", 1 => 5, 'b'=>'b' }
=> {"a"=>"a", "b"=>"b", 1=>5}
irb(main):006:0> print h
aabb15=> nil
irb(main):007:0> h.to_s
=> "aabb15"
irb(main):008:0> puts h
aabb15
=> nil
irb(main):009:0>
As you can see, there is no formatting with the to_s method. Furthermore, there's a uniqueness problem if i call to_s on [1,2,3,4] and [1,23,4] and [1234] because the to_s clumps all elements together so they all end up being "1234". I know that i can try to emulate the python built-in to-string methods for every native data structure by overriding the to_s method ( "[" + a.join(",") + "]" #just for arrays), but i was wondering if there is a better alternative since hacking it would seem to break the convention-over-configuration concept.
So is there a ruby equivalent of python's built-in to-string method?
| [
"[1,23,4].inspect #=> \"[1, 23, 4]\"\np [1,23,4] # Same as puts [1,23,4].inspect\n\n",
"In Ruby, there are four methods that are typically available for getting a string representation of an object.\n\n#to_str: this is part of Ruby's standard type conversion protocols (similar to to_int, to_ary, to_float, …). It is used if and only if the object really actually is a string but for whatever reason is not an instance of the String class. It is extremely unusual. In fact, in the entire core library, there is only the no-op implementation in the String class itself.\n#to_s: this is also part of Ruby's standard type conversion protocols (similar to to_i, to_a, to_f, …). It is used if the object has some sort of sensible string representation. It does not actually need to be a string. Almost all objects should respond to this.\nKernel#String(obj): this is also part of Ruby's standard type conversion protocols (similar to Kernel#Integer(obj), Kernel#Array(obj), Kernel#Float(obj), …). It is the same as obj.to_s.\n#inspect: it is supposed to return a human-readable description of the object for debugging purposes. In other words: it is for inspecting an object (duh).\n\nThere are three methods for printing objects:\n\nKernel#print(obj, ...): prints all objs separated by $, and terminated by $\\. If an obj is not a String, print will call obj.to_s first.\nKernel#puts(obj, ...): is basically equivalent to $stdout.puts(obj, ...). It also prints the objs, but it typically separates them with newlines. However, it also has some special case behavior, in particular it treats arrays specially by printing each item on a new line.\nKernel#p(obj, ...): similar to puts but calls #inspect on all objs.\n\nIn addition to those, there is also the pp (pretty print) library in the standard library which adds a Kernel#pp(obj, ...) method.\nThen, there's the awesome_print library and hirb.\n",
"Use inspect\nirb(main):001:0> h = { \"a\" => \"a\", 1 => 5, 'b'=>'b' }\n=> {\"a\"=>\"a\", \"b\"=>\"b\", 1=>5}\nirb(main):003:0> puts h.inspect\n{\"a\"=>\"a\", \"b\"=>\"b\", 1=>5}\n=> nil\nirb(main):004:0>\n\n"
] | [
9,
9,
0
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0003144265_python_ruby.txt |
Q:
Accepting only numbers as input in Python
Is there a way to accept only numbers in Python, say like using raw_input()?
I know I can always get the input and catch a ValueError exception, but I was interested in knowing whether there was someway I could force the prompt to accept only numbers and freeze on any other input.
A:
From the docs:
How do I get a single keypress at a time?
For Unix variants: There are several
solutions. It’s straightforward to do
this using curses, but curses is a
fairly large module to learn. Here’s a
solution without curses:
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
print "Got character", `c`
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
You need the termios and the fcntl
module for any of this to work, and
I’ve only tried it on Linux, though it
should work elsewhere. In this code,
characters are read and printed one at
a time.
termios.tcsetattr() turns off stdin’s
echoing and disables canonical mode.
fcntl.fnctl() is used to obtain
stdin’s file descriptor flags and
modify them for non-blocking mode.
Since reading stdin when it is empty
results in an IOError, this error is
caught and ignored.
Using this, you could grab the character, check if it's a number, and then display it. I haven't tried it myself, though.
A:
As far as I know, no. I've never heard of such a thing being possible with a terminal, in Python or any other language.
The closest way I can think of to fake it would be to put the terminal in silent mode (so that input characters are not echoed) and unbuffered mode (so that you get each character typed as it's typed, without waiting for the end of the line), then read each input character one by one; if it's a digit, print it and append it to a string, otherwise discard it. But I'm not even sure if the terminal would allow you to do that.
| Accepting only numbers as input in Python | Is there a way to accept only numbers in Python, say like using raw_input()?
I know I can always get the input and catch a ValueError exception, but I was interested in knowing whether there was someway I could force the prompt to accept only numbers and freeze on any other input.
| [
"From the docs:\n\nHow do I get a single keypress at a time?\nFor Unix variants: There are several\n solutions. It’s straightforward to do\n this using curses, but curses is a\n fairly large module to learn. Here’s a\n solution without curses:\n\nimport termios, fcntl, sys, os\nfd = sys.stdin.fileno()\n\noldterm = termios.tcgetattr(fd)\nnewattr = termios.tcgetattr(fd)\nnewattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO\ntermios.tcsetattr(fd, termios.TCSANOW, newattr)\n\noldflags = fcntl.fcntl(fd, fcntl.F_GETFL)\nfcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)\n\ntry:\n while 1:\n try:\n c = sys.stdin.read(1)\n print \"Got character\", `c`\n except IOError: pass\nfinally:\n termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)\n fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)\n\n\nYou need the termios and the fcntl\n module for any of this to work, and\n I’ve only tried it on Linux, though it\n should work elsewhere. In this code,\n characters are read and printed one at\n a time.\ntermios.tcsetattr() turns off stdin’s\n echoing and disables canonical mode.\n fcntl.fnctl() is used to obtain\n stdin’s file descriptor flags and\n modify them for non-blocking mode.\n Since reading stdin when it is empty\n results in an IOError, this error is\n caught and ignored.\n\nUsing this, you could grab the character, check if it's a number, and then display it. I haven't tried it myself, though.\n",
"As far as I know, no. I've never heard of such a thing being possible with a terminal, in Python or any other language.\nThe closest way I can think of to fake it would be to put the terminal in silent mode (so that input characters are not echoed) and unbuffered mode (so that you get each character typed as it's typed, without waiting for the end of the line), then read each input character one by one; if it's a digit, print it and append it to a string, otherwise discard it. But I'm not even sure if the terminal would allow you to do that.\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003144529_python.txt |
Q:
a indexing question of ndarray
for example, there is a matrix:
import numpy as np
A = np.array([[ 8. , -6. , 2. ],
[-0.5, 8. , -6. ],
[ 0.5, -0.5, 2. ]])
It's a LU Decomposition (Doolittle’s decomposition) result.(A = [L\U])
I want to get L and U from A.
U should be:
U = np.array([[ 8., -6., 2.],
[ 0., 8., -6.],
[ 0., 0., 2.]])
L should be:
L = np.array([[ 1. , 0. , 0. ],
[-0.5, 1. , 0. ],
[ 0.5, -0.5, 1.]])
then, want I want to know is how to get the L and U from A?
A:
You don't need any index manipulation. Just use tril, triu and identity functions:
import numpy as np
A = np.array([[ 8. , -6. , 2. ],
[-0.5, 8. , -6. ],
[ 0.5, -0.5, 2. ]])
U = np.triu(A)
#[[ 8. -6. 2.]
# [-0. 8. -6.]
# [ 0. -0. 2.]]
L = np.tril(A, k=-1) + np.identity(3)
#[[ 1. 0. 0. ]
# [-0.5 1. 0. ]
# [ 0.5 -0.5 1. ]]
A:
What you want doesn't look like LU-decomposition to me,
http://en.wikipedia.org/wiki/LU_decomposition
>>> U_ = np.array([[ 8., -6., 2.],
[ 0., 8., -6.],
[ 0., 0., 2.]])
>>> L_ = np.array([[ 1. , 0. , 0. ],
[-0.5, 1. , 0. ],
[ 0.5, -0.5, 1.]])
>>> np.dot(L_, U_)
array([[ 8., -6., 2.],
[ -4., 11., -7.],
[ 4., -7., 6.]])
LU decomposition is available in scipy.linalg
>>> A = np.array([[ 8. , -6. , 2. ], [-0.5, 8. , -6. ], [ 0.5, -0.5, 2. ]])
>>> import scipy.linalg as spla
>>> P, L, U = spla.lu(A)
>>> L
array([[ 1. , 0. , 0. ],
[-0.0625 , 1. , 0. ],
[ 0.0625 , -0.01639344, 1. ]])
>>> U
array([[ 8. , -6. , 2. ],
[ 0. , 7.625 , -5.875 ],
[ 0. , 0. , 1.77868852]])
>>> np.dot(L, U)
array([[ 8. , -6. , 2. ],
[-0.5, 8. , -6. ],
[ 0.5, -0.5, 2. ]])
| a indexing question of ndarray | for example, there is a matrix:
import numpy as np
A = np.array([[ 8. , -6. , 2. ],
[-0.5, 8. , -6. ],
[ 0.5, -0.5, 2. ]])
It's a LU Decomposition (Doolittle’s decomposition) result.(A = [L\U])
I want to get L and U from A.
U should be:
U = np.array([[ 8., -6., 2.],
[ 0., 8., -6.],
[ 0., 0., 2.]])
L should be:
L = np.array([[ 1. , 0. , 0. ],
[-0.5, 1. , 0. ],
[ 0.5, -0.5, 1.]])
then, want I want to know is how to get the L and U from A?
| [
"You don't need any index manipulation. Just use tril, triu and identity functions:\nimport numpy as np\nA = np.array([[ 8. , -6. , 2. ], \n [-0.5, 8. , -6. ], \n [ 0.5, -0.5, 2. ]])\n\nU = np.triu(A)\n\n#[[ 8. -6. 2.]\n# [-0. 8. -6.]\n# [ 0. -0. 2.]]\n\nL = np.tril(A, k=-1) + np.identity(3)\n\n#[[ 1. 0. 0. ]\n# [-0.5 1. 0. ]\n# [ 0.5 -0.5 1. ]]\n\n",
"What you want doesn't look like LU-decomposition to me, \nhttp://en.wikipedia.org/wiki/LU_decomposition\n>>> U_ = np.array([[ 8., -6., 2.],\n [ 0., 8., -6.],\n [ 0., 0., 2.]])\n>>> L_ = np.array([[ 1. , 0. , 0. ],\n [-0.5, 1. , 0. ],\n [ 0.5, -0.5, 1.]])\n>>> np.dot(L_, U_)\narray([[ 8., -6., 2.],\n [ -4., 11., -7.],\n [ 4., -7., 6.]])\n\nLU decomposition is available in scipy.linalg\n>>> A = np.array([[ 8. , -6. , 2. ], [-0.5, 8. , -6. ], [ 0.5, -0.5, 2. ]])\n>>> import scipy.linalg as spla\n>>> P, L, U = spla.lu(A)\n>>> L\narray([[ 1. , 0. , 0. ],\n [-0.0625 , 1. , 0. ],\n [ 0.0625 , -0.01639344, 1. ]])\n>>> U\narray([[ 8. , -6. , 2. ],\n [ 0. , 7.625 , -5.875 ],\n [ 0. , 0. , 1.77868852]])\n>>> np.dot(L, U)\narray([[ 8. , -6. , 2. ],\n [-0.5, 8. , -6. ],\n [ 0.5, -0.5, 2. ]])\n\n"
] | [
2,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003107991_numpy_python.txt |
Q:
QSvgRenderer segmentation fault
I realize specific questions like this aren't great, but I've spent several days trying to puzzle this out. Hopefully someone here can help.
This python code using PyQt4 causes a segmentation fault:
data = """<?xml version="1.0" ?>
<svg height="1000" width="2000">
<text>blah</text>
</svg>"""
svg = QSvgRenderer(QByteArray(data))
qim = QImage(int(width), int(height), QImage.Format_ARGB32)
painter = QPainter()
painter.begin(qim)
svg.render(painter)
painter.end()
qim.save('test2.png')
The line that causes the fault is svg.render(painter).
The fault points at libQtGui.so (so something in QPainter or QImage).
svg.isValid() returns True, and qim.isNull() returns False.
A:
Try making it draw on a QPixmap instead of a QImage.
Qt does cause segfaults once in a while, I usually just code around them.
Maybe you could rasterize this SVG in Gimp and just load that.
A:
With only a minor change to make that run (defining width and height), it works for me. Note that I don't see any text but if I swap out data to something I know is valid it works perfectly. Here's my full code:
#!/usr/bin/env python
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtSvg import *
import sys
if __name__ == '__main__':
app = QApplication(sys.argv)
data = """... (my valid svg) ..."""
svg = QSvgRenderer(QByteArray(data))
qim = QImage(int(2000), int(1000), QImage.Format_ARGB32)
painter = QPainter()
painter.begin(qim)
svg.render(painter)
painter.end()
print "null:", qim.isNull()
qim.save('test2.png')
| QSvgRenderer segmentation fault | I realize specific questions like this aren't great, but I've spent several days trying to puzzle this out. Hopefully someone here can help.
This python code using PyQt4 causes a segmentation fault:
data = """<?xml version="1.0" ?>
<svg height="1000" width="2000">
<text>blah</text>
</svg>"""
svg = QSvgRenderer(QByteArray(data))
qim = QImage(int(width), int(height), QImage.Format_ARGB32)
painter = QPainter()
painter.begin(qim)
svg.render(painter)
painter.end()
qim.save('test2.png')
The line that causes the fault is svg.render(painter).
The fault points at libQtGui.so (so something in QPainter or QImage).
svg.isValid() returns True, and qim.isNull() returns False.
| [
"Try making it draw on a QPixmap instead of a QImage.\nQt does cause segfaults once in a while, I usually just code around them.\nMaybe you could rasterize this SVG in Gimp and just load that.\n",
"With only a minor change to make that run (defining width and height), it works for me. Note that I don't see any text but if I swap out data to something I know is valid it works perfectly. Here's my full code:\n#!/usr/bin/env python\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtSvg import *\nimport sys\n\nif __name__ == '__main__':\n\n app = QApplication(sys.argv)\n\n data = \"\"\"... (my valid svg) ...\"\"\"\n \n svg = QSvgRenderer(QByteArray(data))\n qim = QImage(int(2000), int(1000), QImage.Format_ARGB32)\n painter = QPainter()\n\n painter.begin(qim)\n svg.render(painter)\n painter.end()\n\n print \"null:\", qim.isNull()\n qim.save('test2.png')\n\n"
] | [
0,
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qt",
"segmentation_fault"
] | stackoverflow_0003144361_pyqt_pyqt4_python_qt_segmentation_fault.txt |
Q:
Python question about time spent
I would like to know that how much time a particular function has spent during the duration of the program which involves recursion, what is the best way of doing it?
Thank you
A:
The best way would be to run some benchmark tests (to test individual functions) or Profiling (to test an entire application/program). Python comes with built-in Profilers.
Alternatively, you could go back to the very basics by simply setting a start time at the beginning of the program, and, at the end of the program, subtracting the current time from the start time. This is basically very simple Benchmarking.
Here is an implementation from the an answer from the linked question:
import time
start = time.time()
do_long_code()
print "it took", time.time() - start, "seconds."
Python has something for benchmarking included in its standard library, as well.
From the example give on the page:
def test():
"Time me"
L = []
for i in range(100):
L.append(i)
if __name__=='__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
A:
Use the profiler!
python -m cProfile -o prof yourscript.py
runsnake prof
runsnake is a nice tool for looking at the profiling output. You can of course use other tools.
More on the Profiler here: http://docs.python.org/library/profile.html
| Python question about time spent | I would like to know that how much time a particular function has spent during the duration of the program which involves recursion, what is the best way of doing it?
Thank you
| [
"The best way would be to run some benchmark tests (to test individual functions) or Profiling (to test an entire application/program). Python comes with built-in Profilers.\nAlternatively, you could go back to the very basics by simply setting a start time at the beginning of the program, and, at the end of the program, subtracting the current time from the start time. This is basically very simple Benchmarking.\nHere is an implementation from the an answer from the linked question:\nimport time\nstart = time.time()\ndo_long_code()\nprint \"it took\", time.time() - start, \"seconds.\"\n\nPython has something for benchmarking included in its standard library, as well.\nFrom the example give on the page:\ndef test():\n \"Time me\"\n L = []\n for i in range(100):\n L.append(i)\n\nif __name__=='__main__':\n from timeit import Timer\n t = Timer(\"test()\", \"from __main__ import test\")\n print t.timeit()\n\n",
"Use the profiler!\npython -m cProfile -o prof yourscript.py\nrunsnake prof\n\nrunsnake is a nice tool for looking at the profiling output. You can of course use other tools.\nMore on the Profiler here: http://docs.python.org/library/profile.html\n"
] | [
15,
4
] | [] | [] | [
"python",
"timedelta"
] | stackoverflow_0003144898_python_timedelta.txt |
Q:
Using named arguments with variable length un-named arguments in Python
I apologize if this question has already been asked/answered, I would have expected that to be the case but was unable to find any related questions...
I'd like to create a python function that takes two mandatory arguments, one named argument, and some unknown number of other, non-named arguments as so:
def my_function(arg1, arg2, arg3=None, *other_args):
pass
Is this possible in Python 2.x?
Can a function accept named arguments in addition to a variable length argument list?
I believe the answer is 'no', in which case I'm thinking the only solution available to me would be something similar to the following:
def my_function(arg1, arg2, **kwargs):
arg3 = kwargs["arg3"]
other_args = kwargs["other_args"]
Is that correct?
A:
That syntax is certainly valid, but I think you mean can you write the function signature such that arg3 is only bound if it's used as a named parameter (e.g. my_function(1, 2, arg3 = 3)), and otherwise to have all arguments past the first two be caught by *other_args, in which case the answer is no. Optional arguments can be specified by naming, but they're also positional like normal arguments and are filled in if enough parameters are available, before resorting to catch-alls like *args or **kwargs.
I would probably write it exactly as you did, using keyword arguments
| Using named arguments with variable length un-named arguments in Python | I apologize if this question has already been asked/answered, I would have expected that to be the case but was unable to find any related questions...
I'd like to create a python function that takes two mandatory arguments, one named argument, and some unknown number of other, non-named arguments as so:
def my_function(arg1, arg2, arg3=None, *other_args):
pass
Is this possible in Python 2.x?
Can a function accept named arguments in addition to a variable length argument list?
I believe the answer is 'no', in which case I'm thinking the only solution available to me would be something similar to the following:
def my_function(arg1, arg2, **kwargs):
arg3 = kwargs["arg3"]
other_args = kwargs["other_args"]
Is that correct?
| [
"That syntax is certainly valid, but I think you mean can you write the function signature such that arg3 is only bound if it's used as a named parameter (e.g. my_function(1, 2, arg3 = 3)), and otherwise to have all arguments past the first two be caught by *other_args, in which case the answer is no. Optional arguments can be specified by naming, but they're also positional like normal arguments and are filled in if enough parameters are available, before resorting to catch-alls like *args or **kwargs.\nI would probably write it exactly as you did, using keyword arguments\n"
] | [
1
] | [] | [] | [
"keyword_argument",
"named_parameters",
"python",
"variadic_functions"
] | stackoverflow_0003145241_keyword_argument_named_parameters_python_variadic_functions.txt |
Q:
Another Python Scope Question - losing information going into if statement
Not sure if I'm missing something obvious, but here's what is happening:
I have a python 2.4.3 script that contains several RegEx objects. Below one of the regex objects is searching for all matches in a string (tMatchList). Even if tMatchList is not null, it is printing an empty set after the 'if p:' step. This behavior occurs even if it prints correctly before the 'if p:' step. I thought it may have been a scope issue, but everything is declared & contained within one function. I'm not quite seeing how the 'if p:' step is not able to see tMatchList. I am able to print tMatchList after the if statement as well.
tMatchList = []
for lines in r:
linecount += 1
tMatchList = self._testReplacePDFTag.findall(lines)
p = self._pdfPathRegex.search(lines)
print tMatchList #tMatchList is printing just fine here if it has any elements
if p:
print tMatchList #now it's empty,
#even if it printed elements in prior statement
lines = .....
else:
<something else gets done>
print tMatchList #now it prints again
Including entire function definition for those who would like to see it....
def FindFilesAndModifyPDFTag(self, inRootDirArg, inRollBackBool):
for root, dirs, files in os.walk(inRootDirArg):
for d in dirs:
if d.startswith('.'):#excludes directories that start with '.'
continue
for file in files:
if os.path.splitext(file)[1] == self._fileExt:
#Backup original. just do it
shutil.copy2(os.path.join(root, file), os.path.join(root, file)+"~")
r = open(os.path.join(root, file)+"~", "r")
f = open(os.path.join(root, file), "w")
linecount = 0
tMatchList = []
for lines in r:
linecount += 1
tMatchList = self._testReplacePDFTag.findall(lines)
t = self._testReplacePDFTag.search(lines)
#find pdf path(s) in line
pMatchList = self._pdfPathRegex.findall(lines)
p = self._pdfPathRegex.search(lines)
#fix the pdf tracking code
print id(tMatchList), "BEFORE"
if p:
print id(tMatchList), "INSIDE"
lines = self.processPDFTagLine(pMatchList, lines, linecount, file, tMatchList)
else:
lines = self.processCheckMetaTag(lines, linecount, file)
#print id(tMatchList), "INSIDE ELSE"
print id(tMatchList), "AFTER"
f.writelines(lines)
f.close()
r.close()
os.remove(os.path.join(root, file)+"~")
enter code here
A:
The findall may not create a list object. If it is some kind of generator function, then it has a value which is "consumed" by traversing the results once.
After consuming the results yielded by this function, there are no more results.
tMatchList = self._testReplacePDFTag.findall(lines)
p = self._pdfPathRegex.search(lines)
print tMatchList #tMatchList is printing just fine here if it has any elements
if p:
print tMatchList #now it's empty,
Try this.
tMatchList = list( self._testReplacePDFTag.findall(lines) )
A:
So this is what ended up 'fixing' the issue:
I moved the tMatchList findall() line to follow the search. Then I added an 'if t:' statement. Now I am seeing the content of tMatchList inside the 'if p:' statement when I print it out. So problem solved for now, but I'm thinking there is some sort of behavioral concern I'm not aware of concerning the re module(?) or evaluating an empty list object.
#original code ....
linecount += 1
#this is modified section
t = self._testReplacePDFTag.search(lines)
if t:
tMatchList = self._testReplacePDFTag.findall(lines)
#end modified section
pMatchList = self._pdfPathRegex.findall(lines)
| Another Python Scope Question - losing information going into if statement | Not sure if I'm missing something obvious, but here's what is happening:
I have a python 2.4.3 script that contains several RegEx objects. Below one of the regex objects is searching for all matches in a string (tMatchList). Even if tMatchList is not null, it is printing an empty set after the 'if p:' step. This behavior occurs even if it prints correctly before the 'if p:' step. I thought it may have been a scope issue, but everything is declared & contained within one function. I'm not quite seeing how the 'if p:' step is not able to see tMatchList. I am able to print tMatchList after the if statement as well.
tMatchList = []
for lines in r:
linecount += 1
tMatchList = self._testReplacePDFTag.findall(lines)
p = self._pdfPathRegex.search(lines)
print tMatchList #tMatchList is printing just fine here if it has any elements
if p:
print tMatchList #now it's empty,
#even if it printed elements in prior statement
lines = .....
else:
<something else gets done>
print tMatchList #now it prints again
Including entire function definition for those who would like to see it....
def FindFilesAndModifyPDFTag(self, inRootDirArg, inRollBackBool):
for root, dirs, files in os.walk(inRootDirArg):
for d in dirs:
if d.startswith('.'):#excludes directories that start with '.'
continue
for file in files:
if os.path.splitext(file)[1] == self._fileExt:
#Backup original. just do it
shutil.copy2(os.path.join(root, file), os.path.join(root, file)+"~")
r = open(os.path.join(root, file)+"~", "r")
f = open(os.path.join(root, file), "w")
linecount = 0
tMatchList = []
for lines in r:
linecount += 1
tMatchList = self._testReplacePDFTag.findall(lines)
t = self._testReplacePDFTag.search(lines)
#find pdf path(s) in line
pMatchList = self._pdfPathRegex.findall(lines)
p = self._pdfPathRegex.search(lines)
#fix the pdf tracking code
print id(tMatchList), "BEFORE"
if p:
print id(tMatchList), "INSIDE"
lines = self.processPDFTagLine(pMatchList, lines, linecount, file, tMatchList)
else:
lines = self.processCheckMetaTag(lines, linecount, file)
#print id(tMatchList), "INSIDE ELSE"
print id(tMatchList), "AFTER"
f.writelines(lines)
f.close()
r.close()
os.remove(os.path.join(root, file)+"~")
enter code here
| [
"The findall may not create a list object. If it is some kind of generator function, then it has a value which is \"consumed\" by traversing the results once.\nAfter consuming the results yielded by this function, there are no more results.\ntMatchList = self._testReplacePDFTag.findall(lines)\n\np = self._pdfPathRegex.search(lines)\nprint tMatchList #tMatchList is printing just fine here if it has any elements\nif p:\n print tMatchList #now it's empty, \n\nTry this.\ntMatchList = list( self._testReplacePDFTag.findall(lines) )\n\n",
"So this is what ended up 'fixing' the issue:\nI moved the tMatchList findall() line to follow the search. Then I added an 'if t:' statement. Now I am seeing the content of tMatchList inside the 'if p:' statement when I print it out. So problem solved for now, but I'm thinking there is some sort of behavioral concern I'm not aware of concerning the re module(?) or evaluating an empty list object.\n#original code ....\nlinecount += 1\n\n#this is modified section\nt = self._testReplacePDFTag.search(lines)\nif t:\n tMatchList = self._testReplacePDFTag.findall(lines)\n\n#end modified section\n\npMatchList = self._pdfPathRegex.findall(lines)\n\n"
] | [
0,
0
] | [] | [] | [
"python",
"scope"
] | stackoverflow_0003141534_python_scope.txt |
Q:
making a python object unsable after a finalize-type call
I have a python object which wraps a sensitive and important resource on the system. I have a cleanup() function which safely releases various locks used by the object.
I want to make sure that after a call to cleanup() the object becomes unusable. Ideally, any call to any member function of the object would raises an exception. Is there a way to do this that does not involve checking a flag in every function?
A:
One way is to simply set all the instance variables to None. Then, doing pretty much anything will cause AttributeError or TypeError. A more sophisticated approach is to wrap instance methods with a decorator. The decorator can check if the close has been disposed. If so, it throws an exception:
class Unusable:
def __init__(self):
self.alive = True
def notcleanedup(func):
def operation(self, *args, **kwargs):
if self.alive:
func(self, *args, **kwargs)
else:
raise Exception("Use after cleanup")
return operation
@notcleanedup
def sensitive(self, a, b):
print a, b
def cleanup(self):
self.alive = False
| making a python object unsable after a finalize-type call | I have a python object which wraps a sensitive and important resource on the system. I have a cleanup() function which safely releases various locks used by the object.
I want to make sure that after a call to cleanup() the object becomes unusable. Ideally, any call to any member function of the object would raises an exception. Is there a way to do this that does not involve checking a flag in every function?
| [
"One way is to simply set all the instance variables to None. Then, doing pretty much anything will cause AttributeError or TypeError. A more sophisticated approach is to wrap instance methods with a decorator. The decorator can check if the close has been disposed. If so, it throws an exception:\nclass Unusable:\n def __init__(self):\n self.alive = True\n\n def notcleanedup(func):\n def operation(self, *args, **kwargs):\n if self.alive:\n func(self, *args, **kwargs)\n else:\n raise Exception(\"Use after cleanup\")\n\n return operation\n\n @notcleanedup\n def sensitive(self, a, b):\n print a, b\n\n def cleanup(self):\n self.alive = False\n\n"
] | [
1
] | [] | [] | [
"destructor",
"object",
"python",
"resources"
] | stackoverflow_0003145353_destructor_object_python_resources.txt |
Q:
Executing a python script using subprocess.Popen() in a django view
I've looked around a bit but I can't seem to solve this problem I have. I'd like to execute a python script within a view of my django app. I've placed the code I'd like to execute inside a django management command so it can be accessed via command line python manage.py command-name. I then tried to run this command using subprocess.Popen("python manage.py command-name",shell=True).
However, this command could take some time to execute so I'd like the view to continue and allow the script to execute in the background. Using subprocess.Popen alone seems to cause the view to hang until the script has finished, so I tried using a thread (following another SA question):
class SubprocessThread(threading.Thread):
def __init__(self, c):
self.command = c
self.stdout = None
self.stderr = None
threading.Thread.__init__(self)
def run(self):
p = subprocess.Popen(self.command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.stdout, self.stderr = p.communicate()
and then executing it:
t = SubprocessThread("python manage.py command-name")
t.setDaemon(True)
t.start()
t.join()
However, the view still hangs: the cursor has a busy symbol and the AJAX on the page does not load. Otherwise the page's html seems to load fine and commands in the view after the thread call appear to finish normally (before the script finishes). Can someone please help me? I'd like the script to execute and do its own thing without holding up the view or AJAX calls on the page.
A:
Maybe you should use celery
Celery is a task queue/job queue based
on distributed message passing. It is
focused on real-time operation
A:
I wasted a lot of time trying to implement something similar, but had the same problems as you. Eventually, I gave up and implemented a beanstalk queue to handle the work.
http://kr.github.com/beanstalkd/
I put an id on the queue in the Django view, and then have a management command to run the consumer (watched by supervisord).
Using a queue means you could expand to multiple consumers, and allows to better manage the load (pausing the consumer if necessary without losing the work required).
| Executing a python script using subprocess.Popen() in a django view | I've looked around a bit but I can't seem to solve this problem I have. I'd like to execute a python script within a view of my django app. I've placed the code I'd like to execute inside a django management command so it can be accessed via command line python manage.py command-name. I then tried to run this command using subprocess.Popen("python manage.py command-name",shell=True).
However, this command could take some time to execute so I'd like the view to continue and allow the script to execute in the background. Using subprocess.Popen alone seems to cause the view to hang until the script has finished, so I tried using a thread (following another SA question):
class SubprocessThread(threading.Thread):
def __init__(self, c):
self.command = c
self.stdout = None
self.stderr = None
threading.Thread.__init__(self)
def run(self):
p = subprocess.Popen(self.command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.stdout, self.stderr = p.communicate()
and then executing it:
t = SubprocessThread("python manage.py command-name")
t.setDaemon(True)
t.start()
t.join()
However, the view still hangs: the cursor has a busy symbol and the AJAX on the page does not load. Otherwise the page's html seems to load fine and commands in the view after the thread call appear to finish normally (before the script finishes). Can someone please help me? I'd like the script to execute and do its own thing without holding up the view or AJAX calls on the page.
| [
"Maybe you should use celery\n\nCelery is a task queue/job queue based\n on distributed message passing. It is\n focused on real-time operation\n\n",
"I wasted a lot of time trying to implement something similar, but had the same problems as you. Eventually, I gave up and implemented a beanstalk queue to handle the work. \nhttp://kr.github.com/beanstalkd/\nI put an id on the queue in the Django view, and then have a management command to run the consumer (watched by supervisord). \nUsing a queue means you could expand to multiple consumers, and allows to better manage the load (pausing the consumer if necessary without losing the work required). \n"
] | [
3,
2
] | [] | [] | [
"django",
"multithreading",
"python",
"subprocess"
] | stackoverflow_0003144162_django_multithreading_python_subprocess.txt |
Q:
How can I group objects by their date in Django?
I'm trying to select all objects in the articles table, and have them grouped by their date. I'm thinking it would look similar to this:
articles = Article.objects.filter(pub_date__lte=datetime.date.today()).group_by(pub_date.day)
articles = {'2010-01-01': (articleA, articleB, articleC...),
'2010-01-02': (article1, article2, article3...)...}
A:
Here's a working example of ignacio's suggestion to use itertools.groupby.
class Article(object):
def __init__(self, pub_date):
self.pub_date = pub_date
if __name__ == '__main__':
from datetime import date
import itertools
import operator
# You'll use your Article query here instead:
# a_list = Article.objects.filter(pub_date__lte = date.today())
a_list = [
Article(date(2010, 1, 2)),
Article(date(2010, 2, 3)),
Article(date(2010, 1, 2)),
Article(date(2011, 3, 2)),
]
keyfunc = operator.attrgetter('pub_date')
a_list = sorted(a_list, key = keyfunc)
group_list = [{ k.strftime('%Y-%m-%d') : list(g)}
for k, g in itertools.groupby(a_list, keyfunc)]
print group_list
Output:
[{'2010-01-02': [<__main__.Article object at 0xb76c4fec>, <__main__.Article object at 0xb76c604c>]}, {'2010-02-03': [<__main__.Article object at 0xb76c602c>]}, {'2011-03-02': [<__main__.Article object at 0xb76c606c>]}]
A:
itertools.groupby()
A:
MAybe you should do it at template level? If so you only need this : regroup tempalte tag
| How can I group objects by their date in Django? | I'm trying to select all objects in the articles table, and have them grouped by their date. I'm thinking it would look similar to this:
articles = Article.objects.filter(pub_date__lte=datetime.date.today()).group_by(pub_date.day)
articles = {'2010-01-01': (articleA, articleB, articleC...),
'2010-01-02': (article1, article2, article3...)...}
| [
"Here's a working example of ignacio's suggestion to use itertools.groupby. \nclass Article(object):\n def __init__(self, pub_date):\n self.pub_date = pub_date\n\n\nif __name__ == '__main__':\n from datetime import date\n import itertools\n import operator\n\n # You'll use your Article query here instead:\n # a_list = Article.objects.filter(pub_date__lte = date.today())\n a_list = [\n Article(date(2010, 1, 2)),\n Article(date(2010, 2, 3)),\n Article(date(2010, 1, 2)),\n Article(date(2011, 3, 2)),\n ]\n\n\n keyfunc = operator.attrgetter('pub_date')\n\n a_list = sorted(a_list, key = keyfunc)\n group_list = [{ k.strftime('%Y-%m-%d') : list(g)} \n for k, g in itertools.groupby(a_list, keyfunc)]\n\n print group_list\n\nOutput:\n[{'2010-01-02': [<__main__.Article object at 0xb76c4fec>, <__main__.Article object at 0xb76c604c>]}, {'2010-02-03': [<__main__.Article object at 0xb76c602c>]}, {'2011-03-02': [<__main__.Article object at 0xb76c606c>]}]\n\n",
"itertools.groupby()\n",
"MAybe you should do it at template level? If so you only need this : regroup tempalte tag\n"
] | [
4,
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003145246_django_python.txt |
Q:
Python: get number of items in generator without storing the items
I have a generator for a large set of items. I want to iterate through them once, outputting them to a file. However, with the file format I currently have, I first have to output the number of items I have. I don't want to build a list of the items in memory, as there are too many of them and that would take a lot of time and memory. Is there a way to iterate through the generator, getting its length, but somehow be able to iterate through it again later, getting the same items?
If not, what other solution could I come up with for this problem?
A:
If you can figure out how to just write a formula to calculate the size based on the parameters that control the generator, do that. Otherwise, I don't think you would save much time.
Include the generator here, and we'll try to do it for you!
A:
This cannot be done. Once a generator is exhausted it needs to be reconstructed in order to be used again. It is possible to define the __len__() method on an iterator object if the number of items is known ahead of time, and then len() can be called against the iterator object.
A:
I don't think that is possible for any generalized iterator. You will need to figure out how the generator was originally constructed and then regenerate it for the final pass.
Alternatively, you could write out a dummy size to your file, write the items, and then reopen the file for modification and correct the size in the header.
If your file is a binary format, this could work quite well, since the number of bytes for the size is the same regardless of what the actual size is. If it is a text format, it is possible that you would have to add some extra length to the file if you weren't able to pad the dummy size to cover all cases. See this question for a discussion on inserting and rewriting in a text file using Python.
| Python: get number of items in generator without storing the items | I have a generator for a large set of items. I want to iterate through them once, outputting them to a file. However, with the file format I currently have, I first have to output the number of items I have. I don't want to build a list of the items in memory, as there are too many of them and that would take a lot of time and memory. Is there a way to iterate through the generator, getting its length, but somehow be able to iterate through it again later, getting the same items?
If not, what other solution could I come up with for this problem?
| [
"If you can figure out how to just write a formula to calculate the size based on the parameters that control the generator, do that. Otherwise, I don't think you would save much time.\nInclude the generator here, and we'll try to do it for you!\n",
"This cannot be done. Once a generator is exhausted it needs to be reconstructed in order to be used again. It is possible to define the __len__() method on an iterator object if the number of items is known ahead of time, and then len() can be called against the iterator object.\n",
"I don't think that is possible for any generalized iterator. You will need to figure out how the generator was originally constructed and then regenerate it for the final pass.\nAlternatively, you could write out a dummy size to your file, write the items, and then reopen the file for modification and correct the size in the header.\nIf your file is a binary format, this could work quite well, since the number of bytes for the size is the same regardless of what the actual size is. If it is a text format, it is possible that you would have to add some extra length to the file if you weren't able to pad the dummy size to cover all cases. See this question for a discussion on inserting and rewriting in a text file using Python.\n"
] | [
5,
5,
5
] | [] | [] | [
"generator",
"memory",
"performance",
"python",
"yield"
] | stackoverflow_0003145483_generator_memory_performance_python_yield.txt |
Q:
printing lines that contain 60 characters
I'm having trouble printing a string in lines chat contains 60 characters.
my code is below:
s = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrtsucwxyz'
for i in range(0, len(s), 60):
for k in s[i:i+60]:
print k
A:
s[i:i+60] will slice the 60 characters you want into a string. By adding a second for loop, you're looping over each character in that string and outputting it separately. Just output s[i:i+60] instead
A:
Print the slice itself, not each character in the slice.
s = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrtsucwxyz'
for i in range(0, len(s), 60):
print s[i:i+60]
A:
You can also use the textwrap module, ie textwrap.fill(s, 60)
| printing lines that contain 60 characters | I'm having trouble printing a string in lines chat contains 60 characters.
my code is below:
s = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrtsucwxyz'
for i in range(0, len(s), 60):
for k in s[i:i+60]:
print k
| [
"s[i:i+60] will slice the 60 characters you want into a string. By adding a second for loop, you're looping over each character in that string and outputting it separately. Just output s[i:i+60] instead\n",
"Print the slice itself, not each character in the slice. \ns = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrtsucwxyz'\n\nfor i in range(0, len(s), 60):\n print s[i:i+60]\n\n",
"You can also use the textwrap module, ie textwrap.fill(s, 60)\n"
] | [
4,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0003145046_python.txt |
Q:
PyS60 vs Symbian C++
I'm planning some Symbian related development on S60 3.1 platform. It seems like generally available language options are Python and C++. However Nokia's official forum seems very much tilted towards C++.
I want to know what are the advantages and disadvantages of using Python for S60 over Symbian C++? And is it even possible to do Python programming for S60 3.1 platform?
A:
PyS60 is good when you need to prototype something simple fast. If you try to develop a full application with it though, you'll most likely find yourself sooner or later wanting to use features that are available in Symbian C++ but not in PyS60 without writing bindings (in C++) for it. Also you'll need to deal with the right version of PyS60 runtime being available, and some of them aren't backwards compatible.
If you go for the Symbian C++ route, you can embed a python interpreter in it too.
A:
C++ is very, very fast, and the Qt library is for C++. If you're programming on a mobile phone, Python will be very slow and you'll have to spend ages writing bindings for it.
A:
I answer this as a user.
PyS60 is slow and not so much app and sample to start with.
C++ is good, native, fast, but if you mind deevelop app for most device (current N-series), you will not want to go with Qt, I have a N78 and tested Qt in N82 too, it's slow (more than Python, sadly but true)
A:
PyS60 has a very limited API. Applications written using it are slow, hard to deploy (since you have to install the runtime first) and cannot be posted on the Ovi store. If you're looking for an easy way to write simple Symbian apps take a look at Nokia WRT.
If you don't mind C++ try the recently released Qt SDK 1.0. It's really powerful, future proof and will soon be supported by the Ovi store.
A:
What is the purpose of your programming? Are you planning distribute your app through Ovi Store? If so, you should use a tool that could be tested and signed by Symbian Signed.
What does it mean? As far as I know, they don't provide such functionality for Python. So you have to choose native Symbian C++ or Qt.
By the way, Qt signing procedure is not quite clear for now. It seems Ovi Store and Symbian Signed are only allow Qt apps for a certain devices (Nokia X6, Nokia N97 mini, maybe some other). I suppose it is a subject for a change, and quite fast change, but you should consider this too.
A:
When 3rd edition Feature Pack 1 ran the latest phones on the market, the main runtime people were using to program them was J2ME (http://www.forum.nokia.com/Develop/Java/). I know the title pits C++ against Python, but have you considered Java? It was much easier than native Symbian C++. The performance is good.
-jk
| PyS60 vs Symbian C++ | I'm planning some Symbian related development on S60 3.1 platform. It seems like generally available language options are Python and C++. However Nokia's official forum seems very much tilted towards C++.
I want to know what are the advantages and disadvantages of using Python for S60 over Symbian C++? And is it even possible to do Python programming for S60 3.1 platform?
| [
"PyS60 is good when you need to prototype something simple fast. If you try to develop a full application with it though, you'll most likely find yourself sooner or later wanting to use features that are available in Symbian C++ but not in PyS60 without writing bindings (in C++) for it. Also you'll need to deal with the right version of PyS60 runtime being available, and some of them aren't backwards compatible.\nIf you go for the Symbian C++ route, you can embed a python interpreter in it too.\n",
"C++ is very, very fast, and the Qt library is for C++. If you're programming on a mobile phone, Python will be very slow and you'll have to spend ages writing bindings for it.\n",
"I answer this as a user.\nPyS60 is slow and not so much app and sample to start with.\nC++ is good, native, fast, but if you mind deevelop app for most device (current N-series), you will not want to go with Qt, I have a N78 and tested Qt in N82 too, it's slow (more than Python, sadly but true)\n",
"PyS60 has a very limited API. Applications written using it are slow, hard to deploy (since you have to install the runtime first) and cannot be posted on the Ovi store. If you're looking for an easy way to write simple Symbian apps take a look at Nokia WRT.\nIf you don't mind C++ try the recently released Qt SDK 1.0. It's really powerful, future proof and will soon be supported by the Ovi store.\n",
"What is the purpose of your programming? Are you planning distribute your app through Ovi Store? If so, you should use a tool that could be tested and signed by Symbian Signed. \nWhat does it mean? As far as I know, they don't provide such functionality for Python. So you have to choose native Symbian C++ or Qt. \nBy the way, Qt signing procedure is not quite clear for now. It seems Ovi Store and Symbian Signed are only allow Qt apps for a certain devices (Nokia X6, Nokia N97 mini, maybe some other). I suppose it is a subject for a change, and quite fast change, but you should consider this too.\n",
"When 3rd edition Feature Pack 1 ran the latest phones on the market, the main runtime people were using to program them was J2ME (http://www.forum.nokia.com/Develop/Java/). I know the title pits C++ against Python, but have you considered Java? It was much easier than native Symbian C++. The performance is good. \n-jk\n"
] | [
2,
1,
1,
0,
0,
0
] | [] | [] | [
"c++",
"pys60",
"python",
"symbian"
] | stackoverflow_0003123340_c++_pys60_python_symbian.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.