content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to write a Python 2.6+ script that gracefully fails with older Python?
I'm using the new print from Python 3.x and I observed that the following code does not compile due to the end=' '.
from __future__ import print_function
import sys
if sys.hexversion < 0x02060000:
raise Exception("py too old")
...
print("x",end=" ") # fails to compile with py24
How can I continue using the new syntax but make the script fails nicely? Is it mandatory to call another script and use only safe syntax in this one?
A:
The easy method for Python 2.6 is just to add a line like:
b'You need Python 2.6 or later.'
at the start of the file. This exploits the fact that byte literals were introduced in 2.6 and so any earlier versions will raise a SyntaxError with whatever message you write given as the stack trace.
A:
There are some suggestions in this question here, but it looks like it is not easily possible. You'll have to create a wrapper script.
A:
One way is to write your module using python 2.x print statement, then when you want to port it into python 3, you use 2to3 script. I think there are scripts for 3to2 conversion as well, although they seems to be less mature than 2to3.
Either way, in biggers scripts, you should always separate domain logic and input/output; that way, all the print statements/functions are bunched up together in a single file. For logging, you should use the logging module.
| How to write a Python 2.6+ script that gracefully fails with older Python? | I'm using the new print from Python 3.x and I observed that the following code does not compile due to the end=' '.
from __future__ import print_function
import sys
if sys.hexversion < 0x02060000:
raise Exception("py too old")
...
print("x",end=" ") # fails to compile with py24
How can I continue using the new syntax but make the script fails nicely? Is it mandatory to call another script and use only safe syntax in this one?
| [
"The easy method for Python 2.6 is just to add a line like:\nb'You need Python 2.6 or later.'\n\nat the start of the file. This exploits the fact that byte literals were introduced in 2.6 and so any earlier versions will raise a SyntaxError with whatever message you write given as the stack trace.\n",
"There are ... | [
8,
2,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003035749_python_python_3.x.txt |
Q:
monitor keyboard events with python in windows 7
Is there any way to monitor keyboard events in windows 7 with python without the python program having focus? I would like to run the python script as a background process that monitors certain keyboard events and does certain things on various keyboard input combinations.
A:
Ok, I got pyHook working after installing the 32bit version of python 2.7 and compiling pyHook from the source with MinGW. Thanks for the pointers everyone.
| monitor keyboard events with python in windows 7 | Is there any way to monitor keyboard events in windows 7 with python without the python program having focus? I would like to run the python script as a background process that monitors certain keyboard events and does certain things on various keyboard input combinations.
| [
"Ok, I got pyHook working after installing the 32bit version of python 2.7 and compiling pyHook from the source with MinGW. Thanks for the pointers everyone.\n"
] | [
2
] | [] | [] | [
"event_handling",
"events",
"python",
"windows_7"
] | stackoverflow_0003476183_event_handling_events_python_windows_7.txt |
Q:
wxPython SetBackgroundColour not working on OS X
I haven't had to do any GUI programming in a long time, so I might be being obtuse here, so please bear with me if this is a stupid question. I decided to use wxPython for a small hobby project, and I'm having trouble changing the background colour of the main window. I'm using Python 2.6.2 and wxPython 2.8.11.0 on Snow Leopard. Can anyone tell me what I'm doing wrong here? Or have I stumbled upon a bug of some sort? Here's a small sample that demonstrates the problem...
from wx import *
class MainFrame(Frame):
def __init__(self, parent, title):
Frame.__init__(self, parent, title=title)
self.Maximize()
self.cdatabase = ColourDatabase()
self.SetBackgroundStyle(BG_STYLE_CUSTOM)
self.SetOwnBackgroundColour(self.cdatabase.Find('BLACK'))
self.Show(True)
self.ClearBackground()
app = App(False)
frame = MainFrame(None, 'a title')
app.MainLoop()
A:
Your call to self.SetBackgroundStyle(BG_STYLE_CUSTOM) seems to be causing trouble on my system, and also you don't need the line for self.cdatabase = ColourDatabase() at all in my tests. This code works on my side of things:
from wx import *
class MainFrame(Frame):
def __init__(self, parent, title):
Frame.__init__(self, parent, title=title)
self.Maximize()
self.SetOwnBackgroundColour('Black')
self.Show(True)
app = App(False)
frame = MainFrame(None, 'a title')
app.MainLoop()
A:
The thing to remember with wxPython is that for the most part, it wraps the native widgets of the platform it is on. So if the frame on Linux doesn't support changing its background color, than you can't do it with just the frame. (Note: I don't know which platforms wx.Frame supports bg color changing)
The wx.Panel should always be included for consistent look and feel as well as getting tabbing to work correctly on the child widgets. If you want to be able to completely control every aspect of your application, you would need to use a different toolkit. By the way, many of the core controls in wxPython have generic counterparts that were written in pure python and can be hacked to do stuff that native widgets cannot.
| wxPython SetBackgroundColour not working on OS X | I haven't had to do any GUI programming in a long time, so I might be being obtuse here, so please bear with me if this is a stupid question. I decided to use wxPython for a small hobby project, and I'm having trouble changing the background colour of the main window. I'm using Python 2.6.2 and wxPython 2.8.11.0 on Snow Leopard. Can anyone tell me what I'm doing wrong here? Or have I stumbled upon a bug of some sort? Here's a small sample that demonstrates the problem...
from wx import *
class MainFrame(Frame):
def __init__(self, parent, title):
Frame.__init__(self, parent, title=title)
self.Maximize()
self.cdatabase = ColourDatabase()
self.SetBackgroundStyle(BG_STYLE_CUSTOM)
self.SetOwnBackgroundColour(self.cdatabase.Find('BLACK'))
self.Show(True)
self.ClearBackground()
app = App(False)
frame = MainFrame(None, 'a title')
app.MainLoop()
| [
"Your call to self.SetBackgroundStyle(BG_STYLE_CUSTOM) seems to be causing trouble on my system, and also you don't need the line for self.cdatabase = ColourDatabase() at all in my tests. This code works on my side of things:\nfrom wx import * \n\nclass MainFrame(Frame):\n def __init__(self, parent, title):\n ... | [
1,
1
] | [] | [] | [
"macos",
"python",
"wxpython"
] | stackoverflow_0003472609_macos_python_wxpython.txt |
Q:
Converting to Twisted Asynchronous Design
Ok I have had a problem expressing my problems with the code I am working on without dumping a ton of code; so here is what it would be synchronously (instead of asking it from the view of it being async).
Also for classes when should a variable be accessed through a method argument and when should it be accessed through a instance variable?
Synchronously it would look like so...
Note: the actual server urls and parsing are different but just complicate things. Also in the following example the get_token method takes the session as a parameter, should it instead get the session by using self.session instead?
import urllib
import time
class SyncExampleClass(object):
def __init__(self):
self.session = None
self.token = None
self.session_time = -1
def get_session(self):
s = urllib.urlopen("http://example.com/session/").read()
self.session_time = int(time.time())
return s
def get_token(self, session):
t = urllib.urlopen("http://example.com/token/?session=%s" % session).read()
return t
def construct_api_call(self, api_method):
# if the session is over an hour old (is that the correct sign?)
if time.time() - 3600 > self.session_time or self.session is None:
self.session = get_session()
self.token = get_token(self.session)
call = urllib.urlopen("http://example.com/api/?method=%s%session=%s&token=%s" % (api_method, self.session, self.token) ).read()
return call
A:
Given the circumstances, this just a skeleton of a solution which much implied. It seems to go against instinct to provide a solution with code where much is implied and untested...
However, if I was coding what I think you're trying to achieve, I might go about it something like this:
from twisted.internet import defer
from twisted.web import client
from twisted.python import log
from urllib import urlencode
import time
class APIException(Exception):
pass
class ASyncExampleClass(object):
def __init__(self):
self.session = None
self.token = None
@defer.inlineCallbacks
def api_call(self, api_method,tries=3,timeout=10):
attempt = 1
while attempt <= tries:
attempt += 1
if self.session = None:
yield sess_data = client.getPage("http://example.com/session/",timeout=timeout)
self.session = extractSessionFromData(sess_data)
if self.token = None:
yield token_data = client.getPage("http://example.com/token/?%s" % urlencode(dict(session=self.session)),timeout=timeout)
self.token = extractTokenFromData(token_data)
# Place "the" call
yield api_result = client.getPage("http://example.com/api/?%s" % urlencode(dict(api_method=api_method,session=self.session,token=self.token)),timeout=timeout)
#
if sessionInvalid(api_result):
log.msg("Request for %s failed because invalid session %s" % (api_method,self.session))
self.session = None
self.token = None
continue
if tokenInvalid(api_result):
log.msg("Request for %s failed because invalid token %s" % (api_method,self.token))
self.token = None
continue
# Any other checks for valid result
returnValue(api_result)
break # Not sure if this is needed, not in an position to test readily.
else:
raise APIException("Tried and failed %s times to do %s" % (attempt - 1, api_method))
The method that makes the external api uses inlineCallbacks and handles the logic of acquiring and renewing sessions and tokens itself. I have assumed that when a session is invalid, that any tokens acquired with it are also invalid. It implements a retry loop, which could also contain a try/except block for better handling of HTTP Exceptions.
You can use twisted.web.client.getPage with POST, the extra arguments you supply are handled by HTTPClientFactory.
Also, I wouldn't bother to time the session, just renew it when needed.
| Converting to Twisted Asynchronous Design | Ok I have had a problem expressing my problems with the code I am working on without dumping a ton of code; so here is what it would be synchronously (instead of asking it from the view of it being async).
Also for classes when should a variable be accessed through a method argument and when should it be accessed through a instance variable?
Synchronously it would look like so...
Note: the actual server urls and parsing are different but just complicate things. Also in the following example the get_token method takes the session as a parameter, should it instead get the session by using self.session instead?
import urllib
import time
class SyncExampleClass(object):
def __init__(self):
self.session = None
self.token = None
self.session_time = -1
def get_session(self):
s = urllib.urlopen("http://example.com/session/").read()
self.session_time = int(time.time())
return s
def get_token(self, session):
t = urllib.urlopen("http://example.com/token/?session=%s" % session).read()
return t
def construct_api_call(self, api_method):
# if the session is over an hour old (is that the correct sign?)
if time.time() - 3600 > self.session_time or self.session is None:
self.session = get_session()
self.token = get_token(self.session)
call = urllib.urlopen("http://example.com/api/?method=%s%session=%s&token=%s" % (api_method, self.session, self.token) ).read()
return call
| [
"Given the circumstances, this just a skeleton of a solution which much implied. It seems to go against instinct to provide a solution with code where much is implied and untested...\nHowever, if I was coding what I think you're trying to achieve, I might go about it something like this:\nfrom twisted.internet impo... | [
5
] | [] | [] | [
"asynchronous",
"python",
"twisted"
] | stackoverflow_0003463496_asynchronous_python_twisted.txt |
Q:
How to avoid writing the name of the module all the time when importing a module in python?
I use the math module a lot lately. I don't want to write math.sqrt(x) and math.sin(x) all the time. I would like to shorten it and write sqrt(x) and sin(x).
How?
A:
For longer module names it is common to shorten them, e.g.
import numpy as np
Then you can use the short name. Or you can import the specific stuff that you need, as shown in the other anwsers:
from math import sin, sqrt
This is often used inside packages, for code that is more closely coupled. For libraries the first option with the name shortening is often the prefered way.
What you should never do is use the from math import * form. It will pollute the name space, potentially leading to name collisions and making debugging harder. Most importantly it makes the code hard to read, because it is not clear where a particular function came from.
An exception can be made in the interactive interpreter. But once you are in the habit of using the shortened names it might not be worth to go with another convention there.
A:
You can import like this:
>>> from math import sqrt, sin
>>> sqrt(100)
10.0
From: More on modules
There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table. For example:
>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
There is even a variant to import all names that a module defines which can be useful in the interactive interpreter:
>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.
A:
from math import sin, sqrt
# Then you can just do
sqrt(4)
A:
let me add that i consider not only from math import * a case of namespace pollution, but also from math import cos. this is because when you do this on top of module foo, and you then look at the namespace of that module with import foo; print( dir( foo ) ), you will have an item cos in that list. usually, this is not what you want.
so most of the time all my imports look like from math import cos as _cos, the leading underscore being the conventional sigil to indicate a private name. the idea is that an import from another module and a printout, import foo; print( name for name in dir( foo ) if not name.startswith( '_' ) ) will give you exactly those names that were defined in that module as public.
there is one thing to be aware of: from math import cos as _cos; f = lambda x: _cos( x ) is functionally not 100% identical to import math; g = lambda x: math.cos( x ). the difference is that in python, name resolution happens at run time, each time the code is called. with the first import, the name cos is only resolved once; any subsequent changes to the math module will not affect f(). with the second import, cos will be resolved against math each time it is called, so changes to the math module's cos method will propagate into g(). of course, the math module is neither expected to change during runtime, nor is changing a module's method at runtime a particularly recommendable programming technique. on the other hand, a module is just an object like everything else in python, so it pays off to always be aware what happens under the hood.
normally, from math import cos as _cos; f = lambda x: _cos( x ) is what you want, and it is also a bit faster than the second form.
| How to avoid writing the name of the module all the time when importing a module in python? | I use the math module a lot lately. I don't want to write math.sqrt(x) and math.sin(x) all the time. I would like to shorten it and write sqrt(x) and sin(x).
How?
| [
"For longer module names it is common to shorten them, e.g.\nimport numpy as np\n\nThen you can use the short name. Or you can import the specific stuff that you need, as shown in the other anwsers:\nfrom math import sin, sqrt\n\nThis is often used inside packages, for code that is more closely coupled. For librari... | [
7,
5,
5,
1
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0003476509_import_module_python.txt |
Q:
C++ methods overload in python
suppose a C++ class has several constructors which are overloaded according the number and type and sequences of their respective parameters, for example, constructor(int x, int y) and constructor(float x, float y, float z), I think these two are overloaded methods, which one to use depends on the parameters, right? So then in python, how could I create a constructor that can work like this? I notice that python has the def method(self, *args, **kwargs):, so can I use it like: def __init__(self, *args), then I check the length of *args, like if len(args) == 2:, then construct according to the 2-parameters constructor, if len(args) == 3, then use the 3-parameters constructor, etc. So, does that work? Or is there any better way to do it with python? Or should I think in other ways that could take the advantage of python feature itself? thanks~
A:
Usually, you're fine with any combination of
slightly altered design
default arguments (def __init__(self, x = 0.0, y = 0.0, z = 0.0))
use of polymorphism (in a duck-typed language, you don't need an overload for SomeThing vs SomeSlightlyDifferentThing if neither inherits from the other one, as long as their interfaces are similar enough).
If that doesn't seem feasible, try harder ;) If it still doesn't seem feasible, look at David's link.
A:
It really depends on what you want to do. The *args/**kwargs method works fairly well, as does the default arguments that delnan suggests.
The main difference between C++ and Python in this case is the what and why of what you are trying to do. If you have a class that needs floats, just try casting the arguments as floats. You can also rely on default arguments to branch your logic:
class Point(object):
def __init__(self, x=0.0, y=0.0, z=None):
# Because None is a singleton,
# it's like Highlander - there can be only one! So use 'is'
# for identity comparison
if z is None:
self.x = int(x)
self.y = int(y)
self.z = None
else:
self.x = float(x)
self.y = float(y)
self.z = float(z)
p1 = Point(3, 5)
p2 = Point(1.0, 3.3, 4.2)
p3 = Point('3', '4', '5')
points = [p1, p2, p3]
for p in points:
print p.x, p.y, p.z
You don't, of course, have to assign self.z = None, that was simply for the convenience of my example.
For the best advice about which pattern to use,
In [17]: import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
...
If your pattern is beautiful, explicit, and simple, it just may be the right one to use.
A:
I think these two are overloaded methods, which one to use depends on the parameters, right?
Sorry, if I seem to be nitpicking, but just thought of bringing this difference out clearly.
The term parameters and arguments have very specific meaning in C++
argument: an expression in the comma-separated list bounded by the parentheses in a function call expression, a sequence of preprocessing tokens in the comma-separated list bounded by the parentheses in a function-like macro invocation, the operand of throw, or an expression, type-id or template-name in the commaseparated list bounded by the angle brackets in a template instantiation. Also known as an actual argument or actual parameter.
parameter: an object or reference declared as part of a function declaration or definition, or in the catch clause of an exception handler, that acquires a value on entry to the function or handler; an identifier from the commaseparated list bounded by the parentheses immediately following the macro name in a function-like macro definition; or a template-parameter. Parameters are also known as formal arguments or formal parameters
| C++ methods overload in python | suppose a C++ class has several constructors which are overloaded according the number and type and sequences of their respective parameters, for example, constructor(int x, int y) and constructor(float x, float y, float z), I think these two are overloaded methods, which one to use depends on the parameters, right? So then in python, how could I create a constructor that can work like this? I notice that python has the def method(self, *args, **kwargs):, so can I use it like: def __init__(self, *args), then I check the length of *args, like if len(args) == 2:, then construct according to the 2-parameters constructor, if len(args) == 3, then use the 3-parameters constructor, etc. So, does that work? Or is there any better way to do it with python? Or should I think in other ways that could take the advantage of python feature itself? thanks~
| [
"Usually, you're fine with any combination of\n\nslightly altered design\ndefault arguments (def __init__(self, x = 0.0, y = 0.0, z = 0.0))\nuse of polymorphism (in a duck-typed language, you don't need an overload for SomeThing vs SomeSlightlyDifferentThing if neither inherits from the other one, as long as their ... | [
3,
1,
0
] | [
"This article talks about how a multimethod decorator can be created in Python. I haven't tried out the code that they give, but the syntax that it defines looks quite nice. Here's an example from the article:\nfrom mm import multimethod\n\n@multimethod(int, int)\ndef foo(a, b):\n ...code for two ints...\n\n@mul... | [
-2
] | [
"c++",
"constructor",
"overloading",
"python"
] | stackoverflow_0003476387_c++_constructor_overloading_python.txt |
Q:
Is there a lib to generate data according to a regexp? (Python or other)
Given a regexp, I would like to generate random data x number of time to test something.
e.g.
>>> print generate_date('\d{2,3}')
13
>>> print generate_date('\d{2,3}')
422
Of course the objective is to do something a bit more complicated than that such as phone numbers and email addresses.
Does something like this exists? If it does, does it exists for Python? If not, any clue/theory I could use to do that?
A:
Pyparsing includes this regex inverter, which returns a generator of all permutations for simple regexes. Here are some of the test cases from that module:
[A-C]{2}\d{2}
@|TH[12]
@(@|TH[12])?
@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?
@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?
(([ECMP]|HA|AK)[SD]|HS)T
[A-CV]{2}
A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]
(a|b)|(x|y)
Edit:
To do your random selection, create a list (once!) of your permutations, and then call random.choice on the list each time you want a random string that matches the regex, something like this (untested):
class RandomString(object):
def __init__(self, regex):
self.possible_strings = list(invRegex.invert(regex))
def random_string(self):
return random.choice(self.possible_strings)
A:
There is a post on the Python mailing list about a module that generates all permutations of a regex. I'm not so sure how you might go about randomising it though. I'll keep checking.
A:
I will probably be flogged for suggesting this, but perl has a module that does exactly this. You might want to take a look at the code how to implement it in python:
http://p3rl.org/String::Random
| Is there a lib to generate data according to a regexp? (Python or other) | Given a regexp, I would like to generate random data x number of time to test something.
e.g.
>>> print generate_date('\d{2,3}')
13
>>> print generate_date('\d{2,3}')
422
Of course the objective is to do something a bit more complicated than that such as phone numbers and email addresses.
Does something like this exists? If it does, does it exists for Python? If not, any clue/theory I could use to do that?
| [
"Pyparsing includes this regex inverter, which returns a generator of all permutations for simple regexes. Here are some of the test cases from that module:\n[A-C]{2}\\d{2}\n@|TH[12]\n@(@|TH[12])?\n@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?\n@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?... | [
8,
2,
1
] | [] | [] | [
"data_generation",
"python",
"regex"
] | stackoverflow_0003477300_data_generation_python_regex.txt |
Q:
"pythonic" method to parse a string of comma-separated integers into a list of integers?
I am reading in a string of integers such as "3 ,2 ,6 " and want them in the list [3,2,6] as integers. This is easy to hack about, but what is the "pythonic" way of doing it?
A:
mylist = [int(x) for x in '3 ,2 ,6 '.split(',')]
And if you're not sure you'll only have digits (or want to discard the others):
mylist = [int(x) for x in '3 ,2 ,6 '.split(',') if x.strip().isdigit()]
A:
map( int, myString.split(',') )
A:
While a custom solution will teach you about Python, for production code using the csv module is the best idea. Comma-separated data can become more complex than initially appears.
| "pythonic" method to parse a string of comma-separated integers into a list of integers? | I am reading in a string of integers such as "3 ,2 ,6 " and want them in the list [3,2,6] as integers. This is easy to hack about, but what is the "pythonic" way of doing it?
| [
"mylist = [int(x) for x in '3 ,2 ,6 '.split(',')]\n\nAnd if you're not sure you'll only have digits (or want to discard the others):\nmylist = [int(x) for x in '3 ,2 ,6 '.split(',') if x.strip().isdigit()]\n\n",
"map( int, myString.split(',') )\n\n",
"While a custom solution will teach you about Python, for pro... | [
31,
25,
9
] | [] | [] | [
"python"
] | stackoverflow_0003477502_python.txt |
Q:
replace empty datasets
Sorry, I agree that was really poorly written:
Take 2:
I have many columns of data (up to 63) in over 50 datasets. I am extracting only 3 columns of data that I need and writing it into a new .csv file. There are a few of my datasets that do not have the third desired column of data. But that's okay I can leave it blank (or insert another value like "-" or whatever). I don't want to open all my files to figure out which files have what. The error message I get when I try to extract data from a non-existent column is:
IndexError: list index out of range
Is there a loop that I can write to fix this?
I'm really new to python, and in my head it seems easy but when I try to actually do it it's very difficult.
Thanks
A:
Based on the error message, I'm guessing you have a list of lists that looks something like this (a gross simplification):
[[0,1,2,3],
[1,2,3,4,5],
[1,2,3],
[1,2,3]]
And you are trying to do the following:
for row in xrange(4):
for col in xrange(4):
#something else?
print data[row][col]
And then you're getting your error because one of the values doesn't have an element at index 3:
+------------------------+
| Index: | 0 | 1 | 2 | 3 |
+------------------------+
|Value: | 1 | 2 | 3 | <----- No value at index 3
+--------------------+
Depending on where you're getting your data from originally, there are several different ways to accomplish what you're trying to accomplish.
If you provide sample I/O you'll get much better answers.
A:
I assume you're doing something like:
for line in file:
parts = line.split()
blah = line[2]
And blah doesn't exist for some lines.
You can check the length of lists:
if len(parts) > 2:
blah = line[2]
else:
blah = "" # or whatever
Without any example code it's hard to be more precise, but this is probably a quick and easy fix for what you're doing.
A:
Instead of looping through all your data before you start, you could just catch the Exception and handle it appropriately:
try:
a = list[57]
except IndexError:
a = '-'
| replace empty datasets | Sorry, I agree that was really poorly written:
Take 2:
I have many columns of data (up to 63) in over 50 datasets. I am extracting only 3 columns of data that I need and writing it into a new .csv file. There are a few of my datasets that do not have the third desired column of data. But that's okay I can leave it blank (or insert another value like "-" or whatever). I don't want to open all my files to figure out which files have what. The error message I get when I try to extract data from a non-existent column is:
IndexError: list index out of range
Is there a loop that I can write to fix this?
I'm really new to python, and in my head it seems easy but when I try to actually do it it's very difficult.
Thanks
| [
"Based on the error message, I'm guessing you have a list of lists that looks something like this (a gross simplification):\n[[0,1,2,3],\n[1,2,3,4,5],\n[1,2,3],\n[1,2,3]]\n\nAnd you are trying to do the following:\nfor row in xrange(4):\n for col in xrange(4):\n #something else?\n print data[row][col]... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003477058_python.txt |
Q:
How to assign a value to a variable when writing the value takes multiple lines (python)
I have a variable x to which I want to assign a very long string. Since the string is pretty long I split it into 10 substrings. I would like to do something like this:
x =
'a very long string - part 1'+
'a very long string - part 2'+
'a very long string - part 3'+
...
'a very long string - part 10'
But turns out this is an invalid syntax. What is the valid syntax for that?
A:
If you want a string with no line-feeds, you could
>>> x = (
... 'a very long string - part 1' +
... 'a very long string - part 2' +
... 'a very long string - part 3' )
>>> x
'a very long string - part 1a very long string - part 2a very long string - part 3'
>>>
The + operator is not necessary with string literals:
2.4.2. String literal concatenation
Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings, for example:
re.compile("[A-Za-z_]" # letter or underscore
"[A-Za-z0-9_]*" # letter, digit or underscore
)
Your case:
>>> x = (
... 'a very long string - part 1'
... 'a very long string - part 2'
... 'a very long string - part 3' )
>>> x
'a very long string - part 1a very long string - part 2a very long string - part 3'
>>>
A:
Usually Python will spot that one line continues to the next but if it doesn't put a backslash at the end of each line:
>>> x = 'a' + \
... 'b' + \
... 'c'
>>> x
'abc'
Or use standard syntax like brackets to make it clear:
>>> x = ('a' +
... 'b' +
... 'c')
>>> x
'abc'
You can create a long string using triple quotes - """ - but note that any news lines will be included in the string.
>>> x = """a very long string part 1
... a very long string part 2
... a very long string part 3
... a very long string part 4"""
>>> x
'a very long string part 1\na very long string part 2\na very long string part 3\na very long string part 4'
| How to assign a value to a variable when writing the value takes multiple lines (python) | I have a variable x to which I want to assign a very long string. Since the string is pretty long I split it into 10 substrings. I would like to do something like this:
x =
'a very long string - part 1'+
'a very long string - part 2'+
'a very long string - part 3'+
...
'a very long string - part 10'
But turns out this is an invalid syntax. What is the valid syntax for that?
| [
"If you want a string with no line-feeds, you could\n>>> x = (\n... 'a very long string - part 1' +\n... 'a very long string - part 2' +\n... 'a very long string - part 3' )\n>>> x\n'a very long string - part 1a very long string - part 2a very long string - part 3'\n>>> \n\nThe + operator is not necessary with stri... | [
5,
4
] | [] | [] | [
"python",
"string",
"variable_assignment"
] | stackoverflow_0003477592_python_string_variable_assignment.txt |
Q:
Making python like system calls in java
Is there an equivalent to Python's popen2 in Java?
A:
I believe the Process object is what you're looking for. Javadoc here. You use it something like Process myProcess = System.getRuntime().exec("cmd here")); It allows you to get the standard and error output streams.
A:
System.getRuntime().exec(...)
System.getRuntime() yields the Runtime object, from which you can make various .exec(...) calls that spawn a Process object. This has input and output streams and a status.
| Making python like system calls in java | Is there an equivalent to Python's popen2 in Java?
| [
"I believe the Process object is what you're looking for. Javadoc here. You use it something like Process myProcess = System.getRuntime().exec(\"cmd here\")); It allows you to get the standard and error output streams.\n",
"System.getRuntime().exec(...)\nSystem.getRuntime() yields the Runtime object, from which y... | [
4,
3
] | [] | [] | [
"java",
"python",
"runtime.exec",
"shell",
"unix"
] | stackoverflow_0003478033_java_python_runtime.exec_shell_unix.txt |
Q:
is fftshift broken in scipy?
I use the latest version of numpy/scipy.
The following script does not work:
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, fftshift, fftfreq
hn= np.ones(10)
hF = fft(hn,1024)
shifted = fftshift(hF)
It gives the following error message:
Traceback (most recent call last):
File "D:\deleteme\New3.py", line 6, in <module>
shifted = fftshift(hF)
File "C:\Python26\lib\site-packages\numpy\fft\helper.py", line 40, in fftshift
y = take(y,mylist,k)
File "C:\Python26\lib\site-packages\numpy\core\fromnumeric.py", line 103, in take
return take(indices, axis, out, mode)
TypeError: array cannot be safely cast to required type
EDIT: i have found the problem. My python interpreter was implicitly called (via my editor settings) with the -Qnew option. This apparently breaks scipy code.
Thanks to all who responded!
A:
You should fill in a bug report on http://www.scipy.org/BugReport
A:
Works fine with my setup, if it's a bug in the current version try installing an older copy and filling out a report.
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy.fftpack import fft, fftshift, fftfreq
>>> hn= np.ones(10)
>>> hF = fft(hn,1024)
>>> shifted = fftshift(hF)
>>> shifted
array([ 0.00000000+0.j , 0.00084688+0.03066325j,
0.00338468+0.06122841j, ..., 0.00760489-0.09159769j,
0.00338468-0.06122841j, 0.00084688-0.03066325j])
>>> import sys
>>> sys.version
'2.6.4 (r264:75706, Jan 22 2010, 16:41:54) [MSC v.1500 32 bit (Intel)]'
>>> import numpy
>>> numpy.version.version
'1.3.0'
>>> import scipy
>>> scipy.version.version
'0.7.1'
>>> import matplotlib
>>> matplotlib.__version__
'0.99.1'
>>>
| is fftshift broken in scipy? | I use the latest version of numpy/scipy.
The following script does not work:
import numpy as np
import matplotlib.pyplot as plt
from scipy.fftpack import fft, fftshift, fftfreq
hn= np.ones(10)
hF = fft(hn,1024)
shifted = fftshift(hF)
It gives the following error message:
Traceback (most recent call last):
File "D:\deleteme\New3.py", line 6, in <module>
shifted = fftshift(hF)
File "C:\Python26\lib\site-packages\numpy\fft\helper.py", line 40, in fftshift
y = take(y,mylist,k)
File "C:\Python26\lib\site-packages\numpy\core\fromnumeric.py", line 103, in take
return take(indices, axis, out, mode)
TypeError: array cannot be safely cast to required type
EDIT: i have found the problem. My python interpreter was implicitly called (via my editor settings) with the -Qnew option. This apparently breaks scipy code.
Thanks to all who responded!
| [
"You should fill in a bug report on http://www.scipy.org/BugReport\n",
"Works fine with my setup, if it's a bug in the current version try installing an older copy and filling out a report.\n>>> import numpy as np\n>>> import matplotlib.pyplot as plt\n>>> from scipy.fftpack import fft, fftshift, fftfreq\n>>> hn= ... | [
1,
0
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0003477649_numpy_python_scipy.txt |
Q:
repeat y axis scale along grid line of graph ( matplotlib)
I am new to matplotlib and I am trying to figure out if I can repeat the y axis scale
values along the grid lines of the line graph.
The graph has 2 axis,
x-axis has hourly values and y-axis has temperature values.
I need to show the graph for 48 hours, so it results in a long horizontal graph. when user scrolls through the graph horizontally he has x-axis scale available for reference but
y axis scale is way towards left and is not visible.
I need a way to repeat the y-axis scale(temperature values) along all the graph. Is there any way to achieve this?
Is there any better solution to this problem, apart from repeating the values?
A:
You might take a look at the colorbar from this example:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import EllipseCollection
x = np.arange(10)
y = np.arange(15)
X, Y = np.meshgrid(x, y)
XY = np.hstack((X.ravel()[:,np.newaxis], Y.ravel()[:,np.newaxis]))
ww = X/10.0
hh = Y/15.0
aa = X*9
ax = plt.subplot(1,1,1)
ec = EllipseCollection(
ww,
hh,
aa,
units='x',
offsets=XY,
transOffset=ax.transData)
ec.set_array((X+Y).ravel())
ax.add_collection(ec)
ax.autoscale_view()
ax.set_xlabel('X')
ax.set_ylabel('y')
cbar = plt.colorbar(ec)
cbar.set_label('X+Y')
plt.show()
A quick experiment shows me that you can pan/zoom the main window and the colorbar will stay constant.
| repeat y axis scale along grid line of graph ( matplotlib) | I am new to matplotlib and I am trying to figure out if I can repeat the y axis scale
values along the grid lines of the line graph.
The graph has 2 axis,
x-axis has hourly values and y-axis has temperature values.
I need to show the graph for 48 hours, so it results in a long horizontal graph. when user scrolls through the graph horizontally he has x-axis scale available for reference but
y axis scale is way towards left and is not visible.
I need a way to repeat the y-axis scale(temperature values) along all the graph. Is there any way to achieve this?
Is there any better solution to this problem, apart from repeating the values?
| [
"You might take a look at the colorbar from this example:\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.collections import EllipseCollection\n\nx = np.arange(10)\ny = np.arange(15)\nX, Y = np.meshgrid(x, y)\n\nXY = np.hstack((X.ravel()[:,np.newaxis], Y.ravel()[:,np.newaxis]))\n\nww = X/10.0\... | [
1
] | [] | [] | [
"graph",
"matplotlib",
"python"
] | stackoverflow_0003478320_graph_matplotlib_python.txt |
Q:
django orm and 3 relations
I have a problem to transpose my sql request in the orm.
Well, this my sql request :
SELECT DISTINCT accommodation.id from accommodation
LEFT JOIN product on product.accommodation_id=accommodation.id
LEFT JOIN date on date.product_id = product.id
WHERE date.begin> '2010-08-13';
So i want all the accommodations for a period, without doubloon.
My models are like this :
class Accommodation(models.Model):
...
class Product(models.Model):
...
accommodation = models.ForeignKey(accommodation)
class Date(models.Model):
...
begin = models.DateField()
product = models.ForeignKey(Product)
So for the moment i do that :
dates = Date.objects.filter(begin__gte=values['start_day'],
...)
...
accommodations_dict = {}
for date in dates : accommodations_dict[date.product.accommodation.slug] = True
accommodations = Accommodation.objects.filter(slug__in=accommodations_dict.keys())
Well, it works, but it's slow, I have a lot of dates.
So I think I can get these accommodations with sql, but I don't know how ?
if you have an idea,
thanks.
A:
This should do what you want:
Accommodation.objects.filter(product__date__begin__gte=values['start_day'])
| django orm and 3 relations | I have a problem to transpose my sql request in the orm.
Well, this my sql request :
SELECT DISTINCT accommodation.id from accommodation
LEFT JOIN product on product.accommodation_id=accommodation.id
LEFT JOIN date on date.product_id = product.id
WHERE date.begin> '2010-08-13';
So i want all the accommodations for a period, without doubloon.
My models are like this :
class Accommodation(models.Model):
...
class Product(models.Model):
...
accommodation = models.ForeignKey(accommodation)
class Date(models.Model):
...
begin = models.DateField()
product = models.ForeignKey(Product)
So for the moment i do that :
dates = Date.objects.filter(begin__gte=values['start_day'],
...)
...
accommodations_dict = {}
for date in dates : accommodations_dict[date.product.accommodation.slug] = True
accommodations = Accommodation.objects.filter(slug__in=accommodations_dict.keys())
Well, it works, but it's slow, I have a lot of dates.
So I think I can get these accommodations with sql, but I don't know how ?
if you have an idea,
thanks.
| [
"This should do what you want:\n Accommodation.objects.filter(product__date__begin__gte=values['start_day'])\n\n"
] | [
3
] | [] | [] | [
"django",
"orm",
"python"
] | stackoverflow_0003478346_django_orm_python.txt |
Q:
subprocess.Popen() has inconsistent behavior between Eclipse/PyCharm and terminal execution
The problem I'm having is with Eclipse/PyCharm interpreting the results of subprocess's Popen() differently from a standard terminal. All are using python2.6.1 on OSX.
Here's a simple example script:
import subprocess
args = ["/usr/bin/which", "git"]
print "Will execute %s" % " ".join(args)
try:
p = subprocess.Popen(["/usr/bin/which", "git"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# tuple of StdOut, StdErr is the responses, so ..
ret = p.communicate()
if ret[0] == '' and ret[1] <> '':
msg = "cmd %s failed: %s" % (fullcmd, ret[1])
if fail_on_error:
raise NameError(msg)
except OSError, e:
print >>sys.stderr, "Execution failed:", e
With a standard terminal, the line:
ret = p.communicate()
gives me:
(Pdb) print ret
('/usr/local/bin/git\n', '')
Eclipse and PyCharm give me an empty tuple:
ret = {tuple} ('','')
Changing the shell= value does not solve the problem either. On the terminal, setting shell=True, and passing the command in altogether (i.e., args=["/usr/bin/which git"]) gives me the same result: ret = ('/usr/local/bin/git\n', ''). And Eclipse/PyCharm both give me an empty tuple.
Any ideas on what I could be doing wrong?
A:
Ok, found the problem, and it's an important thing to keep in mind when using an IDE in a Unix-type environment. IDE's operate under a different environment context than the terminal user (duh, right?!). I was not considering that the subprocess was using a different environment than the context that I have for my terminal (my terminal has bash_profile set to have more things in PATH).
This is easily verified by changing the script as follows:
import subprocess
args = ["/usr/bin/which", "git"]
print "Current path is %s" % os.path.expandvars("$PATH")
try:
p = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# tuple of StdOut, StdErr is the responses, so ..
out, err = p.communicate()
if err:
msg = "cmd %s failed: %s" % (fullcmd, err)
except OSError, e:
print >>sys.stderr, "Execution failed:", e
Under the terminal, the path includes /usr/local/bin. Under the IDE it does not!
This is an important gotcha for me - always remember about environments!
| subprocess.Popen() has inconsistent behavior between Eclipse/PyCharm and terminal execution | The problem I'm having is with Eclipse/PyCharm interpreting the results of subprocess's Popen() differently from a standard terminal. All are using python2.6.1 on OSX.
Here's a simple example script:
import subprocess
args = ["/usr/bin/which", "git"]
print "Will execute %s" % " ".join(args)
try:
p = subprocess.Popen(["/usr/bin/which", "git"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# tuple of StdOut, StdErr is the responses, so ..
ret = p.communicate()
if ret[0] == '' and ret[1] <> '':
msg = "cmd %s failed: %s" % (fullcmd, ret[1])
if fail_on_error:
raise NameError(msg)
except OSError, e:
print >>sys.stderr, "Execution failed:", e
With a standard terminal, the line:
ret = p.communicate()
gives me:
(Pdb) print ret
('/usr/local/bin/git\n', '')
Eclipse and PyCharm give me an empty tuple:
ret = {tuple} ('','')
Changing the shell= value does not solve the problem either. On the terminal, setting shell=True, and passing the command in altogether (i.e., args=["/usr/bin/which git"]) gives me the same result: ret = ('/usr/local/bin/git\n', ''). And Eclipse/PyCharm both give me an empty tuple.
Any ideas on what I could be doing wrong?
| [
"Ok, found the problem, and it's an important thing to keep in mind when using an IDE in a Unix-type environment. IDE's operate under a different environment context than the terminal user (duh, right?!). I was not considering that the subprocess was using a different environment than the context that I have for my... | [
15
] | [] | [] | [
"eclipse",
"popen",
"pycharm",
"python",
"subprocess"
] | stackoverflow_0003460130_eclipse_popen_pycharm_python_subprocess.txt |
Q:
How do I dynamically add an attribute to a module from within that module?
Say in a module I want to define:
a = 'a'
b = 'b'
...
z = 'z'
For some set (in this case I chose letters). How do I dynamically set attributes on the current module? Something like:
for letter in ['a', ..., 'z']:
setattr(globals(), letter, letter)
This doesn't work, but what would? (Also my understanding is that globals() within a module points to a dict of the attributes of that module, but feel free to correct me if that's wrong).
A:
globals() returns the dictionary of the current module, so you add items to it as you would to any other dictionary. Try:
for letter in ['a', ..., 'z']:
globals()[letter] = letter
or to eliminate the repeated call to globals():
global_dict = globals()
for letter in ['a', ..., 'z']:
global_dict[letter] = letter
or even:
globals().update((l,l) for l in ['a', ...,'z'])
| How do I dynamically add an attribute to a module from within that module? | Say in a module I want to define:
a = 'a'
b = 'b'
...
z = 'z'
For some set (in this case I chose letters). How do I dynamically set attributes on the current module? Something like:
for letter in ['a', ..., 'z']:
setattr(globals(), letter, letter)
This doesn't work, but what would? (Also my understanding is that globals() within a module points to a dict of the attributes of that module, but feel free to correct me if that's wrong).
| [
"globals() returns the dictionary of the current module, so you add items to it as you would to any other dictionary. Try:\nfor letter in ['a', ..., 'z']:\n globals()[letter] = letter\n\nor to eliminate the repeated call to globals():\nglobal_dict = globals()\nfor letter in ['a', ..., 'z']:\n global_dict[let... | [
10
] | [] | [] | [
"python"
] | stackoverflow_0003478716_python.txt |
Q:
Inspecting urllib2.Request attributes when using OpenerDirector with handlers
Is it possible to inspect the attributes of an Python urllib2.Request (url, data, headers etc) when using an urllib2.OpenerDirector:
cookie_jar = cookielib.CookieJar()
opener = urllib2.OpenerDirector()
opener.add_handler(urllib2.ProxyHandler())
opener.add_handler(urllib2.UnknownHandler())
opener.add_handler(urllib2.HTTPHandler())
opener.add_handler(urllib2.HTTPRedirectHandler())
opener.add_handler(urllib2.HTTPDefaultErrorHandler())
opener.add_handler(urllib2.HTTPSHandler())
opener.add_handler(urllib2.HTTPErrorProcessor())
opener.add_handler(urllib2.HTTPCookieProcessor(cookie_jar))
request = urllib2.Request('http://example.com')
response = opener.open(request)
The request object has no attributes set before being opened. Is there a way to access them?
A:
I'm not sure which attributes you're looking for exactly, but hopefully this answers your question. All of those attributes are in the Request class. To inspect the ones you listed, you can use these:
url = request.get_full_url()
data = request.get_data()
headers = request.headers
There are also functions to modify data/headers/etc.
More can be found in the docs: http://docs.python.org/library/urllib2.html#request-objects
| Inspecting urllib2.Request attributes when using OpenerDirector with handlers | Is it possible to inspect the attributes of an Python urllib2.Request (url, data, headers etc) when using an urllib2.OpenerDirector:
cookie_jar = cookielib.CookieJar()
opener = urllib2.OpenerDirector()
opener.add_handler(urllib2.ProxyHandler())
opener.add_handler(urllib2.UnknownHandler())
opener.add_handler(urllib2.HTTPHandler())
opener.add_handler(urllib2.HTTPRedirectHandler())
opener.add_handler(urllib2.HTTPDefaultErrorHandler())
opener.add_handler(urllib2.HTTPSHandler())
opener.add_handler(urllib2.HTTPErrorProcessor())
opener.add_handler(urllib2.HTTPCookieProcessor(cookie_jar))
request = urllib2.Request('http://example.com')
response = opener.open(request)
The request object has no attributes set before being opened. Is there a way to access them?
| [
"I'm not sure which attributes you're looking for exactly, but hopefully this answers your question. All of those attributes are in the Request class. To inspect the ones you listed, you can use these:\nurl = request.get_full_url()\ndata = request.get_data()\nheaders = request.headers\n\nThere are also functions to... | [
2
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0003478293_python_urllib2.txt |
Q:
Help Creating Python Class with Tkinter
How do I create a class called rectangle that I can pass it the coordinates and a color and have it fill those one?
from Tkinter import *
master = Tk()
w = Canvas(master, width=300, height=300)
w.pack()
class rectangle():
def make(self, ulx, uly, lrx, lry, color):
self.create_rectangle(ulx, uly, lrx, lry, fill=color)
rect1 = rectangle()
rect1.make(0,0,100,100,'blue')
mainloop()
A:
Here is one way of doing it. First, to draw the rectangle on the Tk Canvas you need to call the create_rectangle method of the Canvas. I also use the __init__ method to store the attributes of the rectangle so that you only need to pass the Canvas object as a parameter to the rectangle's draw() method.
from Tkinter import *
class Rectangle():
def __init__(self, coords, color):
self.coords = coords
self.color = color
def draw(self, canvas):
"""Draw the rectangle on a Tk Canvas."""
canvas.create_rectangle(*self.coords, fill=self.color)
master = Tk()
w = Canvas(master, width=300, height=300)
w.pack()
rect1 = Rectangle((0, 0, 100, 100), 'blue')
rect1.draw(w)
mainloop()
EDIT
Answering your question: what is the * in front of self.coords?
To create a rectangle on a Tk Canvas you call the create_rectangle method as follows.
Canvas.create_rectangle(x0, y0, x1, y1, option, ...)
So each of the coords (x0, y0, etc) are indiviual paramaters to the method. However, I have stored the coords of the Rectangle class in a single 4-tuple. I can pass this single tuple into the method call and putting a * in front of it will unpack it into four separate coordinate values.
If I have self.coords = (0, 0, 1, 1), then create_rectangle(*self.coords) will end up as create_rectangle(0, 0, 1, 1), not create_rectangle((0, 0, 1, 1)). Note the inner set of parentheses in the second version.
The Python documentation discusses this in unpacking argument lists.
| Help Creating Python Class with Tkinter | How do I create a class called rectangle that I can pass it the coordinates and a color and have it fill those one?
from Tkinter import *
master = Tk()
w = Canvas(master, width=300, height=300)
w.pack()
class rectangle():
def make(self, ulx, uly, lrx, lry, color):
self.create_rectangle(ulx, uly, lrx, lry, fill=color)
rect1 = rectangle()
rect1.make(0,0,100,100,'blue')
mainloop()
| [
"Here is one way of doing it. First, to draw the rectangle on the Tk Canvas you need to call the create_rectangle method of the Canvas. I also use the __init__ method to store the attributes of the rectangle so that you only need to pass the Canvas object as a parameter to the rectangle's draw() method.\nfrom Tkint... | [
3
] | [] | [] | [
"class",
"python",
"tkinter"
] | stackoverflow_0003479265_class_python_tkinter.txt |
Q:
Renaming OS files
I am trying to rename files based on their extensions. Below is my code, Somehow my os.rename isn't working. There aren't any errors though. I got no idea what is wrong. Hope you guys could help. Thanks.
import os
import glob
directory = raw_input("directory? ")
ext = raw_input("file extension? ")
r = raw_input("replace name")
pattern = os.path.join(directory, "*" + ext)
matching_files = glob.glob(pattern)
file_number = len(matching_files)
for filename in os.listdir(directory):
if ext in filename:
path = os.path.join(directory, filename)
seperated_names = os.path.splitext(filename)[0]
replace_name = filename.replace(seperated_names, r)
split_new_names = os.path.splitext(replace_name)[0]
for pad_number in range(0, file_number):
padded_numbers = "%04d" % pad_number
padded_names = "%s_%s" % (split_new_names, padded_numbers)
newpath = os.path.join(directory, padded_names)
newpathext = "%s%s" % (newpath, ext)
new_name = os.rename(path, newpathext)
A:
I get an error:
directory? c:\breakup
file extension? .txt
replace name? test
Traceback (most recent call last):
File "foo.py", line 25, in <module>
new_name = os.rename(path, newpathext)
WindowsError: [Error 2] The system cannot find the file specified
shell returned 1
Anyhow, it looks like you're over complicating things. This works just fine:
import os
directory = raw_input("directory? ")
ext = raw_input("file extension? ")
r = raw_input("replace name? ")
for i, filename in enumerate(os.listdir(directory)):
if filename.endswith(ext):
oldname = os.path.join(directory, filename)
newname = os.path.join(directory, "%s_%04d%s" % (r, i, ext))
os.rename(oldname, newname)
| Renaming OS files | I am trying to rename files based on their extensions. Below is my code, Somehow my os.rename isn't working. There aren't any errors though. I got no idea what is wrong. Hope you guys could help. Thanks.
import os
import glob
directory = raw_input("directory? ")
ext = raw_input("file extension? ")
r = raw_input("replace name")
pattern = os.path.join(directory, "*" + ext)
matching_files = glob.glob(pattern)
file_number = len(matching_files)
for filename in os.listdir(directory):
if ext in filename:
path = os.path.join(directory, filename)
seperated_names = os.path.splitext(filename)[0]
replace_name = filename.replace(seperated_names, r)
split_new_names = os.path.splitext(replace_name)[0]
for pad_number in range(0, file_number):
padded_numbers = "%04d" % pad_number
padded_names = "%s_%s" % (split_new_names, padded_numbers)
newpath = os.path.join(directory, padded_names)
newpathext = "%s%s" % (newpath, ext)
new_name = os.rename(path, newpathext)
| [
"I get an error: \ndirectory? c:\\breakup\nfile extension? .txt\nreplace name? test\nTraceback (most recent call last):\n File \"foo.py\", line 25, in <module>\n new_name = os.rename(path, newpathext)\nWindowsError: [Error 2] The system cannot find the file specified\nshell returned 1\n\nAnyhow, it looks like y... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003478237_python.txt |
Q:
How do I dynamically create a function with the same signature as another function?
I'm busy creating a metaclass that replaces a stub function on a class with a new one with a proper implementation. The original function could use any signature. My problem is that I can't figure out how to create a new function with the same signature as the old one. How would I do this?
Update
This has nothing to do with the actual question which is "How do I dynamically create a function with the same signature as another function?" but I'm adding this to show why I can't use subclasses.
I'm trying to implement something like Scala Case Classes in Python. (Not the pattern matching aspect just the automatically generated properties, eq, hash and str methods.)
I want something like this:
>>> class MyCaseClass():
... __metaclass__ = CaseMetaClass
... def __init__(self, a, b):
... pass
>>> instance = MyCaseClass(1, 'x')
>>> instance.a
1
>>> instance.b
'x'
>>> str(instance)
MyCaseClass(1, 'x')
As far as I can see, there is no way to that with subclasses.
A:
I believe functools.wraps does not reproduce the original call signature. However, Michele Simionato's decorator module does:
import decorator
class FooType(type):
def __init__(cls,name,bases,clsdict):
@decorator.decorator
def modify_stub(func, *args,**kw):
return func(*args,**kw)+' + new'
setattr(cls,'stub',modify_stub(clsdict['stub']))
class Foo(object):
__metaclass__=FooType
def stub(self,a,b,c):
return 'original'
foo=Foo()
help(foo.stub)
# Help on method stub in module __main__:
# stub(self, a, b, c) method of __main__.Foo instance
print(foo.stub(1,2,3))
# original + new
A:
It is possible to do this, using inspect.getargspecs. There's even a PEP in place to make it easier.
BUT -- this is not a good thing to do. Can you imagine how much of a debugging/maintenance nightmare it would be to have your functions dynamically created at runtime -- and not only that, but done so by a metaclass?! I don't understand why you have to replace the stub dynamically; can't you just change the code when you want to change the function? I mean, suppose you have a class
class Spam( object ):
def ham( self, a, b ):
return NotImplemented
Since you don't know what it's meant to do, the metaclass can't actually implement any functionality. If you knew what ham were meant to do, you could do it in ham or one of its parent classes, instead of returning NotImplemented.
A:
use functools.wraps
>>> from functools import wraps
>>> def f(a,b):
return a+b
>>> @wraps(f)
def f2(*args):
print(args)
return f(*args)
>>> f2(2,5)
(2, 5)
7
| How do I dynamically create a function with the same signature as another function? | I'm busy creating a metaclass that replaces a stub function on a class with a new one with a proper implementation. The original function could use any signature. My problem is that I can't figure out how to create a new function with the same signature as the old one. How would I do this?
Update
This has nothing to do with the actual question which is "How do I dynamically create a function with the same signature as another function?" but I'm adding this to show why I can't use subclasses.
I'm trying to implement something like Scala Case Classes in Python. (Not the pattern matching aspect just the automatically generated properties, eq, hash and str methods.)
I want something like this:
>>> class MyCaseClass():
... __metaclass__ = CaseMetaClass
... def __init__(self, a, b):
... pass
>>> instance = MyCaseClass(1, 'x')
>>> instance.a
1
>>> instance.b
'x'
>>> str(instance)
MyCaseClass(1, 'x')
As far as I can see, there is no way to that with subclasses.
| [
"I believe functools.wraps does not reproduce the original call signature. However, Michele Simionato's decorator module does:\nimport decorator\n\nclass FooType(type):\n def __init__(cls,name,bases,clsdict):\n @decorator.decorator \n def modify_stub(func, *args,**kw):\n return fu... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003479412_python.txt |
Q:
Accessing the same function from two different classes
I have two classes, suppose A and B. Within B, I instantiate A.
I have a function func() that is required by both the classes.
How should I go about it? I had thought of this approach:
class A:
func()
class B:
x = A()
func()
def func():
And then I can access func() from within A or B. Is this approach OK or is there a better way to do this (perhaps using an OO approach)
Note that I am new to OO programming and that is why I am interested in knowing whether I can apply any OO design to this.
Edit: The function can differ in the arguments it takes.
A:
Define func before you define either class, and it will be available to both.
A:
func here can me a method of common base class
class Base(object):
def func():
#...
class A(Base):
#...
class B(Base):
#...
| Accessing the same function from two different classes | I have two classes, suppose A and B. Within B, I instantiate A.
I have a function func() that is required by both the classes.
How should I go about it? I had thought of this approach:
class A:
func()
class B:
x = A()
func()
def func():
And then I can access func() from within A or B. Is this approach OK or is there a better way to do this (perhaps using an OO approach)
Note that I am new to OO programming and that is why I am interested in knowing whether I can apply any OO design to this.
Edit: The function can differ in the arguments it takes.
| [
"Define func before you define either class, and it will be available to both.\n",
"func here can me a method of common base class\nclass Base(object):\n def func():\n #...\nclass A(Base):\n #...\nclass B(Base):\n #...\n\n"
] | [
1,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003479514_oop_python.txt |
Q:
Importing module with context
I have a module named module.py, which checks a global variable in context.
module.py:
----------
if 'FOO' in globals():
print 'FOO in globals'
else:
print 'nah'
in python shell:
----------------
In [1]: FOO = True
In [2]: import module
nah
how can I import modules with existing context?
A:
This is rather hackish -- don't rely on this for production code since not all implementations of Python have a inspect.getouterframes function. However, this works in CPython:
import inspect
record=inspect.getouterframes(inspect.currentframe())[1]
frame=record[0]
if 'FOO' in frame.f_globals:
print 'FOO in globals'
else:
print 'nah'
% python
>>> import test
nah
>>>
% python
>>> FOO=True
>>> import test
FOO in globals
>>>
A:
Calling globals in module.py will yield the global variables in the module's scope. I assume you want it to look at the globals in the scope of the interpreter? The short answer is that you can't do that, and you shouldn't want to. If it needs an option, set that option deliberately, but don't refer to a magic global.
If you must, you can pass the interpreter's globals with
modules.update_config( globals( ) )
| Importing module with context | I have a module named module.py, which checks a global variable in context.
module.py:
----------
if 'FOO' in globals():
print 'FOO in globals'
else:
print 'nah'
in python shell:
----------------
In [1]: FOO = True
In [2]: import module
nah
how can I import modules with existing context?
| [
"This is rather hackish -- don't rely on this for production code since not all implementations of Python have a inspect.getouterframes function. However, this works in CPython:\nimport inspect\nrecord=inspect.getouterframes(inspect.currentframe())[1]\nframe=record[0]\n\nif 'FOO' in frame.f_globals:\n print 'FOO... | [
2,
0
] | [] | [] | [
"global",
"import",
"python",
"scope"
] | stackoverflow_0003479934_global_import_python_scope.txt |
Q:
need help optimizing a geo algorithm using a map() operation, lists, floats and some validation
Im doing som route(geo) calculations.
I need to sort out some routes going in the "wrong" direction...
all rides have "routes" and all routes consist of a lot of steps on the route.... each step has a lat. and a lng. pair.
I hope this makes sense?
This is the way i do it now, and it works... however... im performing this operation on many(!) rides..routes...coordinate-pairs, so i could use a little speed-up in my code.
for ride in initial_rides:
steps = ride.route.steps.all()
for step in steps:
if lat_min < step.latitude< lat_max and lng_min< step.longitude< lng_max:
approved_rides.append(ride)
break
I better admit already that i'm no super programmer :)
i have tried construction something like this(without any luck):
for i in ride:
number = sum(itertools.ifilter(lambda x: lat_min< x.latitude< lat_max and lng_min< x.longitude< lng_max, ride.route.steps.all()))
if number >= 1:
approved_rides.append(ride)
tried to combine lambda and ifilter however i get an error saying operator doesn't support types "int" and "step"... Am i doing something wrong?
should i be using list comprehensions?? map()?? or something else?
i have read through http://www.python.org/doc/essays/list2str.html without any luck.
any help is greatly appreciated. thank you, and good day :)
Peter
A:
To speed this up you should probably be using a better algorithm instead of trying all possible solutions. A* is a classic heuristic that could work on your problem.
You can try a comprehension like
approved_rides = [ride for ride in initial_rides if any(
(lat_min < step.latitude< lat_max and \
lng_min< step.longitude< lng_max) for step in ride.route.steps.all())]
which is your first code block as a oneliner.
If you can please give me a number how much faster it is, I'm interested :-)
A:
The reason for the error is that you are calling sum on a list of things that you can't sum, namely, ride.route.steps.all(). I assume that gives list of steps; what were you intending to do by summing them?
You can count the number of elements in a list with len.
I think you are trying to do the following:
key = lambda x: lat_min< x.latitude< lat_max and lng_min< x.longitude< lng_max
approved_rides = [ ride for ride in rides if any( map( key, ride.route.steps.all( ) ) ) ]
That will make approved_rides a list of the rides any of whose ride.roude.steps.all( ) satisfies key.
| need help optimizing a geo algorithm using a map() operation, lists, floats and some validation | Im doing som route(geo) calculations.
I need to sort out some routes going in the "wrong" direction...
all rides have "routes" and all routes consist of a lot of steps on the route.... each step has a lat. and a lng. pair.
I hope this makes sense?
This is the way i do it now, and it works... however... im performing this operation on many(!) rides..routes...coordinate-pairs, so i could use a little speed-up in my code.
for ride in initial_rides:
steps = ride.route.steps.all()
for step in steps:
if lat_min < step.latitude< lat_max and lng_min< step.longitude< lng_max:
approved_rides.append(ride)
break
I better admit already that i'm no super programmer :)
i have tried construction something like this(without any luck):
for i in ride:
number = sum(itertools.ifilter(lambda x: lat_min< x.latitude< lat_max and lng_min< x.longitude< lng_max, ride.route.steps.all()))
if number >= 1:
approved_rides.append(ride)
tried to combine lambda and ifilter however i get an error saying operator doesn't support types "int" and "step"... Am i doing something wrong?
should i be using list comprehensions?? map()?? or something else?
i have read through http://www.python.org/doc/essays/list2str.html without any luck.
any help is greatly appreciated. thank you, and good day :)
Peter
| [
"To speed this up you should probably be using a better algorithm instead of trying all possible solutions. A* is a classic heuristic that could work on your problem.\nYou can try a comprehension like \napproved_rides = [ride for ride in initial_rides if any(\n (lat_min < step.latitude< lat_max and \\\n ... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003479989_python.txt |
Q:
How to setup web2py fixtures
I'm trying to find a way to create fixtures for my web2py application. I came across http://thadeusb.com/weblog/2010/4/21/using_fixtures_in_web2py that suggests creating a x_fixtures.py file to place all the fixtures in. The problem is that after a while, the file gets huge and a pain to navigate through.
What I want to be able to do is have a folder named fixtures/ and place all my fixtures in separate files named after the table they're for.
The Official Web2py Book says "tests is a directory for storing test scripts, fixtures and mocks.", but I haven't been able to get that to work either. The project didn't have a tests directory by default, so I had to create one.
Has anyone setup fixtures in this way using web2py before? If not, any suggestions on what to try next?
A:
Well, I couldn't figure out how to get the fixtures to work while in the directory I created web2py/applications/MyApp/tests/fixtures, but I did get fixtures to work how I wanted by simply creating a web2py/applications/MyApp/models/fixtures directory and placing a separate file for each table I want fixtures for following the pattern of x_fixtures_TABLE_NAME.py.
| How to setup web2py fixtures | I'm trying to find a way to create fixtures for my web2py application. I came across http://thadeusb.com/weblog/2010/4/21/using_fixtures_in_web2py that suggests creating a x_fixtures.py file to place all the fixtures in. The problem is that after a while, the file gets huge and a pain to navigate through.
What I want to be able to do is have a folder named fixtures/ and place all my fixtures in separate files named after the table they're for.
The Official Web2py Book says "tests is a directory for storing test scripts, fixtures and mocks.", but I haven't been able to get that to work either. The project didn't have a tests directory by default, so I had to create one.
Has anyone setup fixtures in this way using web2py before? If not, any suggestions on what to try next?
| [
"Well, I couldn't figure out how to get the fixtures to work while in the directory I created web2py/applications/MyApp/tests/fixtures, but I did get fixtures to work how I wanted by simply creating a web2py/applications/MyApp/models/fixtures directory and placing a separate file for each table I want fixtures for ... | [
1
] | [] | [] | [
"fixtures",
"python",
"web2py"
] | stackoverflow_0003477424_fixtures_python_web2py.txt |
Q:
A simple Python HTTP proxy
What is the simplest way to create a HTTP proxy with Python? As far as I can understand, it should be possible to create the proxy relatively easily with a couple lines of code using the standard library HTTP server features and urlopen or Requests.
A:
One incredibly simple one is python-proxy. I found it on the list of python proxies at xhaus, which was the top result when I googled "python proxy server" (sans quotes).
A:
Twisted lets you build simple ones, if you don't mind the complexity that is twisted.
| A simple Python HTTP proxy | What is the simplest way to create a HTTP proxy with Python? As far as I can understand, it should be possible to create the proxy relatively easily with a couple lines of code using the standard library HTTP server features and urlopen or Requests.
| [
"One incredibly simple one is python-proxy. I found it on the list of python proxies at xhaus, which was the top result when I googled \"python proxy server\" (sans quotes).\n",
"Twisted lets you build simple ones, if you don't mind the complexity that is twisted.\n"
] | [
7,
4
] | [] | [] | [
"proxy",
"python"
] | stackoverflow_0003480147_proxy_python.txt |
Q:
How to close stdout/stderr window in python?
In my python app, I print some stuff during a cycle.
After the cycle, I want to close the stdout/stderr window that the prints produced using python code.
A:
import sys
sys.stdout.close()
sys.stderr.close()
Might be what you want. This will certainly close stdout/stderr at any rate.
A:
If you mean the prompt window that opens when you run a Python script on MS Windows, try specifying the executable pythonw instead of python, on the first line of your script.
| How to close stdout/stderr window in python? | In my python app, I print some stuff during a cycle.
After the cycle, I want to close the stdout/stderr window that the prints produced using python code.
| [
"import sys\n\nsys.stdout.close()\nsys.stderr.close()\n\nMight be what you want. This will certainly close stdout/stderr at any rate.\n",
"If you mean the prompt window that opens when you run a Python script on MS Windows, try specifying the executable pythonw instead of python, on the first line of your script... | [
7,
0
] | [] | [] | [
"printing",
"python",
"window"
] | stackoverflow_0003480371_printing_python_window.txt |
Q:
Twisted vs Google App Engine in serving mobile clients
So far I have been using Twisted to simultaneously serve a lot of mobile clients (Android, iPhone) with their HTTP requests exchanging JSON messages.
For my next project I'd like to try out Google App Engine, but I'm wondering if it is capable of doing the same or if I should rather go with a custom built solution again.
A:
Certainly. App Engine will scale your application up as the load increases automatically and will be spread over many machines. The web api they have is pretty nice too. You don't have to worry about deferreds either because it scales by bringing more instances up instead of making things asynchronous.
BTW: I have web services hosted on app engine that are consumed by iPhone.
| Twisted vs Google App Engine in serving mobile clients | So far I have been using Twisted to simultaneously serve a lot of mobile clients (Android, iPhone) with their HTTP requests exchanging JSON messages.
For my next project I'd like to try out Google App Engine, but I'm wondering if it is capable of doing the same or if I should rather go with a custom built solution again.
| [
"Certainly. App Engine will scale your application up as the load increases automatically and will be spread over many machines. The web api they have is pretty nice too. You don't have to worry about deferreds either because it scales by bringing more instances up instead of making things asynchronous.\nBTW: I hav... | [
6
] | [] | [] | [
"google_app_engine",
"python",
"twisted"
] | stackoverflow_0003480524_google_app_engine_python_twisted.txt |
Q:
Is it good style to call bash commands within a Python script using os.system("bash code")?
I was wondering whether or not it is considered a good style to call bash commands within a Python script using os.system(). I was also wondering whether or not it is safe to do so as well.
I know how to implement some of the functionality I need in Bash and in Python, but it is much simpler and more intuitive to implement it in Bash. However, I feel like it is very hackish to write os.system("bash code").
Specifically, I want to move all files that end with a certain extension to a directory.
In bash: *mv .ext /path/to/destination
In Python (Pseudocode):
for file in directory:
if file.endswith("ext"):
move file to destination
In this case, what should I do?
A:
First of all, your example uses mv, which is a program in coreutils, not bash.
Using os.system() calls to external programs is considered poor style because:
You are creating platform-specific dependencies
You are creating version-specific dependencies (Yes, even coreutils change sometimes!)
You need to check for the existence of external commands (and that they are in $PATH, and executable by the user etc.)
You have to wrap the commands with error checking using their return code. It is much nicer to use in-language error-codes or exceptions. (os.system() does not let you parse stdout/stderr)
You have to deal with quoting variables with spaces yourself (or escaping them)
Python has already done the work for you by supplying the libraries!
Look up glob, for shell-like pattern matching (globbing), and shutil, as others have already mentioned. Otherwise, everything you need is already in the standard libraries.
import glob
import shutil
for extfile in glob.glob('*.ext'):
shutil.move(extfile,dest)
In addition, os.system() should not be used - take a look at the subprocess module instead.
A:
Check out Python's shutil module. It offers file system operations such as moving files. Between that and the os module, you should have all the tools you need. This is preferable to the bash commands for the reasons others said.
A:
It always better and better style to use Python functions to do this kind of stuff. With Python it's not that hard to write a script in an OS-independent way instead of using bash.
A:
Some reasons why you should use pure Python,
By using Python, you have already made the assumption that Python and the standard libraries are installed. By using Bash code inside of Python you are making this assumption plus the assumption that Bash is installed and on the system path.
By using a combination of two languages you are making the code more difficult for others to read (not everyone knows Python and Bash)
If you do it the Python way it will feel more natural before long - less lines of code is not always better
In this case, I would use ...
import os
for filename in os.listdir('.'):
if filename.endswith('.ext'):
os.rename(filename, os.path.join('path', 'to', 'new', 'destination', filename))
There may be better ways though
A:
It's not idea, since it makes your script a lot less portable. A native python script can run on any unix or windows machine that has the proper python libraries installed. When you add shell commands into the mix, you break that, and suddenly are locked down to a much narrower subset.
Sometimes you don't have a choice, but if it's something as simple as that, writing the code natively in python would make a lot more sense, and also be faster to boot (since the python process won't have to spawn a new shell just to execute the one command).
A:
The quoting issues alone suggest that a pure Python solution is preferable.
A:
More generally, Python provides the 'subprocess' module that will allow you to run commands and exercise extensive control over their output. It lets you "spawn new processes, connect to their input/output/error pipes, and obtain their return codes":
http://docs.python.org/library/subprocess.html
| Is it good style to call bash commands within a Python script using os.system("bash code")? | I was wondering whether or not it is considered a good style to call bash commands within a Python script using os.system(). I was also wondering whether or not it is safe to do so as well.
I know how to implement some of the functionality I need in Bash and in Python, but it is much simpler and more intuitive to implement it in Bash. However, I feel like it is very hackish to write os.system("bash code").
Specifically, I want to move all files that end with a certain extension to a directory.
In bash: *mv .ext /path/to/destination
In Python (Pseudocode):
for file in directory:
if file.endswith("ext"):
move file to destination
In this case, what should I do?
| [
"First of all, your example uses mv, which is a program in coreutils, not bash.\nUsing os.system() calls to external programs is considered poor style because:\n\nYou are creating platform-specific dependencies\nYou are creating version-specific dependencies (Yes, even coreutils change sometimes!)\nYou need to chec... | [
18,
6,
3,
2,
1,
1,
0
] | [] | [] | [
"bash",
"embedding",
"python",
"scripting",
"security"
] | stackoverflow_0003479728_bash_embedding_python_scripting_security.txt |
Q:
Algorithm Help: Building game board, but need to know when square is locked in
I have built a gameboard that consists of a grid, the grid is then randomly assigned, "Walls" to a cell. Once the cells are built, how can I check to see if a certain cell is 'locked in' so that I don't place a player there.
I have thought about this and the first ago I came up with check all sides for four walls, but obviously, a cell could be surrounded by open cells, which are then surrounded by walls.
The other is a "escape to outside" algo, which basically tries to find a path to an outside wall, which would then mean it is not locked in, but if the block is on an outside wall and surrounded by blocks it would be locked in.
How is this typically handled? I'm using python if that matters for any code examples.
Thanks!
A:
You basically want a floodfill algorithm.
http://en.wikipedia.org/wiki/Floodfill
edit
I think I misunderstood your definitions of 'locked' and 'escape'.
If you have limited game board, every cell there is locked in some space. If I understand you correctly, you just want that space to be big enough. Well, you compute its area easily with flood fill algorithm.
A:
It really depends on the size of your game board. If we are speaking of small boards, a quick path finding algorithm can give you the distance between every cell and each other. This might have a double use if you do not want to place the player too close to other players or other features.
A second option is to design a wall generator that by principle cannot create locked rooms. The roguelike community has done a decent amount of research into the topic of generating random (dungeon-sized) maps without closed rooms.
Finally, using a level of detail approach can help you if you have to find a suitably large empty space on a huge map. Find an interconnection graph for a set of sparse points distributed over your map (this can be a direct result of your map generator). That should be sufficient to place a player. But if you need more detail on a specific point, finding a path to one of these points can tell you if a room is locked in. This might not work in extremely dense labyrinths.
A:
I'm not sure exactly what your game board can look like, but if you have something like this:
+----------------------+
| +-----+ |
| | c | |
| | | |
| +-----+ |
| |
| |
| |
+----------------------+
And you want to avoid putting the character on the c because it's 'walled in', even though it's it's not exactly surrounded by the walls, you could easily implement the Left-or-Right Hand algorithm - only instead of trying to get out of the maze you're checking to see if you make it back to the same coordinate.
A:
Maybe this previous post is what you are looking for. In that post, I answered how to count the number of different areas of dots there was on a grid on which dots could be placed. Your problem is similar, except instead of having "dots", you have walls. The algorithm given in that post will give you a version of your grid G, where
G[x1][y1] == G[x2][y2]
only if it is possible for a player to get from (x1,y1) to (x2,y2), i.e., if there is a clear path with no walls from that first point to the second point.
Is this what you are looking for? Do you want additional details, or do you want me to adapt that code to your particular problem?
| Algorithm Help: Building game board, but need to know when square is locked in | I have built a gameboard that consists of a grid, the grid is then randomly assigned, "Walls" to a cell. Once the cells are built, how can I check to see if a certain cell is 'locked in' so that I don't place a player there.
I have thought about this and the first ago I came up with check all sides for four walls, but obviously, a cell could be surrounded by open cells, which are then surrounded by walls.
The other is a "escape to outside" algo, which basically tries to find a path to an outside wall, which would then mean it is not locked in, but if the block is on an outside wall and surrounded by blocks it would be locked in.
How is this typically handled? I'm using python if that matters for any code examples.
Thanks!
| [
"You basically want a floodfill algorithm.\nhttp://en.wikipedia.org/wiki/Floodfill\nedit\nI think I misunderstood your definitions of 'locked' and 'escape'.\nIf you have limited game board, every cell there is locked in some space. If I understand you correctly, you just want that space to be big enough. Well, you ... | [
2,
1,
1,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0003480515_algorithm_python.txt |
Q:
VCS checkout based on a file
I want to checkout a bunch of files from a CVS server.
Is there a way I can pass cvs command a file name which contains files I want to checkout
Is there another way of accomplishing that?
A:
You might want to take a look at the docs for the CVSROOT/modules file and then define a regular module like this:
MyModule folder file1 file2 file3 [...]
You would then be able to do:
cvs co MyModule
A:
Assuming you are using a bash-style shell:
cvs co $(< myfile)
Where myfile contains the list of files you want to check out.
If you're talking about modules instead of files, Oliver Giesen's answer will be useful.
| VCS checkout based on a file | I want to checkout a bunch of files from a CVS server.
Is there a way I can pass cvs command a file name which contains files I want to checkout
Is there another way of accomplishing that?
| [
"You might want to take a look at the docs for the CVSROOT/modules file and then define a regular module like this:\nMyModule folder file1 file2 file3 [...]\n\nYou would then be able to do:\ncvs co MyModule\n\n",
"Assuming you are using a bash-style shell:\ncvs co $(< myfile)\n\nWhere myfile contains the list of ... | [
1,
1
] | [] | [] | [
"cvs",
"python",
"scripting",
"vcs_checkout"
] | stackoverflow_0003423666_cvs_python_scripting_vcs_checkout.txt |
Q:
Sorting scheduled events python
So I have list of events that are sort of like alarms. They're defined by their start and end time (in hours and minutes), a range of days (ie 1-3 which is sunday through wed.), and a range of months (ie 1-3, january through march). The format of that data is largely unchangeable. I need to, not necessarily sort the list, but I need to find the next upcoming event based on the current time. There's just so many different ways to do this and so many different corner cases. This is my pseudo code:
now = time()
diff = []
# Start difference between now and start times
for s in schedule #assuming appending to diff
diff.minutes = s.minutes - time.minutes #
diff.hours = s.hours - time.hours
diff.days = s.days - time.days
diff.months = s.months - time.months
for d in diff
if d < 0
d = period + d
# period is the maximum period of the attribute. ie minutes is 60, hours is 24
# repeat for event end times
So now I have a list of tuples of differences in hours, minutes, days, and weeks. This tuple already takes into account if it's passed the start time, but before the end time. So let's say it's in August and the start month of the event is July and the end month is September, so diff.month == 0.
Now this specific corner case is giving me trouble:
Let's say a schedule runs from 0 to 23:59 thursdays in august. And it's Friday the 27th. Running my algorithm, the difference in months would be 0 when in reality it won't run again until next august, so it should be 12. And I'm stuck. The month is the only problem I think because the month is the only attribute that directly depends on what the date of the specific month is (versus just the day). Is my algorithm OK and I can just deal with this special case? Or is there something better out there for this?
This is the data I'm working with
map['start_time']=''
map['end_time']=''
map['start_moy']=''
map['end_moy']=''
map['start_dow']=''
map['end_dow']=''
The schedule getAllSchedules method just returns a list to all of the schedules. I can change the schedule class but I'm not sure what difference I can make there. I can't add/change the format of the schedules I'm given
A:
Convert the items from the schedule into datetime objects. Then you can simply sort them
from datetime import datetime
events = sorted(datetime(s.year, s.month, s.day, s.hour, s.minute) for s in schedule)
A:
Since your resolution is in minutes, and assuming that you don't have many events, then I'd simply scan all the events every minute.
Filter your events so that you have a new list where the event range match the current month and day.
Then for each of those events declare that they are active or inactive according to whether the current time matches the event's range.
A:
The primary issue seems to be with the fact that you're using the day of the week, instead of explicit days of the month.
While your cited edge case is one example, does this issue not crop up with all events scheduled in any month outside of the current one?
I think the most robust approach here would be to do the work to get your scheduled events into datetime format, then use @gnibbler's suggestion of sorting the datetime objects.
Once you have determined that the last event for the current month has already passed, calculate the distance to the next month the event occurs in (be it + 1 year, or just + 1 month), then construct a datetime object with that information:
first_of_month = datetime.date(calculated_year, calculated_month, 1)
By using the first day of the month, you can then use:
day_of_week = first_of_month.strftime('%w')
To give you what day of the week the first of that month falls on, which you can then use to calculate how many days to add to get to the first, second, third, etc. instance of a given day of the week, for that month. Once you have that day, you can construct a valid datetime object and do whatever comparisons you wish with now().
A:
I couldn't figure out how to do it using only datetimes. But I found a module and used this. It's perfect
http://labix.org/python-dateutil
| Sorting scheduled events python | So I have list of events that are sort of like alarms. They're defined by their start and end time (in hours and minutes), a range of days (ie 1-3 which is sunday through wed.), and a range of months (ie 1-3, january through march). The format of that data is largely unchangeable. I need to, not necessarily sort the list, but I need to find the next upcoming event based on the current time. There's just so many different ways to do this and so many different corner cases. This is my pseudo code:
now = time()
diff = []
# Start difference between now and start times
for s in schedule #assuming appending to diff
diff.minutes = s.minutes - time.minutes #
diff.hours = s.hours - time.hours
diff.days = s.days - time.days
diff.months = s.months - time.months
for d in diff
if d < 0
d = period + d
# period is the maximum period of the attribute. ie minutes is 60, hours is 24
# repeat for event end times
So now I have a list of tuples of differences in hours, minutes, days, and weeks. This tuple already takes into account if it's passed the start time, but before the end time. So let's say it's in August and the start month of the event is July and the end month is September, so diff.month == 0.
Now this specific corner case is giving me trouble:
Let's say a schedule runs from 0 to 23:59 thursdays in august. And it's Friday the 27th. Running my algorithm, the difference in months would be 0 when in reality it won't run again until next august, so it should be 12. And I'm stuck. The month is the only problem I think because the month is the only attribute that directly depends on what the date of the specific month is (versus just the day). Is my algorithm OK and I can just deal with this special case? Or is there something better out there for this?
This is the data I'm working with
map['start_time']=''
map['end_time']=''
map['start_moy']=''
map['end_moy']=''
map['start_dow']=''
map['end_dow']=''
The schedule getAllSchedules method just returns a list to all of the schedules. I can change the schedule class but I'm not sure what difference I can make there. I can't add/change the format of the schedules I'm given
| [
"Convert the items from the schedule into datetime objects. Then you can simply sort them\nfrom datetime import datetime\nevents = sorted(datetime(s.year, s.month, s.day, s.hour, s.minute) for s in schedule)\n\n",
"Since your resolution is in minutes, and assuming that you don't have many events, then I'd simply ... | [
1,
1,
1,
0
] | [] | [] | [
"calendar",
"date",
"python",
"sorting"
] | stackoverflow_0003471923_calendar_date_python_sorting.txt |
Q:
Union-within-structure syntax in ctypes
Quick question about ctypes syntax, as documentation for Unions isn't clear for a beginner like me.
Say I want to implement an INPUT structure (see here):
typedef struct tagINPUT {
DWORD type;
union {
MOUSEINPUT mi;
KEYBDINPUT ki;
HARDWAREINPUT hi;
} ;
} INPUT, *PINPUT;
Should I or do I need to change the following code?
class INPUTTYPE(Union):
_fields_ = [("mi", MOUSEINPUT),
("ki", KEYBDINPUT),
("hi", HARDWAREINPUT)]
class INPUT(Structure):
_fields_ = [("type", DWORD),
(INPUTTYPE)]
Not sure I can have an unnamed field for the union, but adding a name that isn't defined in the Win32API seems dangerous.
Thanks,
Mike
A:
Your Structure syntax isn't valid:
AttributeError: '_fields_' must be a sequence of pairs
I believe you want to use the anonymous attribute in your ctypes.Structure. It looks like the ctypes documentation creates a TYPEDESC structure (which is very similar in construction to the tagINPUT).
Also note that you'll have to define DWORD as a base type for your platform.
| Union-within-structure syntax in ctypes | Quick question about ctypes syntax, as documentation for Unions isn't clear for a beginner like me.
Say I want to implement an INPUT structure (see here):
typedef struct tagINPUT {
DWORD type;
union {
MOUSEINPUT mi;
KEYBDINPUT ki;
HARDWAREINPUT hi;
} ;
} INPUT, *PINPUT;
Should I or do I need to change the following code?
class INPUTTYPE(Union):
_fields_ = [("mi", MOUSEINPUT),
("ki", KEYBDINPUT),
("hi", HARDWAREINPUT)]
class INPUT(Structure):
_fields_ = [("type", DWORD),
(INPUTTYPE)]
Not sure I can have an unnamed field for the union, but adding a name that isn't defined in the Win32API seems dangerous.
Thanks,
Mike
| [
"Your Structure syntax isn't valid:\nAttributeError: '_fields_' must be a sequence of pairs\n\nI believe you want to use the anonymous attribute in your ctypes.Structure. It looks like the ctypes documentation creates a TYPEDESC structure (which is very similar in construction to the tagINPUT).\nAlso note that you... | [
11
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003480240_ctypes_python.txt |
Q:
Python csv: UnicodeDecodeError
I'm reading in a file with Python's csv module, and have Yet Another Encoding Question (sorry, there are so many on here).
In the CSV file, there are £ signs. After reading the row in and printing it, they have become \xa3.
Trying to encode them as Unicode produces a UnicodeDecodeError:
row = [unicode(x.strip()) for x in row]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 0: ordinal not in range(128)
I have been reading the csv documentation and the numerous other questions about this on StackOverflow. I think that £ becoming \xa3 in ASCII means that the original CSV file is in UTF-8.
(Incidentally, is there a quick way to check the encoding of a CSV file?)
If it's in UTF-8, then shouldn't the csv module be able to cope with it? It seems to be transforming all the symbols into ASCII, even though the documentation claims it accepts UTF-8.
I've tried adding a unicode_csv_reader function as described in the csv examples, but it doesn't help.
---- EDIT -----
I should clarify one thing. I have seen this question, which looks very similar. But adding the unicode_csv_reader function defined there produces a different error instead:
yield [unicode(cell, 'utf-8') for cell in row]
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa3 in position 8: unexpected code byte
So maybe my file isn't UTF8 after all? How can I tell?
A:
Try using the "ISO-8859-1" for your encoding. It seems like you are dealing with extended ASCII, not Unicode.
Edit:
Here's some simple code that deals with extended ASCII:
>>> s = "La Pe\xf1a"
>>> print s
La Pe±a
>>> print s.decode("latin-1")
La Peña
>>>
Even better, dealing with the exact character that is giving you problems:
>>> s = "12\xa3"
>>> print s.decode("latin-1")
12£
>>>
A:
If you are on Windows, it is highly likely that the encoding that you should use is one of the cp125X family ... e.g. if you are in Western Europe or the Americas, it will be cp1252. Windows software often uses bytes in the range \x80 to \x9F inclusive to encode fancy punctuation characters whereas that range is reserved in ISO-8859-X for the rarely used "C1 Control Characters".
You can find out the usual encoding in your locale by running this at the command line:
python -c "import locale; print locale.getpreferredencoding()"
| Python csv: UnicodeDecodeError | I'm reading in a file with Python's csv module, and have Yet Another Encoding Question (sorry, there are so many on here).
In the CSV file, there are £ signs. After reading the row in and printing it, they have become \xa3.
Trying to encode them as Unicode produces a UnicodeDecodeError:
row = [unicode(x.strip()) for x in row]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 0: ordinal not in range(128)
I have been reading the csv documentation and the numerous other questions about this on StackOverflow. I think that £ becoming \xa3 in ASCII means that the original CSV file is in UTF-8.
(Incidentally, is there a quick way to check the encoding of a CSV file?)
If it's in UTF-8, then shouldn't the csv module be able to cope with it? It seems to be transforming all the symbols into ASCII, even though the documentation claims it accepts UTF-8.
I've tried adding a unicode_csv_reader function as described in the csv examples, but it doesn't help.
---- EDIT -----
I should clarify one thing. I have seen this question, which looks very similar. But adding the unicode_csv_reader function defined there produces a different error instead:
yield [unicode(cell, 'utf-8') for cell in row]
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa3 in position 8: unexpected code byte
So maybe my file isn't UTF8 after all? How can I tell?
| [
"Try using the \"ISO-8859-1\" for your encoding. It seems like you are dealing with extended ASCII, not Unicode.\nEdit:\nHere's some simple code that deals with extended ASCII:\n>>> s = \"La Pe\\xf1a\"\n>>> print s\nLa Pe±a\n>>> print s.decode(\"latin-1\")\nLa Peña\n>>>\n\nEven better, dealing with the exact charac... | [
7,
0
] | [] | [] | [
"csv",
"encoding",
"python"
] | stackoverflow_0003479961_csv_encoding_python.txt |
Q:
Analyse data using time and date objects
I have a rather unique problem I'm trying to solve:
Based on this sample data (actual data is very many records, and at least 4 per card per day):
serial, card, rec_date, rec_time, retrieved_on
2976 00040 2010-07-29 18:57 2010-07-31 13:37:31
2977 00040 2010-07-30 09:58 2010-07-31 13:37:31
2978 00040 2010-07-30 15:33 2010-07-31 13:37:31
2979 00040 2010-07-30 16:13 2010-07-31 13:37:31
2980 00040 2010-07-30 19:41 2010-07-31 13:37:31
The records are from a time-clock system.
What I want to do is take a certain group of entries, filtered by card and rec_date, then determine how long the person has been working during the day and the length of each workspan, how many breaks he/she has taken, and at the end of the week get the total number of hours worked.
From the above list, 2977 is a check in, then 2978 is a check out and so on.
I'm lost at how to do this though, so I thought someone here would have an idea.
I'm using a simple class to store this data after importing else from elsewhere:
class TimeClock(models.Model):
serial = models.CharField(max_length = 16)
card_no = models.CharField(max_length = 10)
rec_date = models.DateField()
rec_time = models.TimeField()
oper_date = models.DateTimeField(default=datetime.today)
A:
Clearly, class TimeClock -- by itself -- is inadequate for what you're doing.
You need to summarize TimeClock to create WorkIntervals, which you can work with. These are pairs of TimeClock rows that show the (theoretical) start and end of a work span.
If someone fails to clock in, you're completely unable to reason out what's going on.
It's not "hard", it's impossible.
Also, if someone works past midnight, you're unable to reason out what's going on.
It's not "hard", it's impossible.
But, we'll pretend no one works past midnight and no one fails to clock in or out (hahaha)
def make_pairs( tc_query_set ):
start = None
for row in tc_query_set:
if start is None:
start= row
continue
elif start.card == row.card and start.rec_date == row.rec_date:
yield start, row
start= None
else:
# May as well raise an exception -- the data cannot the processed
yield start, None
start= row
You use this as follows.
data = TimeClock.objects.order_by('card','rec_date','rec_time').all()
for start, end in make_pairs( data ):
WorkIntervals.objects.create( start.card, start.rec_date, start.rec_time, end.rec_time, ... )
Now you can work with the intervals. If it was possible to create them.
A:
Well, there are a bunch of separate problems here. I assume that you've already got filtered data, so that your log looks like all the events for a unique card on a particular day. Suppose this data is stored as a list of strings in log. Then:
import datetime
def dates( log ):
''' Yields consecutive datetimes in the log. '''
for event in log:
yield datetime.datetime.strptime( event[ 12 : 28 ], "%Y-%m-%d %H:%M" )
def time_clocked_in( log ):
assert not len( log ) % 2
total_time = datetime.timedelta( 0 )
event_dates = dates( log )
try:
while 1:
total_time -= next( event_dates ) - next( event_dates )
except StopIteration:
pass
return total_time
log = [
"2977 00040 2010-07-30 09:58 2010-07-31 13:37:31",
"2978 00040 2010-07-30 15:33 2010-07-31 13:37:31",
"2979 00040 2010-07-30 16:13 2010-07-31 13:37:31",
"2980 00040 2010-07-30 19:41 2010-07-31 13:37:31"
]
print( time_clocked_in( log ) )
>>> 9:03:00
| Analyse data using time and date objects | I have a rather unique problem I'm trying to solve:
Based on this sample data (actual data is very many records, and at least 4 per card per day):
serial, card, rec_date, rec_time, retrieved_on
2976 00040 2010-07-29 18:57 2010-07-31 13:37:31
2977 00040 2010-07-30 09:58 2010-07-31 13:37:31
2978 00040 2010-07-30 15:33 2010-07-31 13:37:31
2979 00040 2010-07-30 16:13 2010-07-31 13:37:31
2980 00040 2010-07-30 19:41 2010-07-31 13:37:31
The records are from a time-clock system.
What I want to do is take a certain group of entries, filtered by card and rec_date, then determine how long the person has been working during the day and the length of each workspan, how many breaks he/she has taken, and at the end of the week get the total number of hours worked.
From the above list, 2977 is a check in, then 2978 is a check out and so on.
I'm lost at how to do this though, so I thought someone here would have an idea.
I'm using a simple class to store this data after importing else from elsewhere:
class TimeClock(models.Model):
serial = models.CharField(max_length = 16)
card_no = models.CharField(max_length = 10)
rec_date = models.DateField()
rec_time = models.TimeField()
oper_date = models.DateTimeField(default=datetime.today)
| [
"Clearly, class TimeClock -- by itself -- is inadequate for what you're doing.\nYou need to summarize TimeClock to create WorkIntervals, which you can work with. These are pairs of TimeClock rows that show the (theoretical) start and end of a work span.\nIf someone fails to clock in, you're completely unable to re... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003479693_django_python.txt |
Q:
Problem with encode decode. Python. Django. BeautifulSoup
In this code:
soup=BeautifulSoup(program.Description.encode('utf-8'))
name=soup.find('div',{'class':'head'})
print name.string.decode('utf-8')
error happening when i'm trying to print or save to database.
dosnt metter what i'm doing:
print name.string.encode('utf-8')
or just
print name.string
Traceback (most recent call last):
File "./manage.py", line 16, in <module>
execute_manager(settings)
File "/usr/local/cluster/dynamic/virtualenv/lib/python2.5/site-packages/django/core/management/__init__.py", line 362, in execute_manager
utility.execute()
File "/usr/local/cluster/dynamic/virtualenv/lib/python2.5/site-packages/django/core/management/__init__.py", line 303, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/cluster/dynamic/virtualenv/lib/python2.5/site-packages/django/core/management/base.py", line 195, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/cluster/dynamic/virtualenv/lib/python2.5/site-packages/django/core/management/base.py", line 222, in execute
output = self.handle(*args, **options)
File "/usr/local/cluster/dynamic/website/video/remmedia/management/commands/remmedia.py", line 50, in handle
self.FirstTimeLoad()
File "/usr/local/cluster/dynamic/website/video/remmedia/management/commands/remmedia.py", line 115, in FirstTimeLoad
print name.string.decode('utf-8')
File "/usr/lib/python2.5/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-5: ordinal not in range(128)
This is repr(name.string)
u'\u0412\u044b\u043f\u0443\u0441\u043a \u043e\u0442 27 \u0434\u0435\u043a\u0430\u0431\u0440\u044f'
A:
I don't know what you are trying to do with name.string.decode('utf-8'). As the BeautifulSoup documentation eloquently points out, "BeautifulSoup gives you Unicode, dammit". So name.string is already decoded - it is in unicode. You can encode it back to utf-8 if you want to, but you can't decode it any further.
A:
You can try:
print name.string.encode('ascii', 'replace')
The output should be accepted whatever the encoding of sys.stdout is (including None).
In fact, the file-like object that you are printing to might not accept UTF-8. Here is an example: if you have the apparently benign program
# -*- coding: utf-8 -*-
print u"hérisson"
then running it in a terminal that can print accented characters works fine:
lebigot@weinberg /tmp % python2.5 test.py
hérisson
but printing to a standard output connected to a Unix pipe does not:
lebigot@weinberg /tmp % python2.5 test.py | cat
Traceback (most recent call last):
File "test.py", line 3, in <module>
print u"hérisson"
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128)
because sys.stdout has encoding None, in this case: Python considers that the program that reads through the pipe should receive ASCII, and the printing fails because ASCII cannot represent the word that we want to print. A solution like the one above solves the problem.
Note: You can check the encoding of your standard output with:
print sys.stdout.encoding
This can help you debug encoding problems.
A:
Edit: name.string comes from BeautifulSoup, so it is presumably already a unicode string.
However, your error message mentions 'ascii':
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-5:
ordinal not in range(128)
According to the PrintFails Python wiki page, if Python does not know or
can not determine what kind of encoding your output device is expecting, it sets
sys.stdout.encoding to None and print attempts to encode its arguments with
the 'ascii' codec.
I believe this is the cause of your problem. You can can confirm this by seeing
if print sys.stdout.encoding prints None.
According to the same page, linked above, you can circumvent the problem by
explicitly telling Python what encoding to use. You do that be wrapping
sys.stdout in an instance of StreamWriter:
For example, you could try adding
import sys
import locale
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
to your script before the print statement. You may have to change
locale.getpreferredencoding() to and explicit encoding (e.g. 'utf-8',
'cp1252', etc.). The right encoding to use depends on your output device.
It should be set to whatever encoding your output device is expecting. If
you are outputing to a terminal, the terminal may have a menu setting to allow
the user to set what type of encoding the terminal should expect.
Original answer: Try:
print name.string
or
print name.string.encode('utf-8')
| Problem with encode decode. Python. Django. BeautifulSoup | In this code:
soup=BeautifulSoup(program.Description.encode('utf-8'))
name=soup.find('div',{'class':'head'})
print name.string.decode('utf-8')
error happening when i'm trying to print or save to database.
dosnt metter what i'm doing:
print name.string.encode('utf-8')
or just
print name.string
Traceback (most recent call last):
File "./manage.py", line 16, in <module>
execute_manager(settings)
File "/usr/local/cluster/dynamic/virtualenv/lib/python2.5/site-packages/django/core/management/__init__.py", line 362, in execute_manager
utility.execute()
File "/usr/local/cluster/dynamic/virtualenv/lib/python2.5/site-packages/django/core/management/__init__.py", line 303, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/cluster/dynamic/virtualenv/lib/python2.5/site-packages/django/core/management/base.py", line 195, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/cluster/dynamic/virtualenv/lib/python2.5/site-packages/django/core/management/base.py", line 222, in execute
output = self.handle(*args, **options)
File "/usr/local/cluster/dynamic/website/video/remmedia/management/commands/remmedia.py", line 50, in handle
self.FirstTimeLoad()
File "/usr/local/cluster/dynamic/website/video/remmedia/management/commands/remmedia.py", line 115, in FirstTimeLoad
print name.string.decode('utf-8')
File "/usr/lib/python2.5/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-5: ordinal not in range(128)
This is repr(name.string)
u'\u0412\u044b\u043f\u0443\u0441\u043a \u043e\u0442 27 \u0434\u0435\u043a\u0430\u0431\u0440\u044f'
| [
"I don't know what you are trying to do with name.string.decode('utf-8'). As the BeautifulSoup documentation eloquently points out, \"BeautifulSoup gives you Unicode, dammit\". So name.string is already decoded - it is in unicode. You can encode it back to utf-8 if you want to, but you can't decode it any further.\... | [
5,
4,
0
] | [
"try\ntext = text.decode(\"utf-8\", \"replace\")\n\n"
] | [
-1
] | [
"beautifulsoup",
"encoding",
"python",
"utf_8"
] | stackoverflow_0003480639_beautifulsoup_encoding_python_utf_8.txt |
Q:
python confusion: dict.pop
I am really confused as to why Python acts in a particular way.
Here is an example: I have a dictionary called "copy". (It is a copy of an HttpRequest.POST in django.)
Here is a debug session (with added line numbers):
1 (Pdb) copy
2 <QueryDict: {u'text': [u'test'], u'otherId': [u'60002'], u'cmd': [u'cA'], u'id':
3 [u'15']}>
4 (Pdb) copy['text']
5 u'test'
6 (Pdb) copy.pop('text')
7 [u'test']
My problem is that in the dictionary it looks like the values are all lists (they come from django that way.) When I access an element as in line 4 I get it as a value rather than a list, but when I access it with pop I get it as a list again.
I am really confused by that. Can anyone help?
A:
Have a look at the docs for QueryDicts. The short answer that it is a subclass of dict that modifies the way you get items, so that copy['text'] will return the last value in the list of values associated with 'text'. Since they haven't overridden pop, it will return the entire list.
You can use .getlist to get the list associated with a particular value:
copy['text']
>>> u'test'
copy.getlist('text')
>>> [u'test']
The reason for this is that some HTML elements will return multiple values for a single key.
| python confusion: dict.pop | I am really confused as to why Python acts in a particular way.
Here is an example: I have a dictionary called "copy". (It is a copy of an HttpRequest.POST in django.)
Here is a debug session (with added line numbers):
1 (Pdb) copy
2 <QueryDict: {u'text': [u'test'], u'otherId': [u'60002'], u'cmd': [u'cA'], u'id':
3 [u'15']}>
4 (Pdb) copy['text']
5 u'test'
6 (Pdb) copy.pop('text')
7 [u'test']
My problem is that in the dictionary it looks like the values are all lists (they come from django that way.) When I access an element as in line 4 I get it as a value rather than a list, but when I access it with pop I get it as a list again.
I am really confused by that. Can anyone help?
| [
"Have a look at the docs for QueryDicts. The short answer that it is a subclass of dict that modifies the way you get items, so that copy['text'] will return the last value in the list of values associated with 'text'. Since they haven't overridden pop, it will return the entire list.\nYou can use .getlist to get t... | [
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003481131_django_python.txt |
Q:
SQLAlchemy, self-referential secondary table association
I'm trying to create a "Product" object in SQLAlchemy and so far I have gotten everything working accept the Product's "accessories". What I have is a Product with a list of field/value pairs (ie. Capacity : 12 L etc.), and integer ID and a catalog number. I would like to be able to associate certain "accessories" with a given product where these accessories are also products. Essentially I just want an association table that has product_id and accessory_id which both reference the ID in the Products table. This is what I have so far:
product_accessories=Table('product_accesssories',Base.metadata,\
Column('product_id',Integer,ForeignKey('product.product_id')),\
Column('accessory_id',Integer,ForeignKey('product.product_id')))
class Product(Base):
__tablename__='product'
id=Column('product_id',Integer,primary_key=True)
catNo=Column('catalog_number',String(20))
fields=relationship('ProductField')
accessories=relationship('Product',secondary=product_accessories)
I get the error "Could not determine join condition between parent/child tables on relationship Product.accessories". I have tried fiddling around a bunch with this and haven't been able to get anywhere. I don't want to lose the unique reference to a product and I feel like there should be an easier way to do this other than wrapping accessories in another class.
Any help would be greatly appreciated!
A:
import sqlalchemy as sa
from sqlalchemy import orm
products_table = sa.Table('products', metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('catalog_number', sa.String(20)),
)
accessories_table = sa.Table('product_accessories', metadata,
sa.Column('product_id', sa.ForeignKey(products_table.c.id), primary_key=True),
sa.Column('accessory_id', sa.ForeignKey(products_table.c.id), primary_key=True),
)
class Product(object):
pass
class Accessory(object):
pass
orm.mapper(Product, products_table, properties=dict(
accessories=orm.relation(Accessory,
primaryjoin=(products_table.c.id == accessories_table.c.product_id),
secondaryjoin=(products_table.c.id == accessories_table.c.accessory_id),
),
))
orm.mapper(Accessory, accessories_table)
| SQLAlchemy, self-referential secondary table association | I'm trying to create a "Product" object in SQLAlchemy and so far I have gotten everything working accept the Product's "accessories". What I have is a Product with a list of field/value pairs (ie. Capacity : 12 L etc.), and integer ID and a catalog number. I would like to be able to associate certain "accessories" with a given product where these accessories are also products. Essentially I just want an association table that has product_id and accessory_id which both reference the ID in the Products table. This is what I have so far:
product_accessories=Table('product_accesssories',Base.metadata,\
Column('product_id',Integer,ForeignKey('product.product_id')),\
Column('accessory_id',Integer,ForeignKey('product.product_id')))
class Product(Base):
__tablename__='product'
id=Column('product_id',Integer,primary_key=True)
catNo=Column('catalog_number',String(20))
fields=relationship('ProductField')
accessories=relationship('Product',secondary=product_accessories)
I get the error "Could not determine join condition between parent/child tables on relationship Product.accessories". I have tried fiddling around a bunch with this and haven't been able to get anywhere. I don't want to lose the unique reference to a product and I feel like there should be an easier way to do this other than wrapping accessories in another class.
Any help would be greatly appreciated!
| [
"import sqlalchemy as sa\nfrom sqlalchemy import orm\n\nproducts_table = sa.Table('products', metadata,\n sa.Column('id', sa.Integer(), primary_key=True),\n sa.Column('catalog_number', sa.String(20)),\n)\n\naccessories_table = sa.Table('product_accessories', metadata,\n sa.Column('product_id', sa.ForeignKe... | [
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003480602_python_sqlalchemy.txt |
Q:
Want all links that have 2 attributes, how do you pass 2 attributes?
I know how to pass 1 attribute, but how do I pass 2?
e.g.
somerows = soup.findAll('a', target="blank")
what if I want all links that have target="blank" and class="blah" ?
A:
You can use a dictionary to avoid having problems with some attribute names such as 'class':
soup.findAll('a', {
"target" : "blank",
"class" : "blah",
"href" : re.compile(...)
})
This is mentioned in the documentation.
A:
soup.findAll('a', 'blah', target='blank', href=re.compile(...))
Quoth the BS docs:
The attrs argument would be a pretty
obscure feature were it not for one
thing: CSS. It's very useful to search
for a tag that has a certain CSS
class, but the name of the CSS
attribute, class, is also a Python
reserved word.
You could search by CSS class with
soup.find("tagName", { "class" :
"cssClass" }), but that's a lot of
code for such a common operation.
Instead, you can pass a string for
attrs instead of a dictionary. The
string will be used to restrict the
CSS class.
A:
If you want a more complicated search, you can also do:
key = lambda tag: ...
# or even
def key( tag )
return len( tag.attrs ) == 2 # for example
soup.findAll( key )
See the docs.
| Want all links that have 2 attributes, how do you pass 2 attributes? | I know how to pass 1 attribute, but how do I pass 2?
e.g.
somerows = soup.findAll('a', target="blank")
what if I want all links that have target="blank" and class="blah" ?
| [
"You can use a dictionary to avoid having problems with some attribute names such as 'class':\nsoup.findAll('a', {\n \"target\" : \"blank\",\n \"class\" : \"blah\",\n \"href\" : re.compile(...)\n})\n\nThis is mentioned in the documentation.\n",
"soup.findAll('a', 'blah', target='blank', href=re.compile(.... | [
2,
1,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003481360_beautifulsoup_python.txt |
Q:
in a loop, only add to a dictionary or list or tuple if doesn't contains the key
I am looping in python and want to add a key to a dictionary only if it isn't already in the collection.
How can I do this?
mydic = {}
for x in range(100):
??
A:
For a dict, it's easy and fast:
for x in range(100):
if x not in mydic:
mydic[x] = x # or whatever value you want
that is, just check with not in instead of in.
This is great for a dict. For a list, it's going to be extremely slow (quadratic); for speed, you need to add an auxiliary set (hopefully all items in the list are hashable) before the loop, and check and update it in the loop. I.e.:
auxset = set(mylist)
for x in range(100):
if x not in auxset:
auxset.add(x)
mylist.append(x) # or whatever
For a tuple, it's impossible to add anything to it, or in any other way modify it, of course: tuples are immutable! Surely you know that?! So, why ask?
| in a loop, only add to a dictionary or list or tuple if doesn't contains the key | I am looping in python and want to add a key to a dictionary only if it isn't already in the collection.
How can I do this?
mydic = {}
for x in range(100):
??
| [
"For a dict, it's easy and fast:\nfor x in range(100):\n if x not in mydic:\n mydic[x] = x # or whatever value you want\n\nthat is, just check with not in instead of in.\nThis is great for a dict. For a list, it's going to be extremely slow (quadratic); for speed, you need to add an auxiliary set (hopefully a... | [
5
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003481414_dictionary_python.txt |
Q:
regex that matches a string that contains some text
I need a regex that matches
re.compile('userpage')
href="www.example.com?u=userpage&as=233&p=1"
href="www.example.com?u=userpage&as=233&p=2"
I want to get all urls that have u=userpage and p=1
How can I modify the regex above to find both u=userpage and p=1?
A:
if you want to use, in my opinion, something more proper approach, than regexp:
from urlparse import *
urlparsed = urlparse('www.example.com?u=userpage&as=233&p=1')
# -> ParseResult(scheme='', netloc='', path='www.example.com', params='', query='u=userpage&as=233&p=1', fragment='')
qdict = dict(parse_qsl(urlparsed.query))
# -> {'as': '233', 'p': '1', 'u': 'userpage'}
qdict.get('p') == '1' and qdict.get('u') == 'userpage'
# -> True
A:
import lxml.html, urlparse
d = lxml.html.parse(...)
for link in d.xpath('//a/@href'):
url = urlparse.urlparse(link)
if not url.query:
continue
params = urlparse.parse_qs(url.query)
if 'userpage' in params.get('u', []) and '1' in params.get('p', []):
print link
A:
Regex is not a good choice for this because 1) the params could appear in either order, and 2) you need to do extra checks for query separators so that you don't match potential oddities like "flu=userpage", "sp=1", "u=userpage%20haha", or "s=123". (Note: I missed two of those cases in my first pass! So did others.) Also: 3) you already have a good URL parsing library in Python which does the work for you.
With regex you'd need something clumsy like:
q = re.compile(r'([?&]u=userpage&(.*&)?p=1(&|$))|([?&]p=1&(.*&)?u=userpage(&|$))')
return q.search(href) is not None
With urlparse you can do this. urlparse gives you a little more than you want but you can use a helper function to keep the result simple:
def has_qparam(qs, key, value):
return value in qs.get(key, [])
qs = urlparse.parse_qs(urlparse.urlparse(href).query)
return has_qparam(qs, 'u', 'userpage') and has_qparam(qs, 'p', '1')
A:
/((u=userpage).*?(p=1))|((p=1).*?(u=userpage))/
This will get all strings that contain the two bits you're looking for.
A:
To make sure you don't accidentally match parts like bu=userpage, u=userpagezap, p=111 or zap=1, you need abundant use of the \b "word-boundary" RE pattern element. I.e.:
re.compile(r'\bp=1\b.*\bu=userpage\b|\bu=userpage\b.*\bp=1\b')
The word-boundary elements in the RE's pattern prevent the above-mentioned, presumably-undesirable "accidental" matches. Of course, if in your application they're not "undesirable", i.e., if you positively want to match p=123 and the like, you can easily remove some or all of the word-boundary elements above!-)
| regex that matches a string that contains some text | I need a regex that matches
re.compile('userpage')
href="www.example.com?u=userpage&as=233&p=1"
href="www.example.com?u=userpage&as=233&p=2"
I want to get all urls that have u=userpage and p=1
How can I modify the regex above to find both u=userpage and p=1?
| [
"if you want to use, in my opinion, something more proper approach, than regexp:\nfrom urlparse import *\nurlparsed = urlparse('www.example.com?u=userpage&as=233&p=1')\n# -> ParseResult(scheme='', netloc='', path='www.example.com', params='', query='u=userpage&as=233&p=1', fragment='')\nqdict = dict(parse_qsl(urlpa... | [
5,
4,
2,
0,
0
] | [
"It is possible to do this with string hacking, but you shouldn't. It's already in the standard library:\n>>> import urllib.parse\n>>> urllib.parse.parse_qs(\"u=userpage&as=233&p=1\")\n{'u': ['userpage'], 'as': ['233'], 'p': ['1']}\n\nand hence\nimport urllib.parse\ndef filtered_urls( urls ):\n for url in urls:\... | [
-1
] | [
"python",
"regex"
] | stackoverflow_0003481378_python_regex.txt |
Q:
Python ctypes not loading dynamic library on Mac OS X
I have a C++ library repeater.so that I can load from Python in Linux the following way:
import numpy as np
repeater = np.ctypeslib.load_library('librepeater.so', '.')
However, when I compile the same library on Mac OS X (Snow Leopard, 32 bit) and get repeater.dylib, and then run the following in Python:
import numpy as np
repeater = np.ctypeslib.load_library('librepeater.dylib', '.')
I get the following error:
OSError: dlopen(/mydir/librepeater.dylib, 6): no suitable image found. Did find:
/mydir/librepeater.dylib: mach-o, but wrong architecture
Do I have to do something different to load a dynamic library in Python on Mac OS X?
A:
It's not just a question of what architectures are available in the dylib; it's also a matter of which architecture the Python interpreter is running in. If you are using the Apple-supplied Python 2.6.1 in OS X 10.6, by default it runs in 64-bit mode if possible. Since you say your library was compiled as 32-bit, you'll need to force Python to run in 32-bit mode. For the Apple-supplied Python, one way to do that is to set a special environment variable:
$ python -c "import sys; print sys.maxint"
9223372036854775807
$ export VERSIONER_PYTHON_PREFER_32_BIT=yes
$ python -c "import sys; print sys.maxint"
2147483647
See Apple's man 1 python for more information.
A:
Nope. As the error message says, there's an architecture mismatch between your python and librepeater.dylib file. Use file to check what the architecture of librepeater.dylib is; your python is going to be built using one of the ones not listed.
| Python ctypes not loading dynamic library on Mac OS X | I have a C++ library repeater.so that I can load from Python in Linux the following way:
import numpy as np
repeater = np.ctypeslib.load_library('librepeater.so', '.')
However, when I compile the same library on Mac OS X (Snow Leopard, 32 bit) and get repeater.dylib, and then run the following in Python:
import numpy as np
repeater = np.ctypeslib.load_library('librepeater.dylib', '.')
I get the following error:
OSError: dlopen(/mydir/librepeater.dylib, 6): no suitable image found. Did find:
/mydir/librepeater.dylib: mach-o, but wrong architecture
Do I have to do something different to load a dynamic library in Python on Mac OS X?
| [
"It's not just a question of what architectures are available in the dylib; it's also a matter of which architecture the Python interpreter is running in. If you are using the Apple-supplied Python 2.6.1 in OS X 10.6, by default it runs in 64-bit mode if possible. Since you say your library was compiled as 32-bit... | [
11,
4
] | [] | [] | [
"ctypes",
"dynamic_linking",
"linux",
"macos",
"python"
] | stackoverflow_0003481508_ctypes_dynamic_linking_linux_macos_python.txt |
Q:
How should I configure Amazon EC2 to perform parallelizable data-intensive calculations?
I have a computational intensive project that is highly parallelizable: basically, I have a function that I need to run on each observation in a large table (Postgresql). The function itself is a stored python procedure.
Amazon EC2 seems like an excellent fit for the project.
My question is this: Should I make a custom image (AMI) that already contains the database? This would seem to have the advantage of minimizing data transfers and making parallelization simple: each image could get some assigned block of indices to compute, e.g., image 1 gets 1:100, image 2 101:200 etc. Splitting up the data and the instances (which most how-to guides suggest) doesn't seem to make sense for my application, but I'm very new to this so I'm not confident my intuition is right.
A:
you will definitely want to keep the data and the server instance separate in order for changes in your data to be persisted when you are done with the instance. your best bet will be to start with a basic image that has the OS & database platform you want to use, customize it to suit your needs, and then mount one or more EBS volumes containing your data. You may also want to create your own server instance once you are finished with your customization, unless what you are doing is fairly straightforward.
some helpful links:
http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-10-01/creating-an-image.html
http://developer.amazonwebservices.com/connect/entry.jspa?categoryID=100&externalID=1663
(you said postgres but this mysql tutorial covers the same basic concepts you'll want to keep in mind)
A:
If you've already got the function implemented in Python, the simplest route might be to look at PiCloud, which just gives you a really easy interface for running a Python function on EC2, handling pretty much everything else for you. Whether it's economically sensible will depend on how much data has to get sent per function call vs how long computations take to run.
| How should I configure Amazon EC2 to perform parallelizable data-intensive calculations? | I have a computational intensive project that is highly parallelizable: basically, I have a function that I need to run on each observation in a large table (Postgresql). The function itself is a stored python procedure.
Amazon EC2 seems like an excellent fit for the project.
My question is this: Should I make a custom image (AMI) that already contains the database? This would seem to have the advantage of minimizing data transfers and making parallelization simple: each image could get some assigned block of indices to compute, e.g., image 1 gets 1:100, image 2 101:200 etc. Splitting up the data and the instances (which most how-to guides suggest) doesn't seem to make sense for my application, but I'm very new to this so I'm not confident my intuition is right.
| [
"you will definitely want to keep the data and the server instance separate in order for changes in your data to be persisted when you are done with the instance. your best bet will be to start with a basic image that has the OS & database platform you want to use, customize it to suit your needs, and then mount o... | [
1,
1
] | [] | [] | [
"amazon_ec2",
"postgresql",
"python"
] | stackoverflow_0003481285_amazon_ec2_postgresql_python.txt |
Q:
Python MySQL and Django problem
I am having problems getting python/django to connect to a MySQL database. The error message is basically "Error Loading MySQLDb module: No module named MySQLDb".
This is a fresh install right off python.org, so I assumed that it would have the MySQLDb module included, but it does not seem to. I also can't seem to find the module or how to install it, except in some sleazy looking parts of the net.
Is there a central point for getting this module? Why isn't it in the standard install? Can someone point me to a tutorial or some such to get this module installed?
Newbie in python, MySQL and Django.
Thanks for help.
A:
I believe http://pypi.python.org/pypi/MySQL-python/ is the Python module you need. In general, when looking for Python modules, http://pypi.python.org/ is where you should start (people will refer to it as either PyPI or "the cheese shop." If setuptools is installed (it may be already) then you can run easy_install MySQL-python.
As far as MySQL is concerned, you'll need to install that separately from a likely-looking package on http://dev.mysql.com/downloads/mysql/.
A:
this is how i handled the issue on Fedora13:
you can get the module here: http://sourceforge.net/projects/mysql-python/
download to a convenient directory
read the README file
build the module, according to the instructions in the README, keeping in mind to use the version of python you are planning to use as an interpreter (2.6 for me). if there are more than one version of python, simply using 'python' will probably alias you into a particular version, which might not be the one you want.
after the build is complete, the .egg file will have been created and landed in a 'site-packages' directory associated with the version of python which was used for the build.
then, ensure that the .egg file created (you can see the install path in the output from the install) is placed on your PYTHONPATH
that did it for me, anyhoo...
good luck!
JR
| Python MySQL and Django problem | I am having problems getting python/django to connect to a MySQL database. The error message is basically "Error Loading MySQLDb module: No module named MySQLDb".
This is a fresh install right off python.org, so I assumed that it would have the MySQLDb module included, but it does not seem to. I also can't seem to find the module or how to install it, except in some sleazy looking parts of the net.
Is there a central point for getting this module? Why isn't it in the standard install? Can someone point me to a tutorial or some such to get this module installed?
Newbie in python, MySQL and Django.
Thanks for help.
| [
"I believe http://pypi.python.org/pypi/MySQL-python/ is the Python module you need. In general, when looking for Python modules, http://pypi.python.org/ is where you should start (people will refer to it as either PyPI or \"the cheese shop.\" If setuptools is installed (it may be already) then you can run easy_inst... | [
2,
0
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0003432600_django_mysql_python.txt |
Q:
"x not in" vs. "not x in"
I've noticed that both of these work the same:
if x not in list and if not x in list.
Is there some sort of difference between the two in certain cases? Is there a reason for having both, or is it just because it's more natural for some people to write one or the other?
Which one am I more likely to see in other people's code?
A:
The two forms make identical bytecode, as you can clearly verify:
>>> import dis
>>> dis.dis(compile('if x not in d: pass', '', 'exec'))
1 0 LOAD_NAME 0 (x)
3 LOAD_NAME 1 (d)
6 COMPARE_OP 7 (not in)
9 JUMP_IF_FALSE 4 (to 16)
12 POP_TOP
13 JUMP_FORWARD 1 (to 17)
>> 16 POP_TOP
>> 17 LOAD_CONST 0 (None)
20 RETURN_VALUE
>>> dis.dis(compile('if not x in d: pass', '', 'exec'))
1 0 LOAD_NAME 0 (x)
3 LOAD_NAME 1 (d)
6 COMPARE_OP 7 (not in)
9 JUMP_IF_FALSE 4 (to 16)
12 POP_TOP
13 JUMP_FORWARD 1 (to 17)
>> 16 POP_TOP
>> 17 LOAD_CONST 0 (None)
20 RETURN_VALUE
so obviously they're semantically identical.
As a matter of style, PEP 8 does not mention the issue.
Personally, I strongly prefer the if x not in y form -- that makes it immediately clear that not in is a single operator, and "reads like English". if not x in y may mislead some readers into thinking it means if (not x) in y, reads a bit less like English, and has absolutely no compensating advantages.
A:
>>> dis.dis(lambda: a not in b)
1 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (b)
6 COMPARE_OP 7 (not in)
9 RETURN_VALUE
>>> dis.dis(lambda: not a in b)
1 0 LOAD_GLOBAL 0 (a)
3 LOAD_GLOBAL 1 (b)
6 COMPARE_OP 7 (not in)
9 RETURN_VALUE
when you do "not a in b" it will need be converted for (not in)
so, the right way is "a not in b".
A:
not x in L isn't explicitly disallowed because that would be silly. x not in L is explicitly allowed (though it compiles to the same bytecode) because it's more readable.
x not in L is what everyone uses, though.
A:
When you write a not in b it is using the not in operator, whereas not a in b uses the in operator and then negates the result. But the not in operator is defined to return the same as not a in b so they do exactly the same thing. From the documentation:
The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s.
Similarly there is a is not b versus not a is b.
The extra syntax was added because it makes it easier for a human to read it naturally.
A:
It just personal preference. You could also compare if x != 3 and if not x == 3. There's no difference between the two expressions you've shown.
| "x not in" vs. "not x in" | I've noticed that both of these work the same:
if x not in list and if not x in list.
Is there some sort of difference between the two in certain cases? Is there a reason for having both, or is it just because it's more natural for some people to write one or the other?
Which one am I more likely to see in other people's code?
| [
"The two forms make identical bytecode, as you can clearly verify:\n>>> import dis\n>>> dis.dis(compile('if x not in d: pass', '', 'exec'))\n 1 0 LOAD_NAME 0 (x)\n 3 LOAD_NAME 1 (d)\n 6 COMPARE_OP 7 (not in)\n 9 JUMP_IF_FA... | [
92,
7,
3,
3,
0
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0003481554_operators_python.txt |
Q:
Python using doctest on the mainline
Hello i was wondering if it is possible and if so how? to do doctests or something similar from the mainline, instead of testing a function as is described in the doctest docs
i.e.
"""
>>>
Hello World
"""
if __name__ == "__main__":
print "Hello"
import doctest
doctest.testmod()
This is part of being able to test students scripts against a docstring, i found this snipet of code that allows me to input both as strongs
import doctest
from doctest import DocTestRunner, DocTestParser
enter code here
def run_doctest(code, test):
import doctest
from doctest import DocTestRunner, DocTestParser
code = code + '\n__dtest=__parser.get_doctest(__test, globals(), "Crunchy Doctest", "crunchy", 0)\n__runner.run(__dtest)\n'
runner = DocTestRunner()
parser = DocTestParser()
exec code in {'__runner':runner, '__parser':parser, '__test':test}
that does more or less but it seems hardly ideal, an suggestions on either point
A:
doctest is not limited to testing functions. For example, if dt.py is:
'''
>>> foo
23
'''
foo = 23
if __name__ == '__main__':
import doctest
doctest.testmod()
then, e.g.:
$ py26 dt.py -v
Trying:
foo
Expecting:
23
ok
1 items passed all tests:
1 tests in __main__
1 tests in 1 items.
1 passed and 0 failed.
Test passed.
(works just as well without the -v, but then it wouldn't have much to show: just silence;-). Is this what you're looking for?
| Python using doctest on the mainline | Hello i was wondering if it is possible and if so how? to do doctests or something similar from the mainline, instead of testing a function as is described in the doctest docs
i.e.
"""
>>>
Hello World
"""
if __name__ == "__main__":
print "Hello"
import doctest
doctest.testmod()
This is part of being able to test students scripts against a docstring, i found this snipet of code that allows me to input both as strongs
import doctest
from doctest import DocTestRunner, DocTestParser
enter code here
def run_doctest(code, test):
import doctest
from doctest import DocTestRunner, DocTestParser
code = code + '\n__dtest=__parser.get_doctest(__test, globals(), "Crunchy Doctest", "crunchy", 0)\n__runner.run(__dtest)\n'
runner = DocTestRunner()
parser = DocTestParser()
exec code in {'__runner':runner, '__parser':parser, '__test':test}
that does more or less but it seems hardly ideal, an suggestions on either point
| [
"doctest is not limited to testing functions. For example, if dt.py is:\n'''\n >>> foo\n 23\n'''\n\nfoo = 23\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n\nthen, e.g.:\n$ py26 dt.py -v\nTrying:\n foo\nExpecting:\n 23\nok\n1 items passed all tests:\n 1 tests in __main__\n1 tes... | [
2
] | [] | [] | [
"doctest",
"python",
"string"
] | stackoverflow_0003481561_doctest_python_string.txt |
Q:
Why is this variable being changed?
tokens_raw = {"foo": "bar"}
tokens_raw_old = { }
while not tokens_raw == tokens_raw_old:
tokens_raw_old = tokens_raw
# while loop that modifies tokens_raw goes here;
# tokens_raw_old is never referenced
print tokens_raw_old == tokens_raw
This outputs True after the first time for some reason. tokens_raw_old has the same data as tokens_raw, even after tokens_raw alone was modified. Did I make a dumb mistake somewhere, or does the problem lie within the second while loop (which, again, never once references tokens_raw_old)? If there are no obvious mistakes, I'll post more code.
A:
tokens_raw_old = tokens_raw means: make a new reference called token_raw_old to the same object to which name tokens_raw refers at this time. It's the same object, not a copy of the object! So, changes to this one and only object made through one of the references obviously also affect the very same object when examined through the other reference.
If you want a copy, ask for a copy! For example, since tokens_raw is a dict with immutable values (and keys, but that's frequent in dicts):
tokens_raw_old = tokens_raw.copy()
will be sufficient. Identically (just a style issue), so will
tokens_raw_old = dict(tokens_raw)
(make a copy by "calling the type as a copy constructor", a concept that appeals to C++ programmers -- of which I'm one, so I really like this form;-).
If you need to cover for a general case (tokens_raw being of many possible different types, or values within it being perhaps modified):
import copy
tokens_raw_old = copy.deepcopy(tokens_raw)
This can be quite slow, but, "when you need it, you need it" -- it makes a deep copy of the object, that is, it doesn't just copy the container but also all contained objects (recursively, if a container contains other containers -- say that three times fast...;-).
Not every object can be copied (deeply or shallowly) -- for example, an open file object cannot be copied (you need other approaches if you ever have such weird, advanced needs). But, for a dict with strings as keys and values, the simple approaches I mentioned at the start of this answer will suffice, and be quite speedy too;-).
| Why is this variable being changed? | tokens_raw = {"foo": "bar"}
tokens_raw_old = { }
while not tokens_raw == tokens_raw_old:
tokens_raw_old = tokens_raw
# while loop that modifies tokens_raw goes here;
# tokens_raw_old is never referenced
print tokens_raw_old == tokens_raw
This outputs True after the first time for some reason. tokens_raw_old has the same data as tokens_raw, even after tokens_raw alone was modified. Did I make a dumb mistake somewhere, or does the problem lie within the second while loop (which, again, never once references tokens_raw_old)? If there are no obvious mistakes, I'll post more code.
| [
"tokens_raw_old = tokens_raw means: make a new reference called token_raw_old to the same object to which name tokens_raw refers at this time. It's the same object, not a copy of the object! So, changes to this one and only object made through one of the references obviously also affect the very same object when ... | [
7
] | [] | [] | [
"equality",
"python",
"while_loop"
] | stackoverflow_0003481863_equality_python_while_loop.txt |
Q:
How to open a file with the standard application?
My application prints a PDF to a temporary file. How can I open that file with the default application in Python?
I need a solution for
Windows
Linux (Ubuntu with Xfce if there's nothing more general.)
Related
Open document with default application in Python
A:
os.startfile is only available for windows for now, but xdg-open will be available on any unix client running X.
if sys.platform == 'linux2':
subprocess.call(["xdg-open", file])
else:
os.startfile(file)
A:
on windows it works with os.system('start <myFile>'). On Mac (I know you didn't ask...) it's os.system('open <myFile>')
A:
Open file using an application that your browser thinks is an appropriate one:
import webbrowser
webbrowser.open_new_tab(filename)
A:
if linux:
os.system('xdg-open "$file"') #works for urls too
else:
os.system('start "$file"') #a total guess
A:
A small correction is necessary for NicDumZ's solution to work exactly as given. The problem is with the use of 'is' operator. A working solution is:
if sys.platform == 'linux2':
subprocess.call(["xdg-open", file])
else:
os.startfile(file)
A good discussion of this topic is at Is there a difference between `==` and `is` in Python?.
A:
Ask your favorite Application Framework for how to do this in Linux.
This will work on Windos and Linux as long as you use GTK:
import gtk
gtk.show_uri(gtk.gdk.screen_get_default(), URI, 0)
where URI is the local URL to the file
| How to open a file with the standard application? | My application prints a PDF to a temporary file. How can I open that file with the default application in Python?
I need a solution for
Windows
Linux (Ubuntu with Xfce if there's nothing more general.)
Related
Open document with default application in Python
| [
"os.startfile is only available for windows for now, but xdg-open will be available on any unix client running X.\nif sys.platform == 'linux2':\n subprocess.call([\"xdg-open\", file])\nelse:\n os.startfile(file)\n\n",
"on windows it works with os.system('start <myFile>'). On Mac (I know you didn't ask...) i... | [
36,
10,
8,
4,
4,
0
] | [] | [] | [
"linux",
"python",
"windows"
] | stackoverflow_0001679798_linux_python_windows.txt |
Q:
__decorated__ for python decorators
As of 2.4 (2.6 for classes), python allows you to decorate a function with another function:
def d(func): return func
@d
def test(first): pass
It's a convenient syntactic sugar. You can do all sorts of neat stuff with decorators without making a mess. However, if you want to find out the original function that got decorated you have to jump through hoops (like Cls.method.__func__.__closure__[0].cell_contents or worse).
I found myself wishing for a better way and found that there had been some discussion on python-dev about adding a variable called __decorated__ to the [new] function returned by the decorator. However, it appears that didn't go anywhere.
Being an adventuresome person, and having had pretty heavy python experience for about 4 years, I thought I would look into implementing __decorated__ in the python compiler source, just to see how it goes.
To be honest I have never delved into the C underneath the hood, so my first hours have been just trying to make sense of how the underlying C code works. So firstly, what would be the best resources to get my head around what I would have to change/add for __decorator__?
Secondly, if a decorator returns a new function then __decorated__ would just return the original, decorated function. However, if the decorator returns the original function, what should happen? Here are three options I could think of (the third is my favorite):
Don't add __decorator__.
Add __decorator__ but set it to None.
Add __decorator__ and set it to the original function anyway.
So if it were to happen, what do you think would be the best option?
UPDATE:
Someone else brought to my attention a scenario that I had missed. What happens when the decorator returns neither the original function nor a function that wraps the original? At that point nothing is holding a reference to the original function and it will get garbage collected. (Thanks Oddthinking!)
So in that case, I think that I would still go with the third option. The object returned by the decorator would gain a __decorated__ name that references the original function. This would mean that it would not be garbage-collected.
It seems weird to me that the function from a class definition would utterly disappear because you decorated it. In my mind that is even more reason to have a __decorated__ attribute applied for every decorator. However, it's more likely that my intuition is faulty and that the current behavior is what most people would expect. Any thoughts?
p.s. this is an extension of an earlier, more general question I had. I also went for more info on the first part with a separate post.
A:
Well, independent of any discussion over whether this is a good idea, I'd go for option #3 because it's the most consistent: it always shows that the function has been decorated by the presence of the attribute, and accessing the value of the attribute always returns a function, so you don't have to test it against None.
You should also consider this, though: what would you propose to do about manual decoration? e.g.
def test(first): pass
test = d(test)
Regarding the first part of the question, I haven't looked at the Python interpreter source code very much so I wouldn't be able to point you to anything particularly useful.
A:
i feel free to use some single underscored "private" attribute like _mydecor
possible multi-decorator solution:
def decorate(decoration):
def do_decor(func):
if hasattr(func, '_mydecor'):
func._mydecor.add(decoration)
else:
func._mydecor = set([decoration])
return func
return do_decor
def isDecorated(func, decoration):
return (decoration in getattr(func, '_mydecor', set()))
@decorate('red')
@decorate('green')
def orangefunc(): pass
print isDecorated(orangefunc, 'green') # -> True
print isDecorated(orangefunc, 'blue') # -> False
| __decorated__ for python decorators | As of 2.4 (2.6 for classes), python allows you to decorate a function with another function:
def d(func): return func
@d
def test(first): pass
It's a convenient syntactic sugar. You can do all sorts of neat stuff with decorators without making a mess. However, if you want to find out the original function that got decorated you have to jump through hoops (like Cls.method.__func__.__closure__[0].cell_contents or worse).
I found myself wishing for a better way and found that there had been some discussion on python-dev about adding a variable called __decorated__ to the [new] function returned by the decorator. However, it appears that didn't go anywhere.
Being an adventuresome person, and having had pretty heavy python experience for about 4 years, I thought I would look into implementing __decorated__ in the python compiler source, just to see how it goes.
To be honest I have never delved into the C underneath the hood, so my first hours have been just trying to make sense of how the underlying C code works. So firstly, what would be the best resources to get my head around what I would have to change/add for __decorator__?
Secondly, if a decorator returns a new function then __decorated__ would just return the original, decorated function. However, if the decorator returns the original function, what should happen? Here are three options I could think of (the third is my favorite):
Don't add __decorator__.
Add __decorator__ but set it to None.
Add __decorator__ and set it to the original function anyway.
So if it were to happen, what do you think would be the best option?
UPDATE:
Someone else brought to my attention a scenario that I had missed. What happens when the decorator returns neither the original function nor a function that wraps the original? At that point nothing is holding a reference to the original function and it will get garbage collected. (Thanks Oddthinking!)
So in that case, I think that I would still go with the third option. The object returned by the decorator would gain a __decorated__ name that references the original function. This would mean that it would not be garbage-collected.
It seems weird to me that the function from a class definition would utterly disappear because you decorated it. In my mind that is even more reason to have a __decorated__ attribute applied for every decorator. However, it's more likely that my intuition is faulty and that the current behavior is what most people would expect. Any thoughts?
p.s. this is an extension of an earlier, more general question I had. I also went for more info on the first part with a separate post.
| [
"Well, independent of any discussion over whether this is a good idea, I'd go for option #3 because it's the most consistent: it always shows that the function has been decorated by the presence of the attribute, and accessing the value of the attribute always returns a function, so you don't have to test it agains... | [
2,
1
] | [] | [] | [
"c",
"compiler_construction",
"decorator",
"parsing",
"python"
] | stackoverflow_0003481872_c_compiler_construction_decorator_parsing_python.txt |
Q:
pure python socket module
The socket module in python wraps the _socket module which is the C implementation stuff. As well, socket.socket will take a _sock parameter that must implement the _socket interface. In some regards _sock must be an actual instance of the underlying socket type from _socket since the C code does type checking (unlike pure python).
Given that you can pass in a socket-like object for _sock, it seems like you could write a socket emulator that you could pass in to socket.socket. It would need to emulate the underlying socket behavior but in memory and not over a real network or anything. It should not otherwise be distinguishable from _socket.
What would it take to build out this sort of emulation?
I know, I know, this is not terribly practical. In fact, I learned the hard way that using regular sockets was easier and fake sockets were unnecessary. I had thought that I would have better control of a test environment with fake sockets. Regardless of the time I "wasted", I found that I learned a bunch about sockets and about python in the process.
I was guessing any solution would have to be a stack of interacting objects like this:
something_that_uses_sockets (like XMLRPCTransport for ServerProxy)
|
V
socket.socket
|
V
FakeSocket
|
V
FakeNetwork
|
V
FakeSocket ("remote")
|
V
socket.socket
|
V
something_else_that_uses_sockets (like SimpleXMLRPCServer)
It seems like this is basically what is going on for real sockets, except for a real network instead of a fake one (plus OS-level sockets), and _socket instead of FakeSocket.
Anyway, just for fun, any ideas on how to approach this?
Incidently, with a FakeSocket you could do some socket-like stuff in Google Apps...
A:
It's already been done. Twisted uses this extensively for unit tests of its protocol implementations. A good starting place would be looking at some of Twisted's unit tests.
In essence, you'd just call makeConnection on your protocol with a transport that isn't connected to a real socket. Super easy!
| pure python socket module | The socket module in python wraps the _socket module which is the C implementation stuff. As well, socket.socket will take a _sock parameter that must implement the _socket interface. In some regards _sock must be an actual instance of the underlying socket type from _socket since the C code does type checking (unlike pure python).
Given that you can pass in a socket-like object for _sock, it seems like you could write a socket emulator that you could pass in to socket.socket. It would need to emulate the underlying socket behavior but in memory and not over a real network or anything. It should not otherwise be distinguishable from _socket.
What would it take to build out this sort of emulation?
I know, I know, this is not terribly practical. In fact, I learned the hard way that using regular sockets was easier and fake sockets were unnecessary. I had thought that I would have better control of a test environment with fake sockets. Regardless of the time I "wasted", I found that I learned a bunch about sockets and about python in the process.
I was guessing any solution would have to be a stack of interacting objects like this:
something_that_uses_sockets (like XMLRPCTransport for ServerProxy)
|
V
socket.socket
|
V
FakeSocket
|
V
FakeNetwork
|
V
FakeSocket ("remote")
|
V
socket.socket
|
V
something_else_that_uses_sockets (like SimpleXMLRPCServer)
It seems like this is basically what is going on for real sockets, except for a real network instead of a fake one (plus OS-level sockets), and _socket instead of FakeSocket.
Anyway, just for fun, any ideas on how to approach this?
Incidently, with a FakeSocket you could do some socket-like stuff in Google Apps...
| [
"It's already been done. Twisted uses this extensively for unit tests of its protocol implementations. A good starting place would be looking at some of Twisted's unit tests.\nIn essence, you'd just call makeConnection on your protocol with a transport that isn't connected to a real socket. Super easy!\n"
] | [
3
] | [] | [] | [
"emulation",
"python",
"sockets"
] | stackoverflow_0003481779_emulation_python_sockets.txt |
Q:
I'm looking for a Python multiplayer game server project
I'm looking for a python multiplayer game server project. I'm just trying to learn more.
A:
Well I started on something simple here. It's written with pygame and Python's socket module. You could fork/learn from that.
Presently multiple players can login, move around, and do basic chat communication. There's also a goblin that chases the nearest player.
| I'm looking for a Python multiplayer game server project | I'm looking for a python multiplayer game server project. I'm just trying to learn more.
| [
"Well I started on something simple here. It's written with pygame and Python's socket module. You could fork/learn from that.\nPresently multiple players can login, move around, and do basic chat communication. There's also a goblin that chases the nearest player.\n"
] | [
5
] | [] | [] | [
"mmo",
"multiplayer",
"python"
] | stackoverflow_0003481883_mmo_multiplayer_python.txt |
Q:
How to extract a given frame from a .gif animation in Python
I'm trying to figure out how to extract a given frame from an animated-gif, possibly in PIL, in Python.
I'm not able to easily dig this up, and I'm guessing it would take some knowledge of the gif format, something that is not readily understandable to me.
Is there any straightforward way to accomplish this? Do I need to do some custom parsing?
A:
Reading Sequences
The GIF loader supports the seek and
tell methods. You can seek to the next
frame (im.seek(im.tell()+1), or rewind
the file by seeking to the first
frame. Random access is not supported.
http://effbot.org/imagingbook/format-gif.htm
http://effbot.org/imagingbook/image.htm
| How to extract a given frame from a .gif animation in Python | I'm trying to figure out how to extract a given frame from an animated-gif, possibly in PIL, in Python.
I'm not able to easily dig this up, and I'm guessing it would take some knowledge of the gif format, something that is not readily understandable to me.
Is there any straightforward way to accomplish this? Do I need to do some custom parsing?
| [
"\nReading Sequences\nThe GIF loader supports the seek and\n tell methods. You can seek to the next\n frame (im.seek(im.tell()+1), or rewind\n the file by seeking to the first\n frame. Random access is not supported.\n\nhttp://effbot.org/imagingbook/format-gif.htm\nhttp://effbot.org/imagingbook/image.htm \n"
] | [
5
] | [] | [] | [
"animated_gif",
"python",
"python_imaging_library"
] | stackoverflow_0003482193_animated_gif_python_python_imaging_library.txt |
Q:
Using xterm to open a new console: How to while the current console is printing, to print on the new console also
I'm using python right now. I have a thread that represents my entire program. I want to open another console window using os.system(xterm&) as a thread which works. The only thing is, is it possible to print to the new window while the other thread is printing to the older window?
import sys
import os
def my_fork():
child_pid = os.fork()
if child_pid == 0:
function=open('SMITH747.txt','r')
f=function.readlines()
fd = open("output", "w")
# Open xterm window with logs from that file
p = subprocess.Popen(["xterm", "-e", "tail", "-f", "output"])
# Do logging
while(True):
for i in range(1):
fd.write("Hello, world!")
time.sleep(2)
if f==[]:
pass
else:
bud=False
fd.flush()
else:
function=open('SMITH747.txt','w')
var=input('Enter ')
if var=='q':
function.write('yo')
if __name__ == "__main__":
my_fork()
this is what I have right now: It works except I can't get it to read my file and terminate if f is not []. I would appreciate it so much if someone can help me debug this part. Then it will be perfect!
A:
You could probably create a named pipe, have your new thread write to that, then spawn a new terminal that runs tail -f on the pipe.
A:
Use subprocess.Popen() for creation of the children process. In that case you can specify PIPE and write to stdin of the children.
import subprocess
p = subprocess.Popen(["xterm"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = p.communicate("inputmessage")[0]
Update:
Directly xterm does not received input, so here is not so direct way.
import subprocess
# Open file for output
fd = open("output", "w")
# Open xterm window with logs from that file
p = subprocess.Popen(["xterm", "-e", "tail", "-f", "output"])
# Do logging
fd.write("Hello, world!")
fd.flush()
Now you can redirect stdout descriptor to the fd, so the "print" will write output to the file. But it will be for all threads...
A:
For a unix solution:
The command tee is meant to allow output to a log file while still outputing to the console. You second term can just follow that file with tail -f on the output file.
A:
the reason why I want to open a new console is so that I can var=input('Enter q here: ') >in new window and wait for user to press enter thus terminating the old thread...
Simplest way i see, is helper script for asking user in separate terminal. And it is not stdin/stdout redirection hacks :)
main.py:
import os
os.mkfifo("/tmp/1234");
os.system("xterm -e python input.py &")
f = open("/tmp/1234")
print(f.read())
input.py:
var=input('Enter q here: ')
fifo = open('/tmp/1234','w')
fifo.write(str(var))
fifo.flush()
A:
import os, subprocess, time, threading
# Reads commands from fifo in separate thread.
# if kill command is received, then down continue flag.
class Killer(threading.Thread):
def __init__ (self):
threading.Thread.__init__(self)
self.continueFlag = True
def run(self):
fd=open('ipc','r')
command = fd.read()
if command == "kill\n":
self.continueFlag = False
def my_fork():
# create fifo for reliable inter-process communications
# TODO: check existence of fifo
os.mkfifo('ipc')
# Be careful with threads and fork
child_pid = os.fork()
if child_pid == 0:
fd = open("output", "w")
subprocess.Popen(["xterm", "-e", "tail", "-f", "output"])
# Create and start killer, be careful with threads and fork
killer = Killer()
killer.start()
# Perform work while continue flag is up
while(killer.continueFlag):
fd.write("Hello, world!\n")
fd.flush()
time.sleep(2)
# need to kill subprocess with opened xterm
else:
# File must be fifo, otherwise race condition is possible.
fd=open('ipc','w')
var=input('Enter ')
if var=='q':
fd.write('kill\n')
if __name__ == "__main__":
my_fork()
P.S. discussion is far away from topic, probably you should change it.
| Using xterm to open a new console: How to while the current console is printing, to print on the new console also | I'm using python right now. I have a thread that represents my entire program. I want to open another console window using os.system(xterm&) as a thread which works. The only thing is, is it possible to print to the new window while the other thread is printing to the older window?
import sys
import os
def my_fork():
child_pid = os.fork()
if child_pid == 0:
function=open('SMITH747.txt','r')
f=function.readlines()
fd = open("output", "w")
# Open xterm window with logs from that file
p = subprocess.Popen(["xterm", "-e", "tail", "-f", "output"])
# Do logging
while(True):
for i in range(1):
fd.write("Hello, world!")
time.sleep(2)
if f==[]:
pass
else:
bud=False
fd.flush()
else:
function=open('SMITH747.txt','w')
var=input('Enter ')
if var=='q':
function.write('yo')
if __name__ == "__main__":
my_fork()
this is what I have right now: It works except I can't get it to read my file and terminate if f is not []. I would appreciate it so much if someone can help me debug this part. Then it will be perfect!
| [
"You could probably create a named pipe, have your new thread write to that, then spawn a new terminal that runs tail -f on the pipe.\n",
"Use subprocess.Popen() for creation of the children process. In that case you can specify PIPE and write to stdin of the children.\nimport subprocess\np = subprocess.Popen([\"... | [
0,
0,
0,
0,
0
] | [] | [] | [
"console",
"linux",
"multithreading",
"python"
] | stackoverflow_0003481838_console_linux_multithreading_python.txt |
Q:
Shed some light on working with pipes and subprocesses in Python?
I'm wrestling with the concepts behind subprocesses and pipes, and working with them in a Python context. If anybody could shed some light on these questions it would really help me out.
Say I have a pipeline set up as follows
createText.py | processText.py | cat
processText.py is receiving data through stdin, but how is this implemented? How does it know that no more data will be coming and that it should exit? My guess is that it could look for an EOF and terminate based on that, but what if createText.py never sends one? Would that be considered an error on createText.py's part?
Say parent.py starts a child subprocess (child.py) and calls wait() to wait for the child to complete. If parent is capturing child's stdout and stderr as pipes, is it still safe to read from them after child has terminated? Or are the pipes (and data in them) destroyed when one end terminates?
The general problem that I want to solve is to write a python script that calls rsync several times with the Popen class. I want my program to wait until rsync has completed, then I want to check the return status to see if it exited correctly. If it didn't, I want to read the child's stderr to see what the error was. Here is what I have so far
# makes the rsync call. Will block until the child
# process is finished. Returns the exit code for rsync
def performRsync(src, dest):
print "Pushing " + src + " to " + dest
child = Popen(['rsync', '-av', src, dest], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
child.wait()
## check for success or failure
## 0 is a successful exit code here
if not child.returncode:
return True
else:#ballz
stout, sterr = child.communicate()
print "ERR pushing " + src + ". " + sterr
return False
Update: I also came across this problem. Consider these two simple files:
# createText.py
for x in range(1000):
print "creating line " + str(x)
time.sleep(1)
# processText.py
while True:
line = sys.stdin.readline()
if not line:
break;
print "I modified " + line
Why does processText.py in this case not start printing as it gets data from stdin? Does a pipe collect some amount of buffered data before it passes it along?
A:
This assumes a UNIXish/POSIXish environment.
EOF in a pipeline is signaled by no more data to read, that is, read() returns a length of 0. This normally occurs when the left-hand process exits and closes its stdout. Since you can't read from a pipe whose other end is closed the read in processText indicates EOF.
If createText were to not exit thus closing its output it would be a non-ending program which in a pipeline is a Bad Thing. Even if not in pipeline, a program that never ends usually incorrect (odd cases like yes(1) excepted).
You can read from a pipe as long as you don't get EOF or an IOError(errno.EPIPE) indication which would also indicate there is nothing left to read.
I've not tested your code, does it do something unexpected?
| Shed some light on working with pipes and subprocesses in Python? | I'm wrestling with the concepts behind subprocesses and pipes, and working with them in a Python context. If anybody could shed some light on these questions it would really help me out.
Say I have a pipeline set up as follows
createText.py | processText.py | cat
processText.py is receiving data through stdin, but how is this implemented? How does it know that no more data will be coming and that it should exit? My guess is that it could look for an EOF and terminate based on that, but what if createText.py never sends one? Would that be considered an error on createText.py's part?
Say parent.py starts a child subprocess (child.py) and calls wait() to wait for the child to complete. If parent is capturing child's stdout and stderr as pipes, is it still safe to read from them after child has terminated? Or are the pipes (and data in them) destroyed when one end terminates?
The general problem that I want to solve is to write a python script that calls rsync several times with the Popen class. I want my program to wait until rsync has completed, then I want to check the return status to see if it exited correctly. If it didn't, I want to read the child's stderr to see what the error was. Here is what I have so far
# makes the rsync call. Will block until the child
# process is finished. Returns the exit code for rsync
def performRsync(src, dest):
print "Pushing " + src + " to " + dest
child = Popen(['rsync', '-av', src, dest], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
child.wait()
## check for success or failure
## 0 is a successful exit code here
if not child.returncode:
return True
else:#ballz
stout, sterr = child.communicate()
print "ERR pushing " + src + ". " + sterr
return False
Update: I also came across this problem. Consider these two simple files:
# createText.py
for x in range(1000):
print "creating line " + str(x)
time.sleep(1)
# processText.py
while True:
line = sys.stdin.readline()
if not line:
break;
print "I modified " + line
Why does processText.py in this case not start printing as it gets data from stdin? Does a pipe collect some amount of buffered data before it passes it along?
| [
"This assumes a UNIXish/POSIXish environment.\nEOF in a pipeline is signaled by no more data to read, that is, read() returns a length of 0. This normally occurs when the left-hand process exits and closes its stdout. Since you can't read from a pipe whose other end is closed the read in processText indicates EOF.\... | [
1
] | [] | [] | [
"pipe",
"process",
"python",
"shell"
] | stackoverflow_0003482266_pipe_process_python_shell.txt |
Q:
Komodo Edit auto-complete won't find a Python module
I am using Komodo edit on a Python file on Windows.
When I type import s it successfully lists all the importable files starting with s, including one of my modules in one of my directories.
When I type import t it lists all the importable files starting with t, EXCLUDING one of my modules in the same directory.
Even though Komodo can't find it, the Python interpreter finds and runs both files fine. It is purely a problem with Komodo's Code Intelligence.
The name of the missing module is 9 lower-case letters (nothing fancy). It doesn't clash with any other modules. It is in the same directory as the module that can be found.
Any suggestions about why one module is found and another isn't?
A:
Problem solved itself when I closed Komodo, saving the project, and reopened it.
Sounds like Komodo's internal representation was out-of-date or corrupted.
I'll leave the question here for the next person who stumbles over it.
| Komodo Edit auto-complete won't find a Python module | I am using Komodo edit on a Python file on Windows.
When I type import s it successfully lists all the importable files starting with s, including one of my modules in one of my directories.
When I type import t it lists all the importable files starting with t, EXCLUDING one of my modules in the same directory.
Even though Komodo can't find it, the Python interpreter finds and runs both files fine. It is purely a problem with Komodo's Code Intelligence.
The name of the missing module is 9 lower-case letters (nothing fancy). It doesn't clash with any other modules. It is in the same directory as the module that can be found.
Any suggestions about why one module is found and another isn't?
| [
"Problem solved itself when I closed Komodo, saving the project, and reopened it.\nSounds like Komodo's internal representation was out-of-date or corrupted.\nI'll leave the question here for the next person who stumbles over it.\n"
] | [
2
] | [] | [] | [
"komodo",
"komodoedit",
"python"
] | stackoverflow_0003481949_komodo_komodoedit_python.txt |
Q:
querying a array in django
idarr = [1,2,3,4,5]
for i in range(len(idarr)):
upload.objects.filter(idarr[i])
Cant we pass the idarr at one shot to the query
A:
I am assuming that you are trying to filter all instances of Upload whose id is in the list idarr. If that is the case then you can go about it like this:
Upload.objects.filter(id__in = idarr)
Read the documentation for more details.
A:
So much wrong in so few lines...
In Python, never loop through range(len(whatever)). Just do for i in whatever.
Assuming upload is a Django model, you can't just pass a value to filter - you need to say what you're filtering against. Presumably it's the primary key, so you want .filter(pk=i).
If you want to filter against any of the values in a list, use __in: .filter(pk__in=idarr).
| querying a array in django | idarr = [1,2,3,4,5]
for i in range(len(idarr)):
upload.objects.filter(idarr[i])
Cant we pass the idarr at one shot to the query
| [
"I am assuming that you are trying to filter all instances of Upload whose id is in the list idarr. If that is the case then you can go about it like this:\nUpload.objects.filter(id__in = idarr)\n\nRead the documentation for more details.\n",
"So much wrong in so few lines...\n\nIn Python, never loop through rang... | [
7,
7
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0003482637_django_django_models_django_views_python.txt |
Q:
Passing an array in django urls
Can we pass an array to a django url
<script>
function save()
{
window.location = "/display/xlsdisplay/" + objarr ;
}
var objarr = new Array();
</script>
Urls.py
(r'^xlsdisplay/(?P<qid>\d+)$', 'xlsdisplay'),
There is an error saying
http://192.168.1.11/display/xlsdisplay/334,335,336,337,338,339,340,341,342,343
A:
The regular expression used in your URL will only match a sequence of digits. The comma will require a different expression.
I don't know your specific need but you ought to look at naming URLs rather than hard cording them.
| Passing an array in django urls | Can we pass an array to a django url
<script>
function save()
{
window.location = "/display/xlsdisplay/" + objarr ;
}
var objarr = new Array();
</script>
Urls.py
(r'^xlsdisplay/(?P<qid>\d+)$', 'xlsdisplay'),
There is an error saying
http://192.168.1.11/display/xlsdisplay/334,335,336,337,338,339,340,341,342,343
| [
"\nThe regular expression used in your URL will only match a sequence of digits. The comma will require a different expression. \nI don't know your specific need but you ought to look at naming URLs rather than hard cording them. \n\n"
] | [
2
] | [] | [] | [
"django",
"django_urls",
"django_views",
"python"
] | stackoverflow_0003482481_django_django_urls_django_views_python.txt |
Q:
Is Python's seek() on OS X broken?
I'm trying to implement a simple method to read new lines from a log file each time the method is called.
I've looked at the various suggestions both on stackoverflow (e.g. here) and elsewhere for simulating "tail" functionality; most involve using readline() to read in new lines as they're appended to the file. It should be simple enough, but can't get it to work properly on OS X 10.6.4 with the included Python 2.6.1.
To get to the heart of the problem, I tried the following:
Open two terminal windows.
In one, create a text file "test.log" with three lines:
one
two
three
In the other, start python and execute the following code:
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.stat('test.log')
posix.stat_result(st_mode=33188, st_ino=23465217, st_dev=234881025L, st_nlink=1, st_uid=666, st_gid=20, st_size=14, st_atime=1281782739, st_mtime=1281782738, st_ctime=1281782738)
>>> log = open('test.log')
>>> log.tell()
0
>>> log.seek(0,2)
>>> log.tell()
14
>>>
So we see with the tell() that seek(0,2) brought us to the end of the file as reported by os.stat(), byte 14.
In the first shell, add another two lines to "test.log" so that it looks like this:
one
two
three
four
five
Go back to the second shell, and execute the following code:
>>> os.stat('test.log')
posix.stat_result(st_mode=33188, st_ino=23465260, st_dev=234881025L, st_nlink=1, st_uid=666, st_gid=20, st_size=24, st_atime=1281783089, st_mtime=1281783088, st_ctime=1281783088)
>>> log.seek(0,2)
>>> log.tell()
14
>>>
Here we see from os.stat() that the file's size is now 24 bytes, but seeking to the end of the file somehow still points to byte 14?? I've tried the same on Ubuntu with Python 2.5 and it works as I expect. I tried with 2.5 on my Mac, but got the same results as with 2.6.
I must be missing something fundamental here. Any ideas?
A:
How are you adding two more lines to the file?
Most text editors will go through operations a lot like this:
fd = open(filename, read)
file_data = read(fd)
close(fd)
/* you edit your file, and save it */
unlink(filename)
fd = open(filename, write, create)
write(fd, file_data)
The file is different. (Check it with ls -li; the inode number will change for almost every text editor.)
If you append to the log file using your shell's >> redirection, it'll work exactly as it should:
$ echo one >> test.log
$ echo two >> test.log
$ echo three >> test.log
$ ls -li test.log
671147 -rw-r--r-- 1 sarnold sarnold 14 2010-08-14 04:15 test.log
$ echo four >> test.log
$ ls -li test.log
671147 -rw-r--r-- 1 sarnold sarnold 19 2010-08-14 04:15 test.log
>>> log=open('test.log')
>>> log.tell()
0
>>> log.seek(0,2)
>>> log.tell()
19
$ echo five >> test.log
$ echo six >> test.log
>>> log.seek(0,2)
>>> log.tell()
28
Note that the tail(1) command has an -F command line option to handle the case where the file is changed, but a file by the same name exists. (Great for watching log files that might be periodically rotated.)
A:
Short answer: no, your assumptions are.
Your text editor is creating a new file with the same name, not modifying the old file in place. You can see in your stat result that the st_ino is different. If you were to do os.fstat(log.fileno()), you'd get the old size and old st_ino.
If you want to check for this in your implementation of tail, periodically compare the st_ino of the stat and fstat results. If they differ, there's a new file with the same name.
| Is Python's seek() on OS X broken? | I'm trying to implement a simple method to read new lines from a log file each time the method is called.
I've looked at the various suggestions both on stackoverflow (e.g. here) and elsewhere for simulating "tail" functionality; most involve using readline() to read in new lines as they're appended to the file. It should be simple enough, but can't get it to work properly on OS X 10.6.4 with the included Python 2.6.1.
To get to the heart of the problem, I tried the following:
Open two terminal windows.
In one, create a text file "test.log" with three lines:
one
two
three
In the other, start python and execute the following code:
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.stat('test.log')
posix.stat_result(st_mode=33188, st_ino=23465217, st_dev=234881025L, st_nlink=1, st_uid=666, st_gid=20, st_size=14, st_atime=1281782739, st_mtime=1281782738, st_ctime=1281782738)
>>> log = open('test.log')
>>> log.tell()
0
>>> log.seek(0,2)
>>> log.tell()
14
>>>
So we see with the tell() that seek(0,2) brought us to the end of the file as reported by os.stat(), byte 14.
In the first shell, add another two lines to "test.log" so that it looks like this:
one
two
three
four
five
Go back to the second shell, and execute the following code:
>>> os.stat('test.log')
posix.stat_result(st_mode=33188, st_ino=23465260, st_dev=234881025L, st_nlink=1, st_uid=666, st_gid=20, st_size=24, st_atime=1281783089, st_mtime=1281783088, st_ctime=1281783088)
>>> log.seek(0,2)
>>> log.tell()
14
>>>
Here we see from os.stat() that the file's size is now 24 bytes, but seeking to the end of the file somehow still points to byte 14?? I've tried the same on Ubuntu with Python 2.5 and it works as I expect. I tried with 2.5 on my Mac, but got the same results as with 2.6.
I must be missing something fundamental here. Any ideas?
| [
"How are you adding two more lines to the file?\nMost text editors will go through operations a lot like this:\nfd = open(filename, read)\nfile_data = read(fd)\nclose(fd)\n/* you edit your file, and save it */\nunlink(filename)\nfd = open(filename, write, create)\nwrite(fd, file_data)\n\nThe file is different. (Che... | [
3,
2
] | [] | [] | [
"macos",
"python",
"seek"
] | stackoverflow_0003483007_macos_python_seek.txt |
Q:
How to control/call another python script within one python script? (Communicate between scripts)
I'm working on one GUI program, and was gonna add a long running task into one event, but I found this would make the whole program freeze a lot, so considering other people's advice I would make the GUI only responsible for starting, stopping and monitoring and make the long running task run as a separate script. The only way I know to run another script in one script is by import, is there any other methods to communicate with another script, I mean such as reading another's stdout and terminating it at any time you want?
A:
I suggest you look at the threading module. By subclassing the Thread class you can create new threads for time intensive jobs.
Then for communication between the the threads you can use either pubsub or pydispatcher, I haven't tried the latter so I can't comment on it but I would recommend pubsub for its ease of use and the fact that its apart of wxpython is a bonus.
Here is a wxpython wiki page on running long tasks, skip to the end if you want the simplest example usage of threading.
Heres a simple (runnable) example of how you could use pubsub to send messages from your workerThread to your GUI.
import time
import wx
from threading import Thread
from wx.lib.pubsub import Publisher
class WorkerThread(Thread):
def __init__(self):
Thread.__init__(self)
#A flag that can be set
#to tell the thread to end
self.stop_flag = False
#This calls the run() to start the new thread
self.start()
def run(self):
""" Over-rides the super-classes run()"""
#Put everything in here that
#you want to run in your new thread
#e.g...
for x in range(20):
if self.stop_flag:
break
time.sleep(1)
#Broadcast a message to who ever's listening
Publisher.sendMessage("your_topic_name", x)
Publisher.sendMessage("your_topic_name", "finished")
def stop(self):
"""
Call this method to tell the thread to stop
"""
self.stop_flag = True
class GUI(wx.Frame):
def __init__(self, parent, id=-1,title=""):
wx.Frame.__init__(self, parent, id, title, size=(140,180))
self.SetMinSize((140,180))
panel = wx.Panel(id=wx.ID_ANY, name=u'mainPanel', parent=self)
#Subscribe to messages from the workerThread
Publisher().subscribe(self.your_message_handler, "your_topic_name")
#A button to start the workerThread
self.startButton = wx.Button(panel, wx.ID_ANY, 'Start thread')
self.Bind(wx.EVT_BUTTON, self.onStart, self.startButton)
#A button to stop the workerThread
self.stopButton = wx.Button(panel, wx.ID_ANY, 'Stop thread')
self.Bind(wx.EVT_BUTTON, self.onStop, self.stopButton)
#A text control to display messages from the worker thread
self.threadMessage = wx.TextCtrl(panel, wx.ID_ANY, '', size=(75, 20))
#Do the layout
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.startButton, 0, wx.ALL, 10)
sizer.Add(self.stopButton, 0, wx.ALL, 10)
sizer.Add(self.threadMessage, 0, wx.ALL, 10)
panel.SetSizerAndFit(sizer)
def onStart(self, event):
#Start the worker thread
self.worker = WorkerThread()
#Disable any widgets which could affect your thread
self.startButton.Disable()
def onStop(self, message):
self.worker.stop()
def your_message_handler(self, message):
message_data = message.data
if message_data == 'finished':
self.startButton.Enable()
self.threadMessage.SetLabel(str(message_data))
else:
self.threadMessage.SetLabel(str(message_data))
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = GUI(None, wx.ID_ANY, 'Threading Example')
frame.Show()
app.MainLoop()
A:
If communicating by stdin/stdout is what you need, you should use the subprocess module.
A:
There is much better way to do that, than reading stdout: http://docs.python.org/library/multiprocessing.html
| How to control/call another python script within one python script? (Communicate between scripts) | I'm working on one GUI program, and was gonna add a long running task into one event, but I found this would make the whole program freeze a lot, so considering other people's advice I would make the GUI only responsible for starting, stopping and monitoring and make the long running task run as a separate script. The only way I know to run another script in one script is by import, is there any other methods to communicate with another script, I mean such as reading another's stdout and terminating it at any time you want?
| [
"I suggest you look at the threading module. By subclassing the Thread class you can create new threads for time intensive jobs. \nThen for communication between the the threads you can use either pubsub or pydispatcher, I haven't tried the latter so I can't comment on it but I would recommend pubsub for its ease... | [
5,
1,
1
] | [] | [] | [
"event_handling",
"python",
"wxpython"
] | stackoverflow_0003482112_event_handling_python_wxpython.txt |
Q:
How to generate hebrew strings in python 3?
I'm trying to create hebrew strings but get syntax errors. It works in the IDLE shell but not in Pydev.
Here's what I've tried so far:
s = 'מחרוזת בעברית' #works in the shell only
s = u'מחרוזת בעברית' #doesn't work at all
s = unicode("מחרוזת בעברית", "UTF-8") #also doesn't work at all
I get a syntax error: Non-UTF-8 code starting with '\xee'.
What does it mean and what shall I do to create hebrew strings?
A:
Does your source file start with a # -*- coding: utf-8 -*- line? Is your file actually encoded as utf-8 (and not some other encoding)?
It's supposed to work (the first line, other lines are not valid Python 3).
| How to generate hebrew strings in python 3? | I'm trying to create hebrew strings but get syntax errors. It works in the IDLE shell but not in Pydev.
Here's what I've tried so far:
s = 'מחרוזת בעברית' #works in the shell only
s = u'מחרוזת בעברית' #doesn't work at all
s = unicode("מחרוזת בעברית", "UTF-8") #also doesn't work at all
I get a syntax error: Non-UTF-8 code starting with '\xee'.
What does it mean and what shall I do to create hebrew strings?
| [
"Does your source file start with a # -*- coding: utf-8 -*- line? Is your file actually encoded as utf-8 (and not some other encoding)?\nIt's supposed to work (the first line, other lines are not valid Python 3).\n"
] | [
6
] | [] | [] | [
"hebrew",
"pydev",
"python",
"string",
"unicode"
] | stackoverflow_0003483167_hebrew_pydev_python_string_unicode.txt |
Q:
How should I read the input data?
For example, I have the following input data:
(( 12 3 ) 42 )
I want to treat each integer value of the input data. This is an example of the general input data presentation.
Just for additional information:
Such presentation is corresponding to the binary tree with marked leaves:
/\
/\ 42
12 3
A:
I recommend pyparsing for this parsing task -- here, for example, is a pyparsing-based parsers for S-expressions... probably much richer and more powerful than what you need, but with a really limited understanding of Python and pyparsing you can simplify it down as much as you require (if at all -- it's quite able to perform your task already, as a subset of the broader set it covers;-).
A:
I wrote this script. It may be helpful
import tokenize,StringIO
def parseNode(tokens):
l = []
while True:
c = next(tokens)
if c[1] == '(':
l.append(parseNode(tokens))
elif c[1] == ')':
return l
elif c[0] == tokenize.NUMBER:
l.append(int(c[1]))
def parseTree(string):
tokens = tokenize.generate_tokens(StringIO.StringIO(string).readline)
while next(tokens)[1] != '(' : pass
return parseNode(tokens)
print parseTree('(( 12 3 ) 42 15 (16 (11 2) 2) )')
A:
here is good list of resources you could use. I would suggest PLY
A:
something like the following should work:
import re
newinput = re.sub(r"(\d) ", r"\1, ", input)
newinput = re.sub(r"\) ", r"), ", newinput)
eval(newinput)
| How should I read the input data? | For example, I have the following input data:
(( 12 3 ) 42 )
I want to treat each integer value of the input data. This is an example of the general input data presentation.
Just for additional information:
Such presentation is corresponding to the binary tree with marked leaves:
/\
/\ 42
12 3
| [
"I recommend pyparsing for this parsing task -- here, for example, is a pyparsing-based parsers for S-expressions... probably much richer and more powerful than what you need, but with a really limited understanding of Python and pyparsing you can simplify it down as much as you require (if at all -- it's quite abl... | [
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003481971_python.txt |
Q:
Two classes: one for the django model and one for representing the data outside of django
Is there a reasonable pattern for handling an object that exists as a Django model within the context of a particular Django application and as a non-Django class outside of that particular application?
For example, let's say that I have a Post model within Django application Blog. I want to be able to interact with a class representing this post outside of the Blog Django application and possibly within a different Django application.
In the past I have just created two completely separate classes with slightly different interfaces. The Django model contains to and from methods to create from the non-Django version or to export to the non-Django version. But this feels all wrong to me.
EDIT: I realize that my language and the use of the word 'access' is confusing. I'm not asking about how to talk to a Django application, I'm asking about how to have a Django model class and a non-Django class represent the same data with the same interface where I can export a Django model object to the non-Django class so I can use it in another application. Errr, that probably wasn't clear either was it?
A:
You can use Django code outside of the normal server environment (as the test cases do). If you need to write Python scripts that play with your Django models, you can just access/modify your models as usual, using the ORM, there's just a short magic incantation you have to use first:
from django.core.management import setup_environ
from mysite import settings
from myapp.models import MyModel
setup_environ(settings)
# Now do whatever you want with the ORM
mystuff = MyModel.objects.all()
I tend to avoid this legwork using management commands.
If you need to have multiple Django applications accessing this data, that's fine - just make sure they're in the same Django project.
If you really need to have them in separate projects, then I'd probably write an API that interacts with Django views to add, fetch, update or delete my models - probably using a REST API. You can get some ideas for doing that here.
A:
If I understand you correctly, you have something that you want to represent in multiple programs as an object. To make matters more interesting, if your object is being used in the context of a Django program, you'd like your object to be a Django model, so that you can persist your object in a database, and do all of the other neat things that Django can do with a model. Presumably, although you don't state it explicitly, instead of just enumerating properties of the object, you have behavior that you'd like to have your object implement regardless of the environment (Django or otherwise).
If you were implementing this in Java or C#, I'd suggest something like this:
interface IFoo { ... }
class FooHelper { ... }
class app1.Foo extends Model implements IFoo { ... }
class app2.Foo implements IFoo { ... }
For each method available in IFoo, both app1.Foo and app2.Foo would need to implement the method by delegating to a matching method in FooHelper. As an example, a bar method would look like this:
interface IFoo {
int bar();
}
class FooHelper {
int bar( object foo ) { ... }
}
package app1;
class Foo extends Model implements IFoo {
...
int bar() {
return FooHelper.bar( this );
}
}
package app2;
class Foo implements IFoo {
...
int bar() {
return FooHelper.bar( this );
}
}
Of course FooHelper is going to have to be smart enough to Do The Right Thing depending upon which type of Foo it gets passed.
Solving this in Python should be easier, since Python is a dynamic language.
# Create a class decorator
def decorate_foo( fooclass ):
def bar( self ):
return 0
fooclass.bar = bar
# Create a class to decorate
class Foo: pass
# Decorate the class
decorate_foo( Foo )
# Use the decorated class
f = Foo()
f.bar()
Just put all of your functionality into the decorate_foo function, and then let it add that functionality to the class before you need to invoke one of the added methods.
A:
I'm having trouble imagining what you mean by 'accessing the object outside of the Django application'. How will the external application get the data that defines the model instance? How are the two applications related - are they simply different areas of the same code, or are they completely separate processes communicating via something like HTTP?
If they're separate, you may want to create a RESTful API to your models, which the external app can then access over HTTP. The django-piston project makes this simple. Is that the sort of thing you're after?
| Two classes: one for the django model and one for representing the data outside of django | Is there a reasonable pattern for handling an object that exists as a Django model within the context of a particular Django application and as a non-Django class outside of that particular application?
For example, let's say that I have a Post model within Django application Blog. I want to be able to interact with a class representing this post outside of the Blog Django application and possibly within a different Django application.
In the past I have just created two completely separate classes with slightly different interfaces. The Django model contains to and from methods to create from the non-Django version or to export to the non-Django version. But this feels all wrong to me.
EDIT: I realize that my language and the use of the word 'access' is confusing. I'm not asking about how to talk to a Django application, I'm asking about how to have a Django model class and a non-Django class represent the same data with the same interface where I can export a Django model object to the non-Django class so I can use it in another application. Errr, that probably wasn't clear either was it?
| [
"You can use Django code outside of the normal server environment (as the test cases do). If you need to write Python scripts that play with your Django models, you can just access/modify your models as usual, using the ORM, there's just a short magic incantation you have to use first:\nfrom django.core.management ... | [
2,
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003479982_django_django_models_python.txt |
Q:
Help With Printing a single item from list inside list in python
I first create my grid:
grid = []
for x in range(1,collength + 1):
for y in range(1,collength + 1):
grid.append([x,y,'e'])
Then I make que for my grid and I want to manipulate the que based on the 0, 1, and 2 position of the lists inside the lists:
floodfillque = []
grid = floodfillque
for each in floodfillque:
floodfilllist = []
currentfloodfill = []
print '::'
print each[1]
But when I try to print each[1] I get the whole list, not just the nth element of the list inside the list
What am I doing wrong?
A:
As you have written it, your code iterates over an empty list. I think you mean:
for each in grid:
or perhaps:
floodfillque = grid
This code works fine:
collength = 3
grid = []
for x in range(1,collength + 1):
for y in range(1,collength + 1):
grid.append([x,y,'e'])
for each in grid:
floodfilllist = []
currentfloodfill = []
print '::'
print each[1]
Result:
::
1
::
2
::
3
::
1
::
2
::
3
::
1
::
2
::
3
| Help With Printing a single item from list inside list in python | I first create my grid:
grid = []
for x in range(1,collength + 1):
for y in range(1,collength + 1):
grid.append([x,y,'e'])
Then I make que for my grid and I want to manipulate the que based on the 0, 1, and 2 position of the lists inside the lists:
floodfillque = []
grid = floodfillque
for each in floodfillque:
floodfilllist = []
currentfloodfill = []
print '::'
print each[1]
But when I try to print each[1] I get the whole list, not just the nth element of the list inside the list
What am I doing wrong?
| [
"As you have written it, your code iterates over an empty list. I think you mean:\nfor each in grid:\n\nor perhaps:\nfloodfillque = grid\n\nThis code works fine:\ncollength = 3\n\ngrid = []\nfor x in range(1,collength + 1):\n for y in range(1,collength + 1):\n grid.append([x,y,'e'])\n\nfor each in grid:\n... | [
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003483807_list_python.txt |
Q:
When to inline definitions of metaclass in Python?
Today I have come across a surprising definition of a metaclass in Python here, with the metaclass definition effectively inlined. The relevant part is
class Plugin(object):
class __metaclass__(type):
def __init__(cls, name, bases, dict):
type.__init__(name, bases, dict)
registry.append((name, cls))
When does it make sense to use such an inline definition?
Further Arguments:
An argument one way would be that the created metaclass is not reusable elsewhere using this technique. A counter argument is that a common pattern in using metaclasses is defining a metaclass and using it in one class and then inhertiting from that. For example, in a conservative metaclass the definition
class DeclarativeMeta(type):
def __new__(meta, class_name, bases, new_attrs):
cls = type.__new__(meta, class_name, bases, new_attrs)
cls.__classinit__.im_func(cls, new_attrs)
return cls
class Declarative(object):
__metaclass__ = DeclarativeMeta
def __classinit__(cls, new_attrs): pass
could have been written as
class Declarative(object): #code not tested!
class __metaclass__(type):
def __new__(meta, class_name, bases, new_attrs):
cls = type.__new__(meta, class_name, bases, new_attrs)
cls.__classinit__.im_func(cls, new_attrs)
return cls
def __classinit__(cls, new_attrs): pass
Any other considerations?
A:
Like every other form of nested class definition, a nested metaclass may be more "compact and convenient" (as long as you're OK with not reusing that metaclass except by inheritance) for many kinds of "production use", but can be somewhat inconvenient for debugging and introspection.
Basically, instead of giving the metaclass a proper, top-level name, you're going to end up with all custom metaclasses defined in a module being undistiguishable from each other based on their __module__ and __name__ attributes (which is what Python uses to form their repr if needed). Consider:
>>> class Mcl(type): pass
...
>>> class A: __metaclass__ = Mcl
...
>>> class B:
... class __metaclass__(type): pass
...
>>> type(A)
<class '__main__.Mcl'>
>>> type(B)
<class '__main__.__metaclass__'>
IOW, if you want to examine "which type is class A" (a metaclass is the class's type, remember), you get a clear and useful answer -- it's Mcl in the main module. However, if you want to examine "which type is class B", the answer is not all that useful: it says it's __metaclass__ in the main module, but that's not even true:
>>> import __main__
>>> __main__.__metaclass__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__metaclass__'
>>>
...there is no such thing, actually; that repr is misleading and not very helpful;-).
A class's repr is essentially '%s.%s' % (c.__module__, c.__name__) -- a simple, useful, and consistent rule -- but in many cases such as, the class statement not being unique at module scope, or not being at module scope at all (but rather within a function or class body), or not even existing (classes can of course be built without a class statement, by explicitly calling their metaclass), this can be somewhat misleading (and the best solution is to avoid, in as far as possible, those peculiar cases, except when substantial advantage can be obtained by using them). For example, consider:
>>> class A(object):
... def foo(self): print('first')
...
>>> x = A()
>>> class A(object):
... def foo(self): print('second')
...
>>> y = A()
>>> x.foo()
first
>>> y.foo()
second
>>> x.__class__
<class '__main__.A'>
>>> y.__class__
<class '__main__.A'>
>>> x.__class__ is y.__class__
False
with two class statement at the same scope, the second one rebinds the name (here, A), but existing instances refer to the first binding of the name by object, not by name -- so both class objects remain, one accessible only through the type (or __class__ attribute) of its instances (if any -- if none, that first object disappears) -- the two classes have the same name and module (and therefore the same representation), but they're distinct objects. Classes nested within class or function bodies, or created by directly calling the metaclass (including type), may cause similar confusion if debugging or introspection is ever called for.
So, nesting the metaclass is OK if you'll never need to debug or otherwise introspect that code, and can be lived with if whoever is so doing understand this quirks (though it will never be as convenient as using a nice, real name, of course -- just like debugging a function coded with lambda cannot possibly ever be so convenient as debugging one coded with def). By analogy with lambda vs def you can reasonably claim that anonymous, "nested" definition is OK for metaclasses which are so utterly simple, such no-brainers, that no debugging or introspection will ever conceivably be required.
In Python 3, the "nested definition" just doesn't work -- there, a metaclass must be passed as a keyword argument to the class, as in class A(metaclass=Mcl):, so defining __metaclass__ in the body has no effect. I believe this also suggests that a nested metaclass definition in Python 2 code is probably appropriate only if you know for sure that code will never need to be ported to Python 3 (since you're making that port so much harder, and will need to de-nest the metaclass definition for the purpose) -- "throwaway" code, in other words, which won't be around in a few years when some version of Python 3 acquires huge, compelling advantages of speed, functionality, or third-party support, over Python 2.7 (the last ever version of Python 2).
Code that you expect to be throwaway, as the history of computing shows us, has an endearing habit of surprising you utterly, and being still around 20 years later (while perhaps the code you wrote around the same time "for the ages" is utterly forgotten;-). This would certainly seem to suggest avoiding nested definition of metaclasses.
| When to inline definitions of metaclass in Python? | Today I have come across a surprising definition of a metaclass in Python here, with the metaclass definition effectively inlined. The relevant part is
class Plugin(object):
class __metaclass__(type):
def __init__(cls, name, bases, dict):
type.__init__(name, bases, dict)
registry.append((name, cls))
When does it make sense to use such an inline definition?
Further Arguments:
An argument one way would be that the created metaclass is not reusable elsewhere using this technique. A counter argument is that a common pattern in using metaclasses is defining a metaclass and using it in one class and then inhertiting from that. For example, in a conservative metaclass the definition
class DeclarativeMeta(type):
def __new__(meta, class_name, bases, new_attrs):
cls = type.__new__(meta, class_name, bases, new_attrs)
cls.__classinit__.im_func(cls, new_attrs)
return cls
class Declarative(object):
__metaclass__ = DeclarativeMeta
def __classinit__(cls, new_attrs): pass
could have been written as
class Declarative(object): #code not tested!
class __metaclass__(type):
def __new__(meta, class_name, bases, new_attrs):
cls = type.__new__(meta, class_name, bases, new_attrs)
cls.__classinit__.im_func(cls, new_attrs)
return cls
def __classinit__(cls, new_attrs): pass
Any other considerations?
| [
"Like every other form of nested class definition, a nested metaclass may be more \"compact and convenient\" (as long as you're OK with not reusing that metaclass except by inheritance) for many kinds of \"production use\", but can be somewhat inconvenient for debugging and introspection.\nBasically, instead of giv... | [
20
] | [] | [] | [
"metaclass",
"python"
] | stackoverflow_0003483718_metaclass_python.txt |
Q:
wxPython GridSizer.Add() not working for custom control
I'm trying to create a custom control based on wx.richtext.RichTextCtrl and I'm running into a problem. Whenever I attempt to add the custom control to a sizer, wxPython chokes with the error
Traceback (most recent call last):
File "pyebook.py", line 46, in <module>
frame = MainFrame(None, 'pyebook')
File "pyebook.py", line 14, in __init__
self.mainPanel.GetSizer().Add(ReaderControl(self.mainPanel), 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
File "/usr/local/lib/wxPython-unicode-2.8.11.0/lib/python2.6/site-packages/wx-2.8-mac-unicode/wx/_core.py", line 12685, in Add
return _core_.Sizer_Add(*args, **kwargs)
TypeError: wx.Window, wx.Sizer, wx.Size, or (w,h) expected for item
The custom control is at this time extremely simple and looks like this
class ReaderControl(wx.richtext.RichTextCtrl):
def __init__(self, parent, id=-1, value=''):
wx.richtext.RichTextCtrl(parent, id, value, style=wx.richtext.RE_READONLY, name='ReaderControl')
The code I'm using to add the control to the sizer is:
self.mainPanel.GetSizer().Add(ReaderControl(self.mainPanel), 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
Any ideas what I'm doing wrong here?
A:
I think you need to call __ init __ explicitly, so you can pass in 'self'. Otherwise, you are just creating a new instance of RichTextCtrl, not initialising your subclass properly.
IOW:
class ReaderControl(wx.richtext.RichTextCtrl):
def __init__(self, parent, id=-1, value=''):
wx.richtext.RichTextCtrl.__init__(self, parent, id, value, style=wx.richtext.RE_READONLY, name='ReaderControl'
| wxPython GridSizer.Add() not working for custom control | I'm trying to create a custom control based on wx.richtext.RichTextCtrl and I'm running into a problem. Whenever I attempt to add the custom control to a sizer, wxPython chokes with the error
Traceback (most recent call last):
File "pyebook.py", line 46, in <module>
frame = MainFrame(None, 'pyebook')
File "pyebook.py", line 14, in __init__
self.mainPanel.GetSizer().Add(ReaderControl(self.mainPanel), 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
File "/usr/local/lib/wxPython-unicode-2.8.11.0/lib/python2.6/site-packages/wx-2.8-mac-unicode/wx/_core.py", line 12685, in Add
return _core_.Sizer_Add(*args, **kwargs)
TypeError: wx.Window, wx.Sizer, wx.Size, or (w,h) expected for item
The custom control is at this time extremely simple and looks like this
class ReaderControl(wx.richtext.RichTextCtrl):
def __init__(self, parent, id=-1, value=''):
wx.richtext.RichTextCtrl(parent, id, value, style=wx.richtext.RE_READONLY, name='ReaderControl')
The code I'm using to add the control to the sizer is:
self.mainPanel.GetSizer().Add(ReaderControl(self.mainPanel), 1, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
Any ideas what I'm doing wrong here?
| [
"I think you need to call __ init __ explicitly, so you can pass in 'self'. Otherwise, you are just creating a new instance of RichTextCtrl, not initialising your subclass properly.\nIOW:\nclass ReaderControl(wx.richtext.RichTextCtrl):\n def __init__(self, parent, id=-1, value=''):\n wx.richtext.RichText... | [
3
] | [] | [] | [
"custom_controls",
"python",
"wxpython"
] | stackoverflow_0003483613_custom_controls_python_wxpython.txt |
Q:
Django query select distinct by field pairs
I have the field 'submission' which has a user and a problem. How can I get an SQL search result which will give a list of only one result per user-problem pair?
Models are like this:
class Problem(models.Model):
title = models.CharField('Title', max_length = 100)
question = models.TextField('Question')
class Submission(models.Model):
user = models.ForeignKey(User)
problem = models.ForeignKey(Problem)
solution = models.CharKey()
time = models.DateTimeField('Time', auto_now_add=True)
A:
Try this:
distinct_users_problems = Submission.objects.all().values("user", "problem").distinct()
It will give you a list of dicts like this one:
[{'problem': 1, 'user': 1}, {'problem': 2, 'user': 1}, {'problem': 3, 'user': 1}]
containing all the distinct pairs.
It actually results in your usual SELECT DISTINCT SQL query.
A:
Update 2:
(After reading OP's comments) I suggest adding a new model to track the latest submission. Call it LatestSubmission.
class LatestSubmission(models.Model):
user = models.ForeignKey(User)
problem = models.ForeignKey(Problem)
submission = models.ForeignKey(Submission)
You can then either
override Submission.save() to create/update the entry in LatestSubmission every time an user posts a new solution for a Problem
attach a function that does the same to a suitable signal.
such that LatestSubmission will contain one row per problem-user-submission combination pointing to the latest submission for the problem by each user. Once you have this in place you can fire a single query:
LatestSubmission.objects.all().order_by('problem')
Update:
Since the OP has posted sample code, the solution can now be changed as follows:
for user in User.objects.all(): # Get all users
user.submission_set.latest('time') # Pick the latest submission based on time.
Original Answer
In the absence of any date/time based criteria for deciding which is "older" or "newer", you can use the primary key (id) of Submission to "neglect the old ones".
for user in User.objects.all(): # Get all users
user.submission_set.latest('id') # Pick the latest submission by each user.
| Django query select distinct by field pairs | I have the field 'submission' which has a user and a problem. How can I get an SQL search result which will give a list of only one result per user-problem pair?
Models are like this:
class Problem(models.Model):
title = models.CharField('Title', max_length = 100)
question = models.TextField('Question')
class Submission(models.Model):
user = models.ForeignKey(User)
problem = models.ForeignKey(Problem)
solution = models.CharKey()
time = models.DateTimeField('Time', auto_now_add=True)
| [
"Try this:\ndistinct_users_problems = Submission.objects.all().values(\"user\", \"problem\").distinct()\n\nIt will give you a list of dicts like this one:\n[{'problem': 1, 'user': 1}, {'problem': 2, 'user': 1}, {'problem': 3, 'user': 1}]\n\ncontaining all the distinct pairs.\nIt actually results in your usual SELEC... | [
19,
3
] | [] | [] | [
"django",
"django_queryset",
"python"
] | stackoverflow_0003483307_django_django_queryset_python.txt |
Q:
python first web application - where
I am rookie in python - have experience in PHP
my service provider (Bluehost) say that python 2.6 is available, however I am not able to run any script (basic hello word) on it - probably because I try do it PHP way. create a script.php file and place the link to it in browser... :)
Where I can find explanation for dummy like me what I should do with file script.py (hello world inside) in order to be executed and displayed in browser, I am guessing that compilation could be required
thank you
Bensiu
A:
If you're using Apache, this simple tutorial will show you how to configure it and run a python "hello world" script (in the simplest, old-fashioned way: as a CGI script).
This system-administration/configuration part will of course be different with other web servers, or other and better way of running Python web app (WSGI in particular), but then, you're not telling us what server or approach (CGI vs WSGI vs others yet) you want to use, so, this is probably the best we can suggest!-)
| python first web application - where | I am rookie in python - have experience in PHP
my service provider (Bluehost) say that python 2.6 is available, however I am not able to run any script (basic hello word) on it - probably because I try do it PHP way. create a script.php file and place the link to it in browser... :)
Where I can find explanation for dummy like me what I should do with file script.py (hello world inside) in order to be executed and displayed in browser, I am guessing that compilation could be required
thank you
Bensiu
| [
"If you're using Apache, this simple tutorial will show you how to configure it and run a python \"hello world\" script (in the simplest, old-fashioned way: as a CGI script).\nThis system-administration/configuration part will of course be different with other web servers, or other and better way of running Python ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003483981_python.txt |
Q:
Converting a Python Float to a String without losing precision
I am maintaining a Python script that uses xlrd to retrieve values from Excel spreadsheets, and then do various things with them. Some of the cells in the spreadsheet are high-precision numbers, and they must remain as such. When retrieving the values of one of these cells, xlrd gives me a float such as 0.38288746115497402.
However, I need to get this value into a string later on in the code. Doing either str(value) or unicode(value) will return something like "0.382887461155". The requirements say that this is not acceptable; the precision needs to be preserved.
I've tried a couple things so far to no success. The first was using a string formatting thingy:
data = "%.40s" % (value)
data2 = "%.40r" % (value)
But both produce the same rounded number, "0.382887461155".
Upon searching around for people with similar problems on SO and elsewhere on the internet, a common suggestion was to use the Decimal class. But I can't change the way the data is given to me (unless somebody knows of a secret way to make xlrd return Decimals). And when I try to do this:
data = Decimal(value)
I get a TypeError: Cannot convert float to Decimal. First convert the float to a string. But obviously I can't convert it to a string, or else I will lose the precision.
So yeah, I'm open to any suggestions -- even really gross/hacky ones if necessary. I'm not terribly experienced with Python (more of a Java/C# guy myself) so feel free to correct me if I've got some kind of fundamental misunderstanding here.
EDIT: Just thought I would add that I am using Python 2.6.4. I don't think there are any formal requirements stopping me from changing versions; it just has to not mess up any of the other code.
A:
I'm the author of xlrd. There is so much confusion in other answers and comments to rebut in comments so I'm doing it in an answer.
@katriealex: """precision being lost in the guts of xlrd""" --- entirely unfounded and untrue. xlrd reproduces exactly the 64-bit float that's stored in the XLS file.
@katriealex: """It may be possible to modify your local xlrd installation to change the float cast""" --- I don't know why you would want to do this; you don't lose any precision by floating a 16-bit integer!!! In any case that code is used only when reading Excel 2.X files (which had an INTEGER-type cell record). The OP gives no indication that he is reading such ancient files.
@jloubert: You must be mistaken. "%.40r" % a_float is just a baroque way of getting the same answer as repr(a_float).
@EVERYBODY: You don't need to convert a float to a decimal to preserve the precision. The whole point of the repr() function is that the following is guaranteed:
float(repr(a_float)) == a_float
Python 2.X (X <= 6) repr gives a constant 17 decimal digits of precision, as that is guaranteed to reproduce the original value. Later Pythons (2.7, 3.1) give the minimal number of decimal digits that will reproduce the original value.
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32
>>> f = 0.38288746115497402
>>> repr(f)
'0.38288746115497402'
>>> float(repr(f)) == f
True
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win32
>>> f = 0.38288746115497402
>>> repr(f)
'0.382887461154974'
>>> float(repr(f)) == f
True
So the bottom line is that if you want a string that preserves all the precision of a float object, use preserved = repr(the_float_object) ... recover the value later by float(preserved). It's that simple. No need for the decimal module.
A:
You can use repr() to convert to a string without losing precision, then convert to a Decimal:
>>> from decimal import Decimal
>>> f = 0.38288746115497402
>>> d = Decimal(repr(f))
>>> print d
0.38288746115497402
A:
EDIT: I am wrong. I shall leave this answer here so the rest of the thread makes sense, but it's not true. Please see John Machin's answer above. Thanks guys =).
If the above answers work that's great -- it will save you a lot of nasty hacking. However, at least on my system, they won't. You can check this with e.g.
import sys
print( "%.30f" % sys.float_info.epsilon )
That number is the smallest float that your system can distinguish from zero. Anything smaller than that may be randomly added or subtracted from any float when you perform an operation. This means that, at least on my Python setup, the precision is lost inside the guts of xlrd, and there seems to be nothing you can do without modifying it. Which is odd; I'd have expected this case to have occurred before, but apparently not!
It may be possible to modify your local xlrd installation to change the float cast. Open up site-packages\xlrd\sheet.py and go down to line 1099:
...
elif rc == XL_INTEGER:
rowx, colx, cell_attr, d = local_unpack('<HH3sH', data)
self_put_number_cell(rowx, colx, float(d), self.fixed_BIFF2_xfindex(cell_attr, rowx, colx))
...
Notice the float cast -- you could try changing that to a decimal.Decimal and see what happens.
A:
EDIT: Cleared my previous answer b/c it didn't work properly.
I'm on Python 2.6.5 and this works for me:
a = 0.38288746115497402
print repr(a)
type(repr(a)) #Says it's a string
Note: This just converts to a string. You'll need to convert to Decimal yourself later if needed.
A:
As has already been said, a float isn't precise at all - so preserving precision can be somewhat misleading.
Here's a way to get every last bit of information out of a float object:
>>> from decimal import Decimal
>>> str(Decimal.from_float(0.1))
'0.1000000000000000055511151231257827021181583404541015625'
Another way would be like so.
>>> 0.1.hex()
'0x1.999999999999ap-4'
Both strings represent the exact contents of the float. Allmost anything else interprets the float as python thinks it was probably intended (which most of the time is correct).
| Converting a Python Float to a String without losing precision | I am maintaining a Python script that uses xlrd to retrieve values from Excel spreadsheets, and then do various things with them. Some of the cells in the spreadsheet are high-precision numbers, and they must remain as such. When retrieving the values of one of these cells, xlrd gives me a float such as 0.38288746115497402.
However, I need to get this value into a string later on in the code. Doing either str(value) or unicode(value) will return something like "0.382887461155". The requirements say that this is not acceptable; the precision needs to be preserved.
I've tried a couple things so far to no success. The first was using a string formatting thingy:
data = "%.40s" % (value)
data2 = "%.40r" % (value)
But both produce the same rounded number, "0.382887461155".
Upon searching around for people with similar problems on SO and elsewhere on the internet, a common suggestion was to use the Decimal class. But I can't change the way the data is given to me (unless somebody knows of a secret way to make xlrd return Decimals). And when I try to do this:
data = Decimal(value)
I get a TypeError: Cannot convert float to Decimal. First convert the float to a string. But obviously I can't convert it to a string, or else I will lose the precision.
So yeah, I'm open to any suggestions -- even really gross/hacky ones if necessary. I'm not terribly experienced with Python (more of a Java/C# guy myself) so feel free to correct me if I've got some kind of fundamental misunderstanding here.
EDIT: Just thought I would add that I am using Python 2.6.4. I don't think there are any formal requirements stopping me from changing versions; it just has to not mess up any of the other code.
| [
"I'm the author of xlrd. There is so much confusion in other answers and comments to rebut in comments so I'm doing it in an answer.\n@katriealex: \"\"\"precision being lost in the guts of xlrd\"\"\" --- entirely unfounded and untrue. xlrd reproduces exactly the 64-bit float that's stored in the XLS file.\n@katriea... | [
56,
3,
1,
0,
0
] | [] | [] | [
"excel",
"floating_point",
"python",
"xlrd"
] | stackoverflow_0003481289_excel_floating_point_python_xlrd.txt |
Q:
Distribute points on a circle as evenly as possible
Problem statement
I have the following problem: I have a circle with a certain number (zero or more) of points on it. These positions are fixed. Now I have to position another set of points on the circle, such as all points together are as evenly distributed around the circle as possible.
Goal
My goal is now to develop a algorithm taking a list of angles (representing the fixed points) and an int value (representing how many additional points should be placed) and returning a list of angles again (containing only the angles where the additional points should lie).
The points don't have to be really evenly distributed (all same distance from each other), but rather as evenly as it is just possible. A perfect solution may not exist most of the time, as certain points are fixed.
The range of all angles lie in between -pi and +pi.
Examples
Some examples of what I am trying to achieve:
fixed_points = [-pi, -pi/2, pi/2]
v v v
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
fill_circle(fixed_points, 1)
# should return: [0]
fill_circle(fixed_points, 2)
# should return: [-pi/6, pi/6]
or:
fixed_points = [-pi, -pi*3/4, -pi/4]
v v v
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
fill_circle(fixed_points, 6)
This last example should return something like: One point is to set right in between -pi*3/4 and -pi/4, that is: -pi/2 and distribute the other 5 points between -pi/4 and +pi (remember it is a circle, so in this case -pi = +pi):
v v x v x x x x x
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
Previous try
I started with a recursive algorithm that first searches for the largest interval between two points and sets the new point right in between. However, it doesn't give satisfying results. Consider, for example, this configuration, with two points needed to be inserted:
v v v
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
first step: insert right in the middle of largest interval
v v x v
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
second step: insert right in the middle of largest interval
-> all intervals are evenly large, so one of them will be taken
v x v v v
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
Not a very nice solution, as it could have been much better distributed (see above: -pi/6 and +pi/6).
Sorry for the long question, I hope you understand what I want to achieve.
I don't need a complete working algorithm, but rather the right idea for developing one. Maybe some pseudocode if you like. Would be very grateful for some hints to push me in the right direction. Thanks in advance!
Update: Completed algorithm:
Thank you all for your answers! It showed up I basically just needed a non-greedy version of my already existing algorithm. I really liked haydenmuhls idea to simplify the problem a little bit by encapsulating an interval/segment class:
class Segment:
def __init__(self, angle, prev_angle, wrap_around):
self.angle = angle
self.length = abs(angle - prev_angle + \
(2*math.pi if wrap_around else 0))
self.num_points = 0
def sub_length(self):
return self.length / (self.num_points + 1)
def next_sub_length(self):
return self.length / (self.num_points + 2)
def add_point(self):
self.num_points += 1
This makes the actual algorithm incredibly easy and readable:
def distribute(angles, n):
# No points given? Evenly distribute them around the circle
if len(angles) == 0:
return [2*math.pi / n * i - math.pi for i in xrange(n)]
# Sort the angles and split the circle into segments
s, pi, ret = sorted(angles), math.pi, []
segments = [Segment(s[i], s[i-1], i == 0) for i in xrange(len(s))]
# Calculate the length of all subsegments if the point
# would be added; take the largest to add the point to
for _ in xrange(n):
max(segments, key = lambda x: x.next_sub_length()).add_point()
# Split all segments and return angles of the points
for seg in segments:
for k in xrange(seg.num_points):
a = seg.angle - seg.sub_length() * (k + 1)
# Make sure all returned values are between -pi and +pi
ret.append(a - 2*pi if a > pi else a + 2*pi if a < -pi else a)
return ret
A:
Suppose you have M points already given, and N more need to be added. If all points were evenly spaced, then you would have gaps of 2*pi/(N+M) between them. So, if you cut at your M points to give M segments of angle, you can certainly place points into a segment (evenly spaced from each other) until the space is less than or equal to 2*pi/(N+M).
So, if the length of a segment is L, then you should place floor(L*(N+M)/(2*pi)) - 1 points into it.
Now you're going to have some points left over. Rank the segments by the spacing that you would have between points if one more point was added. Actually add the point to the segment with lowest rank. Re-insert that one into your sorted list and do this again, until you run out of points.
Since at every time you're placing a point into a segment where the result will be points as widely spaced as possible, and space between points is not dependent on the order in which you added them, you will end up with the optimal spacing.
(Edit: where "optimal" means "maximal minimum distance between points", i.e. avoiding the worst-case scenario of points on top of each other as best as possible.)
(Edit: I hope it's clear that the idea is to decide how many points go into each segment, and then only at the very end, after the numbers have all been decided, do you space them out equally within each segment.)
A:
You could use an Interval object. An interval is an arc of the circle between two of the original, immovable points.
The following is just pseudo-code. Don't expect it to run anywhere.
class Interval {
private length;
private point_count;
constructor(length) {
this.length = length;
this.point_count = 0;
}
public add_point() {
this.point_count++;
}
public length() {
return this.length;
}
// The current length of each sub-interval
public sub_length() {
return this.length / (this.point_count + 1);
}
// The sub-interval length if you were to add another point
public next_sub_length() {
return this.length / (this.point_count + 2);
}
public point_count() {
return this.point_count;
}
}
Create a list of these objects corresponding to the intervals between points on your circle. Each time you add a point, select the interval with the largest next_sub_length(). When you're done, it won't be hard to reconstruct the new circle.
This should give you the spacing with the the largest possible minimum interval. That is, if you score a solution by the length of its smallest interval, this will give you the highest score possible. I think that's what you've been shooting for.
Edit: Just realized that you specifically asked about this in Python. I'm quite a Python n00b, but you should be able to convert this to a Python object easily enough, though you won't need the getters, since everything in Python is public.
A:
Assume the intervals between the points are a_1 ... a_n. Then if we divide up each segment into pieces of minimum size d, we can fit floor(a_i/d) - 1 points in the segment. This means that sum(floor(a/d) for a in interval_lengths) must be larger than or equal to n + s where n is the number of points we want to add, and s is the number of points already there. We want to choose d as large as possible, it is probably best to just do a binary search for the best d.
Once we have chosen d, just step through each segment adding points every d degrees until there are less than 2 d degrees left in the segment
Edit all you need is to find d such that sum(floor(a/d) for a in interval_lengths) == n + s, then assign floor(a_i/d) - 1 to segment i every a_i/(floor(a_i/d) - 1) degrees. Binary search will find this quickly.
Further Edit
Here is code to find d
def get_d(n, a, lo=0, hi=None):
s = len(a)
lo = 360./(s + n)
hi = 2. * lo
d = (lo + hi)/2
c = sum(floor(x/d) for x in a)
while c != (n + s):
if c < (n + s):
hi = mid
else:
lo = mid
d = (lo + hi)/2
c = sum(floor(x/d) for x in a)
return d
A:
First we redefine term as follows:
Find such distribution of N points, that the length of minimal distance between any of two point of these and M predefined is maximal.
So your task is to find this maximum of minimal length. Call it L
You have M lengths of existing segments, assume they are stored in list s. So if this length is L first of all
min(s) > L
and maximum amount of additional points is
f(L) = sum(ls/L -1 for ls in s)
So you can find optimal L using the binary search taking starting minimum L = 0 and maximum L = min(s) and checking condition if sum(ls/L -1 for ls in s) >= N.
Then for each segment s[i] you can just place s[i]/L -1 of points evenly of it.
I think this is optimal solution.
Updated There was flaw in min(s) > L. It was good enough for redefined term, but mistake for the original. I have changed this condition to max(s) > L. Also added skipping of segments smaller than L in binary search.
Here is full updated code:
from math import pi,floor
def distribute(angles,n):
s = [angles[i] - angles[i-1] for i in xrange(len(angles))]
s = [ls if ls > 0 else 2*pi+ls for ls in s]
Lmin, Lmax = 0., max(s)
while Lmax - Lmin >1e-9:
L = (Lmax + Lmin)/2
if sum(max(floor(ls/L) -1,0) for ls in s ) < n: Lmax = L
else : Lmin = L
L= Lmin
p = []
for i in xrange(len(s)):
u = floor(s[i]/L) -1
if u <= 0:continue
d = s[i]/(u+1)
for j in xrange(u):
p.append(angles[i-1]+d*(j+1))
return p[:n]
print distribute((0, pi/4),1)
print distribute((-pi,-pi/2,pi/2),2
A:
You never did say what "how evenly spaced" is measured precisely. Total root-mean-square variance of interval size from perfectly-spaced interval sizes, or something else?
If you look at any particular open interval at the beginning, I believe an optimal solution that places k points in that interval will always space them evenly. Therefore, the problem reduces to choosing cutoff points for what the minimum interval size is, to get a certain number of interstitial points. When done, if you have not enough points to distribute, drop one point from each interval from largest to smallest and repeat until you get something sane.
I'm not sure of the best way to choose the cutoffs, though.
A:
I propose that you consider the problem either as :
A wrapped line - allowing you to determine inter-point distance easily, then re-map to the circle
or
Consider the angles between points and the centre of the circle rather than arc distance. Again, this simplifies the positioning of new points, and is perhaps the easier candidate for re-mapping to circle-edge points. Find all angles between the already-placed points, then bisect the largest (or similar), and place the new point at the appropriate point on the circle edge.
A:
One idea, write angles as list (in degrees):
[30, 80, 120, 260, 310]
Convert to differences:
[ 50, 40, 140, 50, 80]
Note that we wrap around 310 + 80 (mod 360) = 30, the first angle
For each point to be added, split the largest difference:
n=1, split 140:
[50, 40, 70, 70, 50, 80 ]
n=2, split 80:
[50, 40, 70, 70, 50, 40, 40]
Convert back to angles:
[30, 80, 120, 190, 260, 310, 350]
A:
I have a function called "condition" which takes two arguments - a numerator (const) and a denominator (pass-by-ref). It either "grows" or "shrinks" the value of the denominator until an integer number of "denominators" fit into the numerator, i.e. so that numerator/denominator is an integer.
whether the denominator is grown or shrunk depends on which one will cause it to change by a smaller amount.
Set numerator to 2*pi and denominator to anything kind of close to the spacing you want, and you should have pretty close to even distribution.
Note that I also have a function "compare" which compare two doubles for equality within a certain tolerance.
bool compare( const double num1, const double num2, const double epsilon = 0.0001 )
{
return abs(num1 - num2) < epsilon;
}
then the condition function is
void condition(const double numerator, double &denominator)
{
double epsilon = 0.01;
double mod = fmod( numerator, denominator );
if( compare(mod, 0) )
return;
if( mod > denominator/2 ) // decide whether to grow or shrink
epsilon *= -1;
int count = 0;
while( !compare( fmod( numerator, denominator ), 0, 0.1) )
{
denominator += epsilon;
count++;
if( count > 10000 ) // a safety net
return;
}
}
Hope it helps, I know this little algo has come in very handy for me a number of times.
A:
Starting with array [30, 80, 120, 260, 310] and adding n = 5 angles,
the given algorithm (see below) gives [30, 55, 80, 120, 155, 190, 225, 260, 310, 350]
with a root mean square of the differences between angles
rms(diff) = sqrt[sum(diff * diff)] / n = 11.5974135047,
which appears to be optimal for practical purposes.
| Distribute points on a circle as evenly as possible | Problem statement
I have the following problem: I have a circle with a certain number (zero or more) of points on it. These positions are fixed. Now I have to position another set of points on the circle, such as all points together are as evenly distributed around the circle as possible.
Goal
My goal is now to develop a algorithm taking a list of angles (representing the fixed points) and an int value (representing how many additional points should be placed) and returning a list of angles again (containing only the angles where the additional points should lie).
The points don't have to be really evenly distributed (all same distance from each other), but rather as evenly as it is just possible. A perfect solution may not exist most of the time, as certain points are fixed.
The range of all angles lie in between -pi and +pi.
Examples
Some examples of what I am trying to achieve:
fixed_points = [-pi, -pi/2, pi/2]
v v v
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
fill_circle(fixed_points, 1)
# should return: [0]
fill_circle(fixed_points, 2)
# should return: [-pi/6, pi/6]
or:
fixed_points = [-pi, -pi*3/4, -pi/4]
v v v
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
fill_circle(fixed_points, 6)
This last example should return something like: One point is to set right in between -pi*3/4 and -pi/4, that is: -pi/2 and distribute the other 5 points between -pi/4 and +pi (remember it is a circle, so in this case -pi = +pi):
v v x v x x x x x
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
Previous try
I started with a recursive algorithm that first searches for the largest interval between two points and sets the new point right in between. However, it doesn't give satisfying results. Consider, for example, this configuration, with two points needed to be inserted:
v v v
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
first step: insert right in the middle of largest interval
v v x v
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
second step: insert right in the middle of largest interval
-> all intervals are evenly large, so one of them will be taken
v x v v v
|---------|---------|---------|---------|
-pi -pi/2 0 pi/2 pi
Not a very nice solution, as it could have been much better distributed (see above: -pi/6 and +pi/6).
Sorry for the long question, I hope you understand what I want to achieve.
I don't need a complete working algorithm, but rather the right idea for developing one. Maybe some pseudocode if you like. Would be very grateful for some hints to push me in the right direction. Thanks in advance!
Update: Completed algorithm:
Thank you all for your answers! It showed up I basically just needed a non-greedy version of my already existing algorithm. I really liked haydenmuhls idea to simplify the problem a little bit by encapsulating an interval/segment class:
class Segment:
def __init__(self, angle, prev_angle, wrap_around):
self.angle = angle
self.length = abs(angle - prev_angle + \
(2*math.pi if wrap_around else 0))
self.num_points = 0
def sub_length(self):
return self.length / (self.num_points + 1)
def next_sub_length(self):
return self.length / (self.num_points + 2)
def add_point(self):
self.num_points += 1
This makes the actual algorithm incredibly easy and readable:
def distribute(angles, n):
# No points given? Evenly distribute them around the circle
if len(angles) == 0:
return [2*math.pi / n * i - math.pi for i in xrange(n)]
# Sort the angles and split the circle into segments
s, pi, ret = sorted(angles), math.pi, []
segments = [Segment(s[i], s[i-1], i == 0) for i in xrange(len(s))]
# Calculate the length of all subsegments if the point
# would be added; take the largest to add the point to
for _ in xrange(n):
max(segments, key = lambda x: x.next_sub_length()).add_point()
# Split all segments and return angles of the points
for seg in segments:
for k in xrange(seg.num_points):
a = seg.angle - seg.sub_length() * (k + 1)
# Make sure all returned values are between -pi and +pi
ret.append(a - 2*pi if a > pi else a + 2*pi if a < -pi else a)
return ret
| [
"Suppose you have M points already given, and N more need to be added. If all points were evenly spaced, then you would have gaps of 2*pi/(N+M) between them. So, if you cut at your M points to give M segments of angle, you can certainly place points into a segment (evenly spaced from each other) until the space i... | [
10,
5,
4,
2,
1,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"geometry",
"python"
] | stackoverflow_0003479736_algorithm_geometry_python.txt |
Q:
python reorganize codes
Sorry I dont know how to add a comment with the format, so I post another question with code here, as I am new to python, seems that there are many better ways to reorgnize the codes to make it better:
def min_qvalue(self):
s = 0
q = 1
for i in range(len(self.results)):
if self.results[i].score > s:
s = self.results[i].score
q = self.results[i].qvalue
return q
For the above code, should not be the best piece, any improvements possible? thanks :)
A:
This is the same code:
max_score_qvalue = max( (result.score, result.qvalue) for result in self.results)[1]
It makes pairs of the score and qvalue, finds the pair with the highest score (with max) and then gets the qvalue from it.
Actually, I wrote the above just because I keep forgetting that max takes a key function too:
max_score_qvalue = max(self.results, key=(lambda result: result.score)).qvalue
Also your function says min_qvalue but it computes one with the maximum score!
A:
If you result list is mutable and you often have need to compute this, it's may be better to you heap queue algorithm. There's sample code:
import heapq
class ResultManager(object):
def __init__( self , results ):
self.results = [( -result.score, result) for result in results]
heapq.heapify( self.results )
def append( self , result ):
heapq.heappush( self.results , ( -result.score, result) )
def getMaxScoreQValue(self):
return self.results[0][1].qvalue
| python reorganize codes | Sorry I dont know how to add a comment with the format, so I post another question with code here, as I am new to python, seems that there are many better ways to reorgnize the codes to make it better:
def min_qvalue(self):
s = 0
q = 1
for i in range(len(self.results)):
if self.results[i].score > s:
s = self.results[i].score
q = self.results[i].qvalue
return q
For the above code, should not be the best piece, any improvements possible? thanks :)
| [
"This is the same code:\nmax_score_qvalue = max( (result.score, result.qvalue) for result in self.results)[1]\n\nIt makes pairs of the score and qvalue, finds the pair with the highest score (with max) and then gets the qvalue from it.\nActually, I wrote the above just because I keep forgetting that max takes a key... | [
4,
1
] | [] | [] | [
"python",
"refactoring"
] | stackoverflow_0003484181_python_refactoring.txt |
Q:
Is there a description of how __cmp__ works for dict objects in Python 2?
I've been trying to make a dict subclass inheriting from UserDict.DictMixin that supports non-hashable keys. Performance isn't a concern. Unfortunately, Python implements some of the functions in DictMixin by trying to create a dict object from the subclass. I can implement these myself, but I am stuck on __cmp__.
I cannot find a succinct description of the logic used by the built-in __cmp__ for the dict class.
A:
If you are asking how comparing dictionaries works, it is this:
To compare dicts A and B, first compare their lengths. If they are unequal, then return cmp(len(A), len(B)).
Next, find the key adiff in A that is the smallest key for which adiff not in B or A[adiff] != B[adiff]. (If there is no such key, the dicts are equal.)
Also find the smallest key bdiff in B for which bdiff not in A or A[bdiff] != B[bdiff].
If adiff != bdiff, then return cmp(adiff, bdiff). Else return cmp(A[adiff], B[bdiff]).
In pseudo-code:
def smallest_diff_key(A, B):
"""return the smallest key adiff in A such that adiff not in B or A[adiff] != B[bdiff]"""
diff_keys = [k for k in A if k not in B or A[k] != B[k]]
return min(diff_keys)
def dict_cmp(A, B):
if len(A) != len(B):
return cmp(len(A), len(B))
try:
adiff = smallest_diff_key(A, B)
except ValueError:
# No difference.
return 0
bdiff = smallest_diff_key(B, A)
if adiff != bdiff:
return cmp(adiff, bdiff)
return cmp(A[adiff], b[bdiff])
This is translated from the 2.6.3 implementation in dictobject.c.
A:
An alternative is to use the Mapping ABC from the collections package. It is available in 2.6 and up. You just inherit from collections.Mapping and implement the __getitem__, __contains__, and __iter__ methods. You get everything else for free.
A:
There is a description of __cmp__ here, but I think the important thing to note is that __cmp__ is only used if the “rich comparison” methods, such as __lt__ and __eq__ are not defined. Moreover, in Python3, __cmp__ is removed from the language. So perhaps eschew __cmp__ altogether and just define __lt__ and __eq__.
| Is there a description of how __cmp__ works for dict objects in Python 2? | I've been trying to make a dict subclass inheriting from UserDict.DictMixin that supports non-hashable keys. Performance isn't a concern. Unfortunately, Python implements some of the functions in DictMixin by trying to create a dict object from the subclass. I can implement these myself, but I am stuck on __cmp__.
I cannot find a succinct description of the logic used by the built-in __cmp__ for the dict class.
| [
"If you are asking how comparing dictionaries works, it is this:\n\nTo compare dicts A and B, first compare their lengths. If they are unequal, then return cmp(len(A), len(B)).\nNext, find the key adiff in A that is the smallest key for which adiff not in B or A[adiff] != B[adiff]. (If there is no such key, the d... | [
34,
2,
0
] | [] | [] | [
"python",
"python_2.x"
] | stackoverflow_0003484293_python_python_2.x.txt |
Q:
Resizing a wxPython wx.Panel?
I'm trying to place an image panel on a form such that when a button is clicked the 64x64 image that's put on the panel at program start is replaced with a bigger 320x224 image - the pixel sizes aren't so much important as they are being different sizes. I've ALMOST got it - right now the images both load and it does indeed put the second one up when the button's clicked - unfortunately it's the top left 64x64 of the second image, not the whole thing.
It must be possible to resize the panel so the whole image can be viewed, surely? Here's my code as is:
#First we create our form elements. This app has a label on top of a button, both below a panel with an image on it, so we create a sizer and the elements
self.v_sizer = wx.BoxSizer(wx.VERTICAL)
self.imagePanel = wx.Panel(self, -1)
self.FileDescriptionText = wx.StaticText(self, label="No file loaded")
self.openFileDialog = wx.Button(self, label="Load a file", size=(320,40))
#Bind the button click to our press function
self.openFileDialog.Bind(wx.EVT_BUTTON, self.onOpenFileDialog)
#That done, we need to construct the form. First, put the panel, button and label in the vertical sizer...
self.v_sizer.Add(self.imagePanel, 0, flag=wx.ALIGN_CENTER)
self.v_sizer.Add(self.openFileDialog, 0, flag=wx.ALIGN_CENTER)
self.v_sizer.Add(self.ROMDescriptionText, 0, flag=wx.ALIGN_CENTER)
#then assign an image for the panel to have by default, and apply it
self.imageToLoad = wx.Image("imgs/none_loaded.png", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.imageCtrl = wx.StaticBitmap(self.imagePanel, -1, self.imageToLoad, (0, 0), (self.imageToLoad.GetWidth(), self.imageToLoad.GetHeight()))
#Set the sizer to be owned by the window
self.SetSizer(self.v_sizer)
#Set the current window size to the size of the sizer
self.v_sizer.Fit(self)
#Set the Minimum size of the window to the current size of the sizer
self.SetMinSize(self.v_sizer.GetMinSize())
def onOpenFileDialog(self, event):
img = wx.Image("imgs/title.png", wx.BITMAP_TYPE_ANY)
self.imageCtrl.SetBitmap(wx.BitmapFromImage(img))
self.imagePanel.Refresh()
(It's called onOpenFileDialog as eventually it'll be picking the images from a combobox path.)
How can I edit the onOpenFileDialog method such as it finds the image size first, like it does in the self.imageCtrl line in the initial form element creation? I cannot find a way of doing it.
A:
Try calling self.v_sizer.Fit(self) at the end of your onOpenFileDialog() method
| Resizing a wxPython wx.Panel? | I'm trying to place an image panel on a form such that when a button is clicked the 64x64 image that's put on the panel at program start is replaced with a bigger 320x224 image - the pixel sizes aren't so much important as they are being different sizes. I've ALMOST got it - right now the images both load and it does indeed put the second one up when the button's clicked - unfortunately it's the top left 64x64 of the second image, not the whole thing.
It must be possible to resize the panel so the whole image can be viewed, surely? Here's my code as is:
#First we create our form elements. This app has a label on top of a button, both below a panel with an image on it, so we create a sizer and the elements
self.v_sizer = wx.BoxSizer(wx.VERTICAL)
self.imagePanel = wx.Panel(self, -1)
self.FileDescriptionText = wx.StaticText(self, label="No file loaded")
self.openFileDialog = wx.Button(self, label="Load a file", size=(320,40))
#Bind the button click to our press function
self.openFileDialog.Bind(wx.EVT_BUTTON, self.onOpenFileDialog)
#That done, we need to construct the form. First, put the panel, button and label in the vertical sizer...
self.v_sizer.Add(self.imagePanel, 0, flag=wx.ALIGN_CENTER)
self.v_sizer.Add(self.openFileDialog, 0, flag=wx.ALIGN_CENTER)
self.v_sizer.Add(self.ROMDescriptionText, 0, flag=wx.ALIGN_CENTER)
#then assign an image for the panel to have by default, and apply it
self.imageToLoad = wx.Image("imgs/none_loaded.png", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.imageCtrl = wx.StaticBitmap(self.imagePanel, -1, self.imageToLoad, (0, 0), (self.imageToLoad.GetWidth(), self.imageToLoad.GetHeight()))
#Set the sizer to be owned by the window
self.SetSizer(self.v_sizer)
#Set the current window size to the size of the sizer
self.v_sizer.Fit(self)
#Set the Minimum size of the window to the current size of the sizer
self.SetMinSize(self.v_sizer.GetMinSize())
def onOpenFileDialog(self, event):
img = wx.Image("imgs/title.png", wx.BITMAP_TYPE_ANY)
self.imageCtrl.SetBitmap(wx.BitmapFromImage(img))
self.imagePanel.Refresh()
(It's called onOpenFileDialog as eventually it'll be picking the images from a combobox path.)
How can I edit the onOpenFileDialog method such as it finds the image size first, like it does in the self.imageCtrl line in the initial form element creation? I cannot find a way of doing it.
| [
"Try calling self.v_sizer.Fit(self) at the end of your onOpenFileDialog() method\n"
] | [
3
] | [] | [] | [
"panel",
"python",
"wxpython"
] | stackoverflow_0003484326_panel_python_wxpython.txt |
Q:
Any suggestion on package for drawing 'random intervals' charts?
I need to create a chart with the system load over a period of time. The main issue is that the data extraction is happening at random intervals so I need to be able to specify the X axis time position for the value. Any suggestion on a package/module with such functionality ?
Sample Data:
data = { '10:20' : 5, '10:28' : 8, '10:30' : 1 }
A:
I'm not sure I understand the problem; any graphing library will let you specify x coordinates for the points that you plot. Try e.g. matplotlib.
A:
biggles is a decent Python graphing library. You can use SciPy to interpolate if you need to fill in empty spots on your graph.
| Any suggestion on package for drawing 'random intervals' charts? | I need to create a chart with the system load over a period of time. The main issue is that the data extraction is happening at random intervals so I need to be able to specify the X axis time position for the value. Any suggestion on a package/module with such functionality ?
Sample Data:
data = { '10:20' : 5, '10:28' : 8, '10:30' : 1 }
| [
"I'm not sure I understand the problem; any graphing library will let you specify x coordinates for the points that you plot. Try e.g. matplotlib.\n",
"biggles is a decent Python graphing library. You can use SciPy to interpolate if you need to fill in empty spots on your graph.\n"
] | [
1,
0
] | [] | [] | [
"charts",
"python"
] | stackoverflow_0003484605_charts_python.txt |
Q:
Django: Proxy Meta-class ignoring verbose_name_plural
Django-admin is pluralizing a model that I have running as a proxy class.
The normal case here works fine:
class Triviatheme(models.Model):
[ ... elided ... ]
class Meta:
db_table = u'TriviaTheme'
verbose_name_plural='trivia themes'
But for a main content table, I have a parent model called 'Content', and a proxy class:
class News(Content):
DTYPE='News'
class Meta:
verbose_name_plural='News'
proxy = True
But with the Meta in Content is still pluralizing 'News' resulting in 'Newss', so its ignoring the verbose_name_plural field, but not the proxy field.
Similarly, overriding the field in the parent class seems to have no effect. What am I missing? Is there a better way of implementing a large table model with a discriminator column?
Note that this is reverse engineering a DB from a different app, so the model is pretty well set and I can't just change the schema.
edit:
I'm on python 2.6 / Django 1.2.1
I'm also using a Manager class to handle the discriminator, but its still not working.
A:
FWIW I tested this with Django 1.1.1 and Django 1.2.1 and it worked as expected in both cases.
| Django: Proxy Meta-class ignoring verbose_name_plural | Django-admin is pluralizing a model that I have running as a proxy class.
The normal case here works fine:
class Triviatheme(models.Model):
[ ... elided ... ]
class Meta:
db_table = u'TriviaTheme'
verbose_name_plural='trivia themes'
But for a main content table, I have a parent model called 'Content', and a proxy class:
class News(Content):
DTYPE='News'
class Meta:
verbose_name_plural='News'
proxy = True
But with the Meta in Content is still pluralizing 'News' resulting in 'Newss', so its ignoring the verbose_name_plural field, but not the proxy field.
Similarly, overriding the field in the parent class seems to have no effect. What am I missing? Is there a better way of implementing a large table model with a discriminator column?
Note that this is reverse engineering a DB from a different app, so the model is pretty well set and I can't just change the schema.
edit:
I'm on python 2.6 / Django 1.2.1
I'm also using a Manager class to handle the discriminator, but its still not working.
| [
"FWIW I tested this with Django 1.1.1 and Django 1.2.1 and it worked as expected in both cases.\n"
] | [
1
] | [] | [] | [
"django",
"django_admin",
"python",
"reverse_engineering"
] | stackoverflow_0003472395_django_django_admin_python_reverse_engineering.txt |
Q:
Phone Number Regular Expression (Regex) in Python
Dive into python gives an amazing little tutorial on creating a regular expression for phone numbers: http://diveintopython3.ep.io/regular-expressions.html#phonenumbers
The final version comes out to look like:
phone_re = re.compile(r'(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)$', re.VERBOSE)
This works fine for almost all examples I can come up with, however I found a pretty big failure that I can't seem to fix.
If a group of 3 digits comes before the phone number it works fine. IE:
"500 dollars off, call 123-456-7891"
If a group of 3 digits comes after the phone number it fails. IE:
"Call 123-456-7891 for a discount of up to 500"
Any ideas on a fix that would work for both examples?
A:
The (\d*)$ requires that the string you're matching against end with digit characters (the $ signifies "end of line"). Try removing the $ if you're matching against a larger string where the phone number may not be at the end of the line.
A:
Here's your original, with some spaces (use re.VERBOSE, or remove the spaces):
(\d{3}) \D* (\d{3}) \D* (\d{4}) \D* (\d*)
The \D* will match anything that's not a digit, including words. Maybe you should try this:
(\d{3}) \W* (\d{3}) \W* (\d{4}) \W* (\d*)
The \W* matches anything that's not a word. It will match (222) - 222 - 2222. However, it will not match if there is a letter between the numbers, as in (222) x 222 - 2222. The last part of the match (\d*) appears to be looking for an extension. These can be formatted in a variety of ways—I suggest you either drop it or refine it based on how you expect your data to look. And, like Amber says, you should probably drop the $.
| Phone Number Regular Expression (Regex) in Python | Dive into python gives an amazing little tutorial on creating a regular expression for phone numbers: http://diveintopython3.ep.io/regular-expressions.html#phonenumbers
The final version comes out to look like:
phone_re = re.compile(r'(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)$', re.VERBOSE)
This works fine for almost all examples I can come up with, however I found a pretty big failure that I can't seem to fix.
If a group of 3 digits comes before the phone number it works fine. IE:
"500 dollars off, call 123-456-7891"
If a group of 3 digits comes after the phone number it fails. IE:
"Call 123-456-7891 for a discount of up to 500"
Any ideas on a fix that would work for both examples?
| [
"The (\\d*)$ requires that the string you're matching against end with digit characters (the $ signifies \"end of line\"). Try removing the $ if you're matching against a larger string where the phone number may not be at the end of the line.\n",
"Here's your original, with some spaces (use re.VERBOSE, or remove ... | [
2,
0
] | [] | [] | [
"phone_number",
"python",
"regex"
] | stackoverflow_0003484721_phone_number_python_regex.txt |
Q:
Pass instance as function argument
I wrote a nice little app that gets Yahoo weather info and posts it to Twitter. It worked flawlessly and now I want to rearrange the code into differently named files so it makes more sense. And that's when I hit some issues.
Previously, I had a Class in libtweather.py. It was my account. It allowed me to do accountName.parseFeed() and I'd get as output the parsed Yahoo weather. (__ini__ took the weather URL, twitter username and password as args)
This was accessed from my main script which created instances of the Class like this:
exec '%s = lw.twitterWeather("%s", "%s", "%s")' % (item[0], item[1], item[2], item[3])
It kept a list of all account names in a list which was passed as argument to the other functions.
Another function getWeather got weather by doing:
def getWeather(accountList): #account names passed as a list of strings
for item in accountList:
print item, ': ',
item = eval(item)
print item.parseFeed(), '\n
I've decided now to move the getWeather function to the same file as the Class but the line item = eval(item)'s giving me problems because there are no instances created in that file. All of them are in the main script.
Now my question: Is there some way I could give those instances as arguments to the function? Or must I put the function into the Class? Even if I did that, I'd still need to do the item.parseFeed() for multiple items in the list so I'd still need the item = eval(item), no?
Thanks in advance. My app's a tad bit to post here in entirety, but I'll post more code if needed to understand better.
Update: I ended up running my libtweather.py to create instances when it's imported so that the functions inside it can access them (added the instance generating code at the bottom of the script). I'm sure there's a better way but it works for me currently and I'm OK with that.
A:
You should be using an explicit dict for storing these items. eval, exec, globals, locals, and vars are all horribly silly ways to do this poorly. Remember from the Zen of Python: "explicit is better than implicit."
feeds = {}
for item in whatever:
feeds[item[0]] = lw.twitterWeather(*item[1:])
def getWeather(feeds, accountList):
for item in accountList:
print '%s: %s' % (item, feeds[item].parseFeed())
| Pass instance as function argument | I wrote a nice little app that gets Yahoo weather info and posts it to Twitter. It worked flawlessly and now I want to rearrange the code into differently named files so it makes more sense. And that's when I hit some issues.
Previously, I had a Class in libtweather.py. It was my account. It allowed me to do accountName.parseFeed() and I'd get as output the parsed Yahoo weather. (__ini__ took the weather URL, twitter username and password as args)
This was accessed from my main script which created instances of the Class like this:
exec '%s = lw.twitterWeather("%s", "%s", "%s")' % (item[0], item[1], item[2], item[3])
It kept a list of all account names in a list which was passed as argument to the other functions.
Another function getWeather got weather by doing:
def getWeather(accountList): #account names passed as a list of strings
for item in accountList:
print item, ': ',
item = eval(item)
print item.parseFeed(), '\n
I've decided now to move the getWeather function to the same file as the Class but the line item = eval(item)'s giving me problems because there are no instances created in that file. All of them are in the main script.
Now my question: Is there some way I could give those instances as arguments to the function? Or must I put the function into the Class? Even if I did that, I'd still need to do the item.parseFeed() for multiple items in the list so I'd still need the item = eval(item), no?
Thanks in advance. My app's a tad bit to post here in entirety, but I'll post more code if needed to understand better.
Update: I ended up running my libtweather.py to create instances when it's imported so that the functions inside it can access them (added the instance generating code at the bottom of the script). I'm sure there's a better way but it works for me currently and I'm OK with that.
| [
"You should be using an explicit dict for storing these items. eval, exec, globals, locals, and vars are all horribly silly ways to do this poorly. Remember from the Zen of Python: \"explicit is better than implicit.\"\nfeeds = {}\nfor item in whatever:\n feeds[item[0]] = lw.twitterWeather(*item[1:])\n\ndef getW... | [
5
] | [] | [] | [
"function",
"instance",
"oop",
"python"
] | stackoverflow_0003484715_function_instance_oop_python.txt |
Q:
return as list from box with python (mechanize/twill)
If I were to get something like this with showforms(), how would I get the Values out of the SOME_CODE input box?
Form name=ttform (#2)
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 NUMBER select (None) ['0'] of ['0', '10', '2', '3', '4', ...
2 SOMEYEAR select (None) ['201009'] of ['201009', '201007']
3 SOME_CODE select (None) ['AR%'] of ['AR%', 'AR01', 'AR02', ' ...
4 OTHR_CODE select (None) ['%'] of ['%', 'AAEC', 'ACIS', 'AEE' ...
Thanks!!
A:
This does what you want. Tested on a website I found with the type of select control you have above:
>>> import twill.commands
>>> import BeautifulSoup
>>> import re
>>>
>>> a=twill.commands
>>> a.config("readonly_controls_writeable", 1)
>>> b = a.get_browser()
>>> b.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14")
>>> b.clear_cookies()
>>> url="http://www.thesitewizard.com/archive/navigation.shtml"
>>> b.go(url)
==> at http://www.thesitewizard.com/archive/navigation.shtml
>>> form=b.get_form("1")
>>> b.showforms()
Form #1
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 newurl select dummymenu [''] of ['', '#', '#', '', '#']
Form #2
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 cmd hidden (None) _s-xclick
2 1 submit image (None)
3 encrypted hidden (None) -----BEGIN PKCS7-----MIIHwQYJKoZIhvc ...
Form #3
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 None textarea pagelinkcode <a href="http://www.thesitewizard.co ...
Form #4
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 q text searchterms
2 1 None submit (None) Search
Form #5
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 cmd hidden (None) _s-xclick
2 1 submit image (None)
3 encrypted hidden (None) -----BEGIN PKCS7-----MIIHwQYJKoZIhvc ...
>>> valOpts=[]
>>> for c in form.controls:
... if c.name=="newurl":
... if 'items' in c.__dict__:
... print "control %s has items field length %s" % (c, len(c.items))
... if len(c.items)>0:
... for itm in range(len(c.items)):
... valOpts.append(c.items[itm].attrs['value'])
...
control <SelectControl(newurl=[*, #, #, (), #])> has items field length 5
>>> print valOpts
['', '#', '#', '', '#']
>>>
A:
when debugging forms I use the following:
def getFormControlByLabel(self, form, label):
for control in form.controls:
self.log.debug("checking control %s dict = %s" % (control,control.__dict__))
if 'items' in control.__dict__:
self.log.debug("control %s has items field len %d" % (control, len(control.__dict__['items'])))
if len(control.items) > 0:
if 'label' in control.items[0].attrs:
self.log.debug("control %s has label %s" % (control, control.items[0].attrs['label']))
if control.items[0].attrs['label'] == label:
self.log.debug("control %s has label %s" % (control,label))
return control
for control in form.controls:
try:
if control.items[0].attrs['label'] == label:
# y.items[0].attrs['label']
self.log.debug("control %s has matching label %s" % (control,label))
return control
else:
self.log.debug("control %s has label %s" % (control,control.items[0].attrs['label'] ))
except:
pass
| return as list from box with python (mechanize/twill) | If I were to get something like this with showforms(), how would I get the Values out of the SOME_CODE input box?
Form name=ttform (#2)
## ## __Name__________________ __Type___ __ID________ __Value__________________
1 NUMBER select (None) ['0'] of ['0', '10', '2', '3', '4', ...
2 SOMEYEAR select (None) ['201009'] of ['201009', '201007']
3 SOME_CODE select (None) ['AR%'] of ['AR%', 'AR01', 'AR02', ' ...
4 OTHR_CODE select (None) ['%'] of ['%', 'AAEC', 'ACIS', 'AEE' ...
Thanks!!
| [
"This does what you want. Tested on a website I found with the type of select control you have above:\n>>> import twill.commands\n>>> import BeautifulSoup\n>>> import re\n>>> \n>>> a=twill.commands\n>>> a.config(\"readonly_controls_writeable\", 1)\n>>> b = a.get_browser()\n>>> b.set_agent_string(\"Mozilla/5.0 (Wind... | [
1,
0
] | [] | [] | [
"mechanize",
"python",
"twill"
] | stackoverflow_0003199258_mechanize_python_twill.txt |
Q:
Reading fixed amount of bytes from socket with python asyncore
I use asyncore to communicate with remote servers using "length:message"-type protocol. Can someone recommend me a way to read exact amount of bytes from socket? I was trying to use handle_read to fill internal buffer and call my function every time, checking for size of buffer, but it looked too ugly(Check if buffer is long enough to read length, check if buffer length is bigger than message length, read message, etc...). Is it possible to have something like "socket.read(bytes)" which would sleep until buffer is filled enough and return value?
A:
No. Sleeping would defeat the entire purpose of asynchronous IO.
However, this is remarkably simple to do with twisted.
from twisted.protocols.basic import Int32StringReceiver
class YourProtocol(Int32StringReceiver):
def connectionMade(self):
self.sendString('This string will automatically have its length '
'prepended before it\'s sent over the wire!')
def stringReceived(self, string):
print ('Received %r, which came in with a prefixed length, but which '
'has been stripped off for convenience.' % (string,))
| Reading fixed amount of bytes from socket with python asyncore | I use asyncore to communicate with remote servers using "length:message"-type protocol. Can someone recommend me a way to read exact amount of bytes from socket? I was trying to use handle_read to fill internal buffer and call my function every time, checking for size of buffer, but it looked too ugly(Check if buffer is long enough to read length, check if buffer length is bigger than message length, read message, etc...). Is it possible to have something like "socket.read(bytes)" which would sleep until buffer is filled enough and return value?
| [
"No. Sleeping would defeat the entire purpose of asynchronous IO. \nHowever, this is remarkably simple to do with twisted.\nfrom twisted.protocols.basic import Int32StringReceiver\n\nclass YourProtocol(Int32StringReceiver):\n def connectionMade(self):\n self.sendString('This string will automatically have... | [
1
] | [] | [] | [
"asyncore",
"python",
"sockets"
] | stackoverflow_0003484988_asyncore_python_sockets.txt |
Q:
Appengine forms Option Select from db.Model
My application does not write all data in the database. In the example below just type in the DB name. All fields select dropdown are not recorded in the database. Help please
I have a models Docente
ESCOLHA_SEXO = (u'masculino', u'feminino')
CHOICES_UNIDADE = ('Escola Superior de Tecnologia', 'Escola Superior de Gestao')
CHOICES_CATEGORIA = ('assistente', 'coordenador', 'adjunto')
CHOICES_REGIME = ('trinta', 'cinquenta', 'sessenta', 'cem')
class Docente(db.Model):
photo=db.BlobProperty(u'photo')
docente_nome = db.StringProperty(u'docente_nome',
required=False)
docente_unidade = db.StringProperty(u'docente_unidade',
required=False,
default='Escola Superior de Tecnologia',
choices = CHOICES_UNIDADE )
docente_categoria = db.StringProperty(u'docente_categoria',
default='assistente',
choices =CHOICES_CATEGORIA)
docente_regime = db.StringProperty(u'docente_regime',
required=False,
choices =CHOICES_REGIME)
utilizador=db.ReferenceProperty(Utilizador,
verbose_name=u'utilizador',
required=False,
collection_name='utilizadores')
This is my main:
class CriarCvHandler(webapp.RequestHandler):
def post(self):
if self.request.get('EscDocente'):
id = int(self.request.get('EscDocente'))
docente=models.Docente.get(db.Key.from_path('Docente', id))
else:
docente = models.Docente()
data=forms.DocenteForm(data = self.request.POST)
if data.is_valid():
if self.request.get('photo'):
docente.docente_nome=self.request.get('docente_nome')
docente.docente_unidade=self.request.get('docente_unidade')
docente.docente_categoria=self.request.get('docente_categoria')
docente.docente_regime=self.request.get('docente_regime')
listaUtlz = models.Utilizador.all()
listaUtlz.filter('user =', users.get_current_user())
for utilizador in listaUtlz:
docente.utilizador=utilizador.key()
docente.put()
self.redirect('/academia')
else:
self.redirect('/criarCv')
def get(self):
user=users.get_current_user()
if user:
greeting= ("<ul><li><strong><b>Benvindo %s </b></strong>|</li><li><a href=\"/perfil\"> Minha Conta </a>|</li><li><a href=\"%s\"> Logout</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
else:
greeting = ("<ul><li><a href=\"%s\">Login</a></li></ul>" %(users.create_login_url("/")))
conjUnidade=models.Docente.docente_unidade.choices
conjCategoria=models.Docente.docente_categoria.choices
conjRegime=models.Docente.docente_regime.choices
utilizador=db.Query(models.Utilizador)
utilizador=utilizador.filter('user =', user)
listaUtlz=utilizador.fetch(limit=1)
if self.request.GET.has_key('id'):
id=int(self.request.GET['id'])
EscDocente=models.Docente.get(db.Key.from_path('Docente', id))
path = os.path.join(os.path.dirname(__file__), 'templates/criarCv.html')
self.response.out.write(template.render(path, locals(), debug = True))
This is my template:
Nome Docente:
<tr>
<td>Unidade: </td>
<td>
<select name="docente_unidade">
{% for docente_unidade in conjUnidade %}
<option selected> {{ docente_unidade }} </option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>Categoria: </td>
<td>
<select name="categoria">
<option></option>
{% for docente_categoria in conjCategoria %}
{% ifequal EscDocente.docente_categoria docente_categoria %}
<option selected> {{ docente_categoria }} </option>
{% else %}
<option> {{ docente_categoria }} </option>
{% endifequal %}
{% endfor %}
</select>
</td>
</tr>
<td>Regime: </td>
<td>
<select name="regime">
<option></option>
{% for docente_regime in conjRegime %}
{% ifequal EscDocente.docente_regime docente_regime %}
<option selected> {{ docente_regime }} </option>
{% else %}
<option> {{ docente_regime }} </option>
{% endifequal %}
{% endfor %}
</select>
</td>
<tr>
<td></td>
<td>
<input type="button" value="Guardar" onclick="guardaCv()" />
A:
Change these:
<select name="categoria">
...
<select name="regime">
To this:
<select name="docente_categoria">
...
<select name="docente_regime">
| Appengine forms Option Select from db.Model | My application does not write all data in the database. In the example below just type in the DB name. All fields select dropdown are not recorded in the database. Help please
I have a models Docente
ESCOLHA_SEXO = (u'masculino', u'feminino')
CHOICES_UNIDADE = ('Escola Superior de Tecnologia', 'Escola Superior de Gestao')
CHOICES_CATEGORIA = ('assistente', 'coordenador', 'adjunto')
CHOICES_REGIME = ('trinta', 'cinquenta', 'sessenta', 'cem')
class Docente(db.Model):
photo=db.BlobProperty(u'photo')
docente_nome = db.StringProperty(u'docente_nome',
required=False)
docente_unidade = db.StringProperty(u'docente_unidade',
required=False,
default='Escola Superior de Tecnologia',
choices = CHOICES_UNIDADE )
docente_categoria = db.StringProperty(u'docente_categoria',
default='assistente',
choices =CHOICES_CATEGORIA)
docente_regime = db.StringProperty(u'docente_regime',
required=False,
choices =CHOICES_REGIME)
utilizador=db.ReferenceProperty(Utilizador,
verbose_name=u'utilizador',
required=False,
collection_name='utilizadores')
This is my main:
class CriarCvHandler(webapp.RequestHandler):
def post(self):
if self.request.get('EscDocente'):
id = int(self.request.get('EscDocente'))
docente=models.Docente.get(db.Key.from_path('Docente', id))
else:
docente = models.Docente()
data=forms.DocenteForm(data = self.request.POST)
if data.is_valid():
if self.request.get('photo'):
docente.docente_nome=self.request.get('docente_nome')
docente.docente_unidade=self.request.get('docente_unidade')
docente.docente_categoria=self.request.get('docente_categoria')
docente.docente_regime=self.request.get('docente_regime')
listaUtlz = models.Utilizador.all()
listaUtlz.filter('user =', users.get_current_user())
for utilizador in listaUtlz:
docente.utilizador=utilizador.key()
docente.put()
self.redirect('/academia')
else:
self.redirect('/criarCv')
def get(self):
user=users.get_current_user()
if user:
greeting= ("<ul><li><strong><b>Benvindo %s </b></strong>|</li><li><a href=\"/perfil\"> Minha Conta </a>|</li><li><a href=\"%s\"> Logout</a></li></ul>" %(user.nickname(), users.create_logout_url("/")))
else:
greeting = ("<ul><li><a href=\"%s\">Login</a></li></ul>" %(users.create_login_url("/")))
conjUnidade=models.Docente.docente_unidade.choices
conjCategoria=models.Docente.docente_categoria.choices
conjRegime=models.Docente.docente_regime.choices
utilizador=db.Query(models.Utilizador)
utilizador=utilizador.filter('user =', user)
listaUtlz=utilizador.fetch(limit=1)
if self.request.GET.has_key('id'):
id=int(self.request.GET['id'])
EscDocente=models.Docente.get(db.Key.from_path('Docente', id))
path = os.path.join(os.path.dirname(__file__), 'templates/criarCv.html')
self.response.out.write(template.render(path, locals(), debug = True))
This is my template:
Nome Docente:
<tr>
<td>Unidade: </td>
<td>
<select name="docente_unidade">
{% for docente_unidade in conjUnidade %}
<option selected> {{ docente_unidade }} </option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td>Categoria: </td>
<td>
<select name="categoria">
<option></option>
{% for docente_categoria in conjCategoria %}
{% ifequal EscDocente.docente_categoria docente_categoria %}
<option selected> {{ docente_categoria }} </option>
{% else %}
<option> {{ docente_categoria }} </option>
{% endifequal %}
{% endfor %}
</select>
</td>
</tr>
<td>Regime: </td>
<td>
<select name="regime">
<option></option>
{% for docente_regime in conjRegime %}
{% ifequal EscDocente.docente_regime docente_regime %}
<option selected> {{ docente_regime }} </option>
{% else %}
<option> {{ docente_regime }} </option>
{% endifequal %}
{% endfor %}
</select>
</td>
<tr>
<td></td>
<td>
<input type="button" value="Guardar" onclick="guardaCv()" />
| [
"Change these:\n<select name=\"categoria\">\n\n...\n<select name=\"regime\">\n\nTo this:\n<select name=\"docente_categoria\">\n\n...\n<select name=\"docente_regime\">\n\n"
] | [
1
] | [] | [] | [
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0003485299_django_templates_google_app_engine_python.txt |
Q:
Why can't I import pg.py?
>>> import pg
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
import pg
File "C:\EPD\lib\site-packages\pg.py", line 21, in <module>
from _pg import *
ImportError: DLL load failed: The specified module could not be found.
I downloaded PyGreSQL 4.0 for Windows, and installed it into the \LIB\site-packages of my python directory. When I try to import pg.py, I get this error. :(
A:
Looks like it's unable to find libpq.dll. Make sure that the directory which contains libpq.dll from your PostgreSQL installation is in your Windows path.
A:
Have you looked in the C:\EPD\lib\site-packages\ directory? Perhaps you did not install to the right site-packages directory?
| Why can't I import pg.py? | >>> import pg
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
import pg
File "C:\EPD\lib\site-packages\pg.py", line 21, in <module>
from _pg import *
ImportError: DLL load failed: The specified module could not be found.
I downloaded PyGreSQL 4.0 for Windows, and installed it into the \LIB\site-packages of my python directory. When I try to import pg.py, I get this error. :(
| [
"Looks like it's unable to find libpq.dll. Make sure that the directory which contains libpq.dll from your PostgreSQL installation is in your Windows path.\n",
"Have you looked in the C:\\EPD\\lib\\site-packages\\ directory? Perhaps you did not install to the right site-packages directory?\n"
] | [
1,
0
] | [] | [] | [
"pygresql",
"python",
"sqlite"
] | stackoverflow_0003485483_pygresql_python_sqlite.txt |
Q:
Python, hard-code it time for filename manipulation
I know how to append date to the end of the file name, but I m not sure how can I later in script put that filename as a link to FTP server.
For instance:
import datetime
now = datetime.datetime.now()
suffix = now.strftime(""%d-%m-%Y, %H:%M"")
filename = 'My history(%s).txt'%suffix
How can I hard code it NOW variable so that I can manipulate with it later in script and that time is always the same as it was when it was added to variable.
A:
There is no need to 'hard code' the now variable so that it always references the same point of time. The now() function from the datetime library returns a datetime object; the values of the returned object will not change over time.
>>> import datetime
>>> import time
>>> x = datetime.datetime.now()
>>> x
datetime.datetime(2010, 8, 14, 16, 26, 6, 592441)
>>> time.sleep(5)
>>> x
datetime.datetime(2010, 8, 14, 16, 26, 6, 592441)
| Python, hard-code it time for filename manipulation | I know how to append date to the end of the file name, but I m not sure how can I later in script put that filename as a link to FTP server.
For instance:
import datetime
now = datetime.datetime.now()
suffix = now.strftime(""%d-%m-%Y, %H:%M"")
filename = 'My history(%s).txt'%suffix
How can I hard code it NOW variable so that I can manipulate with it later in script and that time is always the same as it was when it was added to variable.
| [
"There is no need to 'hard code' the now variable so that it always references the same point of time. The now() function from the datetime library returns a datetime object; the values of the returned object will not change over time.\n>>> import datetime\n>>> import time\n>>> x = datetime.datetime.now()\n>>> x\nd... | [
4
] | [] | [] | [
"python",
"time"
] | stackoverflow_0003485502_python_time.txt |
Q:
Pythonic way of repeating a method call on different finite arguments
I was staring at a piece of Python code I produced, which, though correct, is ugly. Is there a more pythonic way of doing this?
r = self.get_pixel(x,y, RED)
g = self.get_pixel(x,y, GREEN)
b = self.get_pixel(x,y, BLUE)
t = function(r,g,b)
if t:
r2, g2, b2 = t
self.set_pixel(x,y,RED, r2)
self.set_pixel(x,y,GREEN, g2)
self.set_pixel(x,y,BLUE, b2)
The problem is the repetition of the method calls for get_pixel and set_pixel. For your information:
RED, GREEN, BLUE = range(3)
Also note that I'd like to preserve code clarity and cleanness.
A:
As you are using self, it appears that get_pixel etc are methods of your class. Instead of list comprehensions and zip() and other workarounds, look at the APIs and fix them. Two suggestions:
Write another method get_pixel_colors(x, y) which returns a 3-tuple. Then you can write r, g, b = self.get_pixel_colors(x, y)
Similarly: self.set_pixel_colors(x, y, r, g, b)
Even better, you can use the *args notation:
old_colors = self.get_pixel_colors(x, y)
new_colors = function(*old_colors)
if new_colors:
self.set_pixel_colors(x, y, *new_colors)
A:
I would use a named tuple to represent the color, and change the class to use color attributes rather than individual get_pixel(x,y,c).
For example:
from collections import namedtuple
Color = namedtuple('Color', 'red green blue')
#...
color = self.get_pixel(x, y)
t = function(*color)
if t:
self.set_pixel(x, y, color)
Edit: thanks to John Machin for the corrections suggested here. His answer also gives more insight into the reasons for this approach. I would add that a namedtuple gives the advantage of having fields such as color.red, color.green, color.blue which I like to have available. YMMV.
A:
To call a function with different arguments and collect the results you can use a list comprehension:
r1, r2, r3 = [foo(x) for x in [x1, x2, x3]]
To call a function for its side-effects I'd recommend not using a list comprehension and instead using an ordinary for loop:
ijs = [(i1, j1), (i2, j2), (i3, j3)]
for i, j in ijs:
bar(i, j)
However your problem really is not that you should not be calling your set pixel for each color separately. If at all possible, change your API so that you can do this as suggested by John Machin:
old_colors = self.get_pixel_colors(x, y)
new_colors = function(*old_colors)
if new_colors:
self.set_pixel_colors(x, y, *new_colors)
A:
colors = (RED, GREEN, BLUE)
r, g, b = [self.get_pixel(x, y, col) for col in colors]
t = function(r, g, b)
for col, rgb in zip(colors, t):
self.set_pixel(x, y, col, rgb)
| Pythonic way of repeating a method call on different finite arguments | I was staring at a piece of Python code I produced, which, though correct, is ugly. Is there a more pythonic way of doing this?
r = self.get_pixel(x,y, RED)
g = self.get_pixel(x,y, GREEN)
b = self.get_pixel(x,y, BLUE)
t = function(r,g,b)
if t:
r2, g2, b2 = t
self.set_pixel(x,y,RED, r2)
self.set_pixel(x,y,GREEN, g2)
self.set_pixel(x,y,BLUE, b2)
The problem is the repetition of the method calls for get_pixel and set_pixel. For your information:
RED, GREEN, BLUE = range(3)
Also note that I'd like to preserve code clarity and cleanness.
| [
"As you are using self, it appears that get_pixel etc are methods of your class. Instead of list comprehensions and zip() and other workarounds, look at the APIs and fix them. Two suggestions:\n\nWrite another method get_pixel_colors(x, y) which returns a 3-tuple. Then you can write r, g, b = self.get_pixel_colors(... | [
5,
4,
1,
1
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0003485403_coding_style_python.txt |
Q:
Porting old apps from Python 2.4
I have a bunch of apps written in Python 2.4. I'd like to port them onto more recent version of the interpreter. Let's say I have no need of syntax features, but I am very concerned about performance. So which of the upper python versions is the fastest (the most optimized) - 2.4 or 2.5 or 2.6 or 2.7 ?
Performance comparison articles (URL) are much appreciated.
Thanks
A:
In general, each successive version along the 2.* line becomes a bit faster than the previous one -- because optimization and fine-tuning is a high priority for many contributors.
I don't know of any articles on performance configuration: my advice is to identify the "hot spots" of your specific application by profiling (but surely you're already doing that, if you are "very concerned about performance") and turn them into microbenchmarks to run on timeit across all four versions.
For example, suppose that ''.joining middling-length lists of shortish strings is known to be a hotspot in your applications. Then, we could measure:
$ python2.4 -mtimeit -s'x=[str(i) for i in range(99)]' '"".join(x)'
100000 loops, best of 3: 2.87 usec per loop
$ python2.5 -mtimeit -s'x=[str(i) for i in range(99)]' '"".join(x)'
100000 loops, best of 3: 3.02 usec per loop
$ python2.6 -mtimeit -s'x=[str(i) for i in range(99)]' '"".join(x)'
100000 loops, best of 3: 2.7 usec per loop
$ python2.7 -mtimeit -s'x=[str(i) for i in range(99)]' '"".join(x)'
100000 loops, best of 3: 2.12 usec per loop
python2.5 in this case does not follow the other releases' general trend (repeating the measurement confirms it's about 5% slower than python2.4 on this microbenchmark) and 2.7 is surprisingly faster than expected (a whopping 26%+ faster than 2.4), but that's for a specific build and platform (as well of course as a specific microbenchmark), which is why it's important for you to perform such measurements on benchmarks and platforms/builds of your specific interest (if you're willing to just accept the general consideration that later builds tend to be faster, then you're not really "very" concerned about performance;-).
| Porting old apps from Python 2.4 | I have a bunch of apps written in Python 2.4. I'd like to port them onto more recent version of the interpreter. Let's say I have no need of syntax features, but I am very concerned about performance. So which of the upper python versions is the fastest (the most optimized) - 2.4 or 2.5 or 2.6 or 2.7 ?
Performance comparison articles (URL) are much appreciated.
Thanks
| [
"In general, each successive version along the 2.* line becomes a bit faster than the previous one -- because optimization and fine-tuning is a high priority for many contributors.\nI don't know of any articles on performance configuration: my advice is to identify the \"hot spots\" of your specific application by ... | [
4
] | [] | [] | [
"performance",
"python"
] | stackoverflow_0003485886_performance_python.txt |
Q:
Using fuzzing lib (python)
I'm trying to use this library : http://pastebin.com/xgPXpGtw (an example of use: http://pastebin.com/fNFAW3Fh)
I have some issues since I dont want to split in an array all the byte as he does.
My test script looks like this:
import random
from random import *
def onerand(packet):
pack = packet[:]
byte = str(chr(choice(range(256))))
pack[choice(range(len(packet)))]= byte
print "fuzzing rand byte:%s\n" % (byte.encode("hex"))
return pack
test = "\x63\x63\x63\x63\x63\x63\x63\x63\x63\x63\x63\x63\x63\x63"
while True:
print onerand(test)
And actually returns :
Traceback (most recent call last):
File "test.py", line 14, in <module>
print onerand(test)
File "test.py", line 7, in onerand
pack[choice(range(len(packet)))]= byte
TypeError: 'str' object does not support item assignment
So what should i do to be able to use that function on the test parameters ?
Thanks !
A:
In Python, strings are immutable. You pass to function onerand a string, argument name packet, copy it giving a local name pack (still a string, still therefore immutable), then you try to do
pack[whatever] = byte
the index doesn't matter: you're trying to modify the immutable string. That's what the error message is telling you, as clearly as possible it seems to me: you can't do that.
I dont want to split in an array all
the byte
Well you surely can't use a string, if you need to assign some of them. What do you have against arrays, anyway? import array, use pack = array.array('c', packet) instead of pack = packet[:], and live happily ever after -- an array.array is very compact and speedy, and mutable too!
Edit: you could do it with a list, as in the accepted answer, but that's only at a truly steep relative cost in performance. Consider, for example:
$ py26 -mtimeit -s's="".join([str(x)[0] for x in range(99)]); import array
> ' 'a=array.array("c",s); a[23]="b"; b=a.tostring()'
1000000 loops, best of 3: 1.09 usec per loop
$ py26 -mtimeit -s's="".join([str(x)[0] for x in range(99)]); import array
> ' 'a=list(s); a[23]="b"; b="".join(a)'
100000 loops, best of 3: 7.68 usec per loop
A list is a much more general structure than the array.array you really need here, whence the more-than-seven-times slowdown in choosing the wrong data structure. (It's less terrible in Python 2.7, "only" a 4-times-plus slowdown -- but, think how much it would cost you to buy a machine four times faster than your current one, and maybe you'll agree that even speeding things up by "just" 4+ times, instead of 7+ times, is still a well-worthwhile byproduct;-).
A:
instead of pack = packet[:], use pack = list(packet), and then return ''.join(pack) at the end.
you can't replace a single byte of a string, but you can convert it to a list of characters, replace one item, and then convert back.
| Using fuzzing lib (python) | I'm trying to use this library : http://pastebin.com/xgPXpGtw (an example of use: http://pastebin.com/fNFAW3Fh)
I have some issues since I dont want to split in an array all the byte as he does.
My test script looks like this:
import random
from random import *
def onerand(packet):
pack = packet[:]
byte = str(chr(choice(range(256))))
pack[choice(range(len(packet)))]= byte
print "fuzzing rand byte:%s\n" % (byte.encode("hex"))
return pack
test = "\x63\x63\x63\x63\x63\x63\x63\x63\x63\x63\x63\x63\x63\x63"
while True:
print onerand(test)
And actually returns :
Traceback (most recent call last):
File "test.py", line 14, in <module>
print onerand(test)
File "test.py", line 7, in onerand
pack[choice(range(len(packet)))]= byte
TypeError: 'str' object does not support item assignment
So what should i do to be able to use that function on the test parameters ?
Thanks !
| [
"In Python, strings are immutable. You pass to function onerand a string, argument name packet, copy it giving a local name pack (still a string, still therefore immutable), then you try to do \npack[whatever] = byte\n\nthe index doesn't matter: you're trying to modify the immutable string. That's what the error ... | [
3,
2
] | [] | [] | [
"fuzzing",
"python",
"string"
] | stackoverflow_0003485989_fuzzing_python_string.txt |
Q:
Should I be comparing bytes using struct?
I'm trying to compare the data within two files, and retrieve a list of offsets of where the differences are.
I tried it on some text files and it worked quite well..
However on non-text files (that still contain ascii text), I call them binary data files. (executables, so on..)
It seems to think some bytes are the same, even though when I look at it in hex editor, they are obviously not. I tried printing out this binary data that it thinks is the same and I get blank lines where it should be printed.
Thus, I think this is the source of the problem.
So what is the best way to compare bytes of data that could be both binary and contain ascii text? I thought using the struct module by be a starting point...
As you can see below, I compare the bytes with the == operator
Here's the code:
import os
import math
#file1 = 'file1.txt'
#file2 = 'file2.txt'
file1 = 'file1.exe'
file2 = 'file2.exe'
file1size = os.path.getsize(file1)
file2size = os.path.getsize(file2)
a = file1size - file2size
end = file1size #if they are both same size
if a > 0:
#file 2 is smallest
end = file2size
big = file1size
elif a < 0:
#file 1 is smallest
end = file1size
big = file2size
f1 = open(file1, 'rb')
f2 = open(file2, 'rb')
readSize = 500
r = readSize
off = 0
data = []
looking = False
d = open('data.txt', 'w')
while off < end:
f1.seek(off)
f2.seek(off)
b1, b2 = f1.read(r), f2.read(r)
same = b1 == b2
print ''
if same:
print 'Same at: '+str(off)
print 'readSize: '+str(r)
print b1
print b2
print ''
#save offsets of the section of "different" bytes
#data.append([diffOff, diffOff+off-1]) #[begin diff off, end diff off]
if looking:
d.write(str(diffOff)+" => "+str(diffOff+off-2)+"\n")
looking = False
r = readSize
off = off + 1
else:
off = off + r
else:
if r == 1:
looking = True
diffOff = off
off = off + 1 #continue reading 1 at a time, until u find a same reading
r = 1 #it will shoot back to the last off, since we didn't increment it here
d.close()
f1.close()
f2.close()
#add the diff ending portion to diff data offs, if 1 file is longer than the other
a = int(math.fabs(a)) #get abs val of diff
if a:
data.append([big-a, big-1])
print data
A:
Did you try difflib and filecmp modules?
This module provides classes and
functions for comparing sequences. It
can be used for example, for comparing
files, and can produce difference
information in various formats,
including HTML and context and unified
diffs. For comparing directories and
files, see also, the filecmp module.
The filecmp module defines functions
to compare files and directories, with
various optional time/correctness
trade-offs. For comparing files, see
also the difflib module
.
A:
You are probably encountering encoding/decoding problems. Someone may suggest a better solution, but you could try reading the file into a bytearray so you're reading raw bytes instead of decoded characters:
Here's a crude example:
$ od -Ax -tx1 /tmp/aa
000000 e0 b2 aa 0a
$ od -Ax -tx1 /tmp/bb
000000 e0 b2 bb 0a
$ cat /tmp/diff.py
a = bytearray(open('/tmp/aa', 'rb').read())
b = bytearray(open('/tmp/bb', 'rb').read())
print "%02x, %02x" % (a[2], a[3])
print "%02x, %02x" % (b[2], b[3])
$ python /tmp/diff.py
aa, 0a
bb, 0a
| Should I be comparing bytes using struct? | I'm trying to compare the data within two files, and retrieve a list of offsets of where the differences are.
I tried it on some text files and it worked quite well..
However on non-text files (that still contain ascii text), I call them binary data files. (executables, so on..)
It seems to think some bytes are the same, even though when I look at it in hex editor, they are obviously not. I tried printing out this binary data that it thinks is the same and I get blank lines where it should be printed.
Thus, I think this is the source of the problem.
So what is the best way to compare bytes of data that could be both binary and contain ascii text? I thought using the struct module by be a starting point...
As you can see below, I compare the bytes with the == operator
Here's the code:
import os
import math
#file1 = 'file1.txt'
#file2 = 'file2.txt'
file1 = 'file1.exe'
file2 = 'file2.exe'
file1size = os.path.getsize(file1)
file2size = os.path.getsize(file2)
a = file1size - file2size
end = file1size #if they are both same size
if a > 0:
#file 2 is smallest
end = file2size
big = file1size
elif a < 0:
#file 1 is smallest
end = file1size
big = file2size
f1 = open(file1, 'rb')
f2 = open(file2, 'rb')
readSize = 500
r = readSize
off = 0
data = []
looking = False
d = open('data.txt', 'w')
while off < end:
f1.seek(off)
f2.seek(off)
b1, b2 = f1.read(r), f2.read(r)
same = b1 == b2
print ''
if same:
print 'Same at: '+str(off)
print 'readSize: '+str(r)
print b1
print b2
print ''
#save offsets of the section of "different" bytes
#data.append([diffOff, diffOff+off-1]) #[begin diff off, end diff off]
if looking:
d.write(str(diffOff)+" => "+str(diffOff+off-2)+"\n")
looking = False
r = readSize
off = off + 1
else:
off = off + r
else:
if r == 1:
looking = True
diffOff = off
off = off + 1 #continue reading 1 at a time, until u find a same reading
r = 1 #it will shoot back to the last off, since we didn't increment it here
d.close()
f1.close()
f2.close()
#add the diff ending portion to diff data offs, if 1 file is longer than the other
a = int(math.fabs(a)) #get abs val of diff
if a:
data.append([big-a, big-1])
print data
| [
"Did you try difflib and filecmp modules?\n\nThis module provides classes and\n functions for comparing sequences. It\n can be used for example, for comparing\n files, and can produce difference\n information in various formats,\n including HTML and context and unified\n diffs. For comparing directories and\n... | [
4,
0
] | [] | [] | [
"byte",
"comparison",
"file",
"python"
] | stackoverflow_0003484460_byte_comparison_file_python.txt |
Q:
How to 'package' a simple, one-file python script for a person that wants to pay for it?
A person (a senior citizen who is learning the very basics of computers) asked me to make a program that will save him LOTS of time with a grunt work type of task. I made the script in Python, it's simple, command line, takes input from the user and saves the output to a file and that's it.
My first question is related to the output of the script:
It doesn't have to be GUI (I have no GUI dev experience and currently no time now), but I also think that it shouldn't be so simplistic as a TXT file, since the output will be 40,000+ lines long and intended for printing (I know it's a waste of paper and I fought hard for him not to do this, but it's his choice).
What file format should I output it to? Maybe an HTML file?
Next, he asked me to burn it into a CD that he can just pop it in his laptop and run it directly and save the output to 'C:'. By the nature of his computing capacity, it has to be as simple as possible, and require the least 'after service.'
There's no restriction regarding the size that the whole program occupies in his computer.
I tried creating an EXE of my Python script with PY2EXE but when I execute the .EXE, it creates the output file on the same folder, opens no 'window', asks for no input, and runs FOREVER, with the output file size increasing by 20mb/s! Of course, when I run it on regular python, it runs perfectly fine. I looked over other stackoverflow threads and followed the 'bundle_files':1 parameter but still...
I'm using Python2.7, should I try PyInstaller? If yes, could people point me to a good tutorial?
Thanks in advance
A:
There's a good PyInstaller tutorial here. However, PyInstaller does not (yet) support Python 2.7 (indeed, on Windows, I believe there are problems with 2.6 also).
In your use case I would recommend PortablePython -- Python configured to run (on Windows) from a USB key. You could easily put on the USB key Python in the "portable" version, your script, and a .bat that runs your script. However, PortablePython also does not yet support Python 2.7 (2.6, sure, no problem).
If you live on the bleeding edge -- making for-pay work in a release that's been out for so little time, that it doesn't have a .1 subrelease yet;-) -- it's not surprising that advanced third-party tools such as packagers don't fully support you yet. What 2.7 features (not found in 2.6) are you using, to be worth this hassle to you?
| How to 'package' a simple, one-file python script for a person that wants to pay for it? | A person (a senior citizen who is learning the very basics of computers) asked me to make a program that will save him LOTS of time with a grunt work type of task. I made the script in Python, it's simple, command line, takes input from the user and saves the output to a file and that's it.
My first question is related to the output of the script:
It doesn't have to be GUI (I have no GUI dev experience and currently no time now), but I also think that it shouldn't be so simplistic as a TXT file, since the output will be 40,000+ lines long and intended for printing (I know it's a waste of paper and I fought hard for him not to do this, but it's his choice).
What file format should I output it to? Maybe an HTML file?
Next, he asked me to burn it into a CD that he can just pop it in his laptop and run it directly and save the output to 'C:'. By the nature of his computing capacity, it has to be as simple as possible, and require the least 'after service.'
There's no restriction regarding the size that the whole program occupies in his computer.
I tried creating an EXE of my Python script with PY2EXE but when I execute the .EXE, it creates the output file on the same folder, opens no 'window', asks for no input, and runs FOREVER, with the output file size increasing by 20mb/s! Of course, when I run it on regular python, it runs perfectly fine. I looked over other stackoverflow threads and followed the 'bundle_files':1 parameter but still...
I'm using Python2.7, should I try PyInstaller? If yes, could people point me to a good tutorial?
Thanks in advance
| [
"There's a good PyInstaller tutorial here. However, PyInstaller does not (yet) support Python 2.7 (indeed, on Windows, I believe there are problems with 2.6 also).\nIn your use case I would recommend PortablePython -- Python configured to run (on Windows) from a USB key. You could easily put on the USB key Python... | [
6
] | [] | [] | [
"executable",
"python"
] | stackoverflow_0003486137_executable_python.txt |
Q:
Help retrieving product code from HTML using Beautiful Soup
A webpage has a product code I need to retrive, and it is in the following HTML section:
<table...>
<tr>
<td>
<font size="2">Product Code#</font>
<br>
<font size="1">2342343</font>
</td>
</tr>
</table>
So I guess the best way to do this would be first to reference the html element with the text value 'Product Code#', and then reference the 2nd font tag in the TD.
Ideas?
A:
Assuming soup is your BeautifulSoup instance:
int(''.join(soup("font", size="1")[0](text=True)))
Or, if you need to get multiple product codes:
[int(''.join(font(text=True))) for font in soup("font", size="1")]
A:
My strategy is:
Find text nodes matching the string "Product Code#"
For each such node, get the parent <font> element and find the parent's next sibling <font> element
Insert the contents of the sibling element into a list
The code:
from BeautifulSoup import BeautifulSoup
html = open("products.html").read()
soup = BeautifulSoup(html)
product_codes = [tag.parent.findNextSiblings('font')[0].contents[0]
for tag in
soup.findAll(text='Product Code#')]
A:
You could use this regex (or something similar):
<td>\n\ <font\ size="2">Product\ Code\#</font>\n\ <br>\n\ <font\ size="1">(?<ProductCode>.+?)</font>\n\ </td>
You could probably remove some of the escapes depending on your RegExp engine... I was being cautious.
A:
Don't use regular expressions to parse HTML. I would use the following XPATH for this task:
//TABLE/TR/TD/FONT[@size='1']
Or, if the font size attribute is not guaranteed to be there and equal to 1:
//FONT[text()='Product Code#']/parent::*/FONT[2]
| Help retrieving product code from HTML using Beautiful Soup | A webpage has a product code I need to retrive, and it is in the following HTML section:
<table...>
<tr>
<td>
<font size="2">Product Code#</font>
<br>
<font size="1">2342343</font>
</td>
</tr>
</table>
So I guess the best way to do this would be first to reference the html element with the text value 'Product Code#', and then reference the 2nd font tag in the TD.
Ideas?
| [
"Assuming soup is your BeautifulSoup instance:\nint(''.join(soup(\"font\", size=\"1\")[0](text=True)))\n\nOr, if you need to get multiple product codes:\n[int(''.join(font(text=True))) for font in soup(\"font\", size=\"1\")]\n\n",
"My strategy is:\n\nFind text nodes matching the string \"Product Code#\"\nFor each... | [
1,
1,
0,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003486204_beautifulsoup_python.txt |
Q:
PyQt's Signal / SLOT different classes
can i connect two objects that are in different classes ?
lets say i want button1's clicked() signal to clear line2
class A(QGroupBox):
def __init__(self, parent=None):
super(A, self).__init__(parent)
self.button1= QPushButton('bt1')
self.button1.show()
class B(QGroupBox):
def __init__(self, parent=None):
super(B, self).__init__(parent)
self.line2 = QLineEdit()
self.line2.show()
ob1 = A()
ob2 = B()
A:
Yes, create a method in object B that's tied to a signal in object A. Note how connect is called (this is just an example):
self.connect(self.okButton, QtCore.SIGNAL("clicked()"),
self, QtCore.SLOT("accept()"))
The third argument is the object with the slot, and the fourth the slot name. The sending and receiving objects can definitely be different.
| PyQt's Signal / SLOT different classes | can i connect two objects that are in different classes ?
lets say i want button1's clicked() signal to clear line2
class A(QGroupBox):
def __init__(self, parent=None):
super(A, self).__init__(parent)
self.button1= QPushButton('bt1')
self.button1.show()
class B(QGroupBox):
def __init__(self, parent=None):
super(B, self).__init__(parent)
self.line2 = QLineEdit()
self.line2.show()
ob1 = A()
ob2 = B()
| [
"Yes, create a method in object B that's tied to a signal in object A. Note how connect is called (this is just an example):\n self.connect(self.okButton, QtCore.SIGNAL(\"clicked()\"),\n self, QtCore.SLOT(\"accept()\"))\n\nThe third argument is the object with the slot, and the fourth the slot n... | [
3
] | [] | [] | [
"pyqt",
"python",
"signals",
"slot"
] | stackoverflow_0003486265_pyqt_python_signals_slot.txt |
Q:
Using BeautifulSoup, Can I quickly traverse to a specific parent element?
Say I reference an element inside of a table in a HTML page like this:
someEl = soup.findAll(text = "some text")
I know for sure this element is embedded inside a table, is there a way to find the parent table without having to call .parent so many times?
<table...>
..
..
<tr>....<td><center><font..><b>some text</b></font></center></td>....<tr>
<table>
A:
Check out findParents, it has a similar form to findAll:
soup = BeautifulSoup("<table>...</table>")
for text in soup.findAll(text='some text')
table = text.findParents('table')[0]
# table is your now your most recent `<table>` parent
Here are the docs for findAllPrevious and also findParents.
A:
while someEl.name != "table":
someEl = someEl.parent
# someEl is now the table
| Using BeautifulSoup, Can I quickly traverse to a specific parent element? | Say I reference an element inside of a table in a HTML page like this:
someEl = soup.findAll(text = "some text")
I know for sure this element is embedded inside a table, is there a way to find the parent table without having to call .parent so many times?
<table...>
..
..
<tr>....<td><center><font..><b>some text</b></font></center></td>....<tr>
<table>
| [
"Check out findParents, it has a similar form to findAll:\nsoup = BeautifulSoup(\"<table>...</table>\")\n\nfor text in soup.findAll(text='some text')\n table = text.findParents('table')[0]\n # table is your now your most recent `<table>` parent\n\nHere are the docs for findAllPrevious and also findParents.\n",
... | [
6,
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003486331_beautifulsoup_python.txt |
Q:
Wxpython app exiting abnormally
I have a wxpython app designed using XRC which has a multiline textctrl inside nested boxlayouts.
I'm adding some text(retrieved from the web) to the text control using SetValue(), inside the longtask method from a separate thread using the following code
thread.start_new_thread(self.longtask, ())
The app runs fine the first couple of tries(text gets added correctly) but after around 3 or 4 times it exits with a segmentation fault and following warning.
(python:3341): Gtk-WARNING **: unable to find signal handler for object(GtkEntry:0x9ed89e0) with func(0x837600) and data(0x9e19c08)
Does anyone know why this is happening and how I can fix it? I'm running Python2.6 on Ubuntu 10.2.
Thanks in advance.
A:
Directly calling methods of GUI elements from a different thread is dangerous. Without getting too much into your code, I'd recommend you to consider a robust multi-threaded design. For example, you can use Queue objects to pass data between threads. Alternatively, use wx's events.
Here's a nice article on this issue. And a related SO discussion. Google for more ('wxpython thread')
| Wxpython app exiting abnormally | I have a wxpython app designed using XRC which has a multiline textctrl inside nested boxlayouts.
I'm adding some text(retrieved from the web) to the text control using SetValue(), inside the longtask method from a separate thread using the following code
thread.start_new_thread(self.longtask, ())
The app runs fine the first couple of tries(text gets added correctly) but after around 3 or 4 times it exits with a segmentation fault and following warning.
(python:3341): Gtk-WARNING **: unable to find signal handler for object(GtkEntry:0x9ed89e0) with func(0x837600) and data(0x9e19c08)
Does anyone know why this is happening and how I can fix it? I'm running Python2.6 on Ubuntu 10.2.
Thanks in advance.
| [
"Directly calling methods of GUI elements from a different thread is dangerous. Without getting too much into your code, I'd recommend you to consider a robust multi-threaded design. For example, you can use Queue objects to pass data between threads. Alternatively, use wx's events.\nHere's a nice article on this i... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003486536_python_wxpython.txt |
Q:
How to get an upload progress bar for urllib2?
I currently use the following code to upload one file to a remote server:
import MultipartPostHandler, urllib2, sys
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
params = {"data" : open("foo.bar") }
request=opener.open("http://127.0.0.1/api.php", params)
response = request.read()
This works fine, but for larger files the upload takes some time, and it would be nice to have a callback that allows me to display the upload progress?
I already tried the kodakloader solution, but it does not has a callback for a single file.
Does anyone knows a solution?
A:
Here's a snippet from our python dependency script that Chris Phillips and I worked on @ Cogi (though he did this particular portion of it). Complete script is here.
try:
tmpfilehandle, tmpfilename = tempfile.mkstemp()
with os.fdopen(tmpfilehandle, 'w+b') as tmpfile:
print ' Downloading from %s' % self.alternateUrl
self.progressLine = ''
def showProgress(bytesSoFar, totalBytes):
if self.progressLine:
sys.stdout.write('\b' * len(self.progressLine))
self.progressLine = ' %s/%s (%0.2f%%)' % (bytesSoFar, totalBytes, float(bytesSoFar) / totalBytes * 100)
sys.stdout.write(self.progressLine)
urlfile = urllib2.urlopen(self.alternateUrl)
totalBytes = int(urlfile.info().getheader('Content-Length').strip())
bytesSoFar = 0
showProgress(bytesSoFar, totalBytes)
while True:
readBytes = urlfile.read(1024 * 100)
bytesSoFar += len(readBytes)
if not readBytes:
break
tmpfile.write(readBytes)
showProgress(bytesSoFar, totalBytes)
except HTTPError, e:
sys.stderr.write('Unable to fetch URL: %s\n' % self.alternateUrl)
raise
A:
I think it's impossible to know upload progress with urllib2. I'm looking into using pycurl.
| How to get an upload progress bar for urllib2? | I currently use the following code to upload one file to a remote server:
import MultipartPostHandler, urllib2, sys
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
params = {"data" : open("foo.bar") }
request=opener.open("http://127.0.0.1/api.php", params)
response = request.read()
This works fine, but for larger files the upload takes some time, and it would be nice to have a callback that allows me to display the upload progress?
I already tried the kodakloader solution, but it does not has a callback for a single file.
Does anyone knows a solution?
| [
"Here's a snippet from our python dependency script that Chris Phillips and I worked on @ Cogi (though he did this particular portion of it). Complete script is here. \n try:\n tmpfilehandle, tmpfilename = tempfile.mkstemp()\n with os.fdopen(tmpfilehandle, 'w+b') as tmpfile:\n print ' ... | [
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003241986_python.txt |
Q:
cant install libgmail in python
i'm a newbie in python , and trying to install libgmail ..
this is what i get :
C:\libgmail-0.1.11>setup.py
Traceback (most recent call last):
File "C:\libgmail-0.1.11\setup.py", line 7, in <module>
import libgmail
File "C:\libgmail-0.1.11\libgmail.py", line 96
exec data in {'__builtins__': None}, {'D': lambda x: result.append(x)}
^
SyntaxError: invalid syntax
i think that the libgmail is a bit older then my python version , but dont know how to solve it, please help :-)
thanks in advance
Amitos80
A:
Which version of Python are you using? It's possible it's 3.x which doesn't understand exec as a statement (in Python 3, exec, like print became a function and is no longer a special keyword/statement).
The solution is to either find a port of libgmail to Python 3, or install Python 2.7 for yourself instead.
A:
What version of libgmail are you installing?
I succesfully installed mechanize( on which libgmail was depending) and libgmail by easy_install minute ago.
| cant install libgmail in python | i'm a newbie in python , and trying to install libgmail ..
this is what i get :
C:\libgmail-0.1.11>setup.py
Traceback (most recent call last):
File "C:\libgmail-0.1.11\setup.py", line 7, in <module>
import libgmail
File "C:\libgmail-0.1.11\libgmail.py", line 96
exec data in {'__builtins__': None}, {'D': lambda x: result.append(x)}
^
SyntaxError: invalid syntax
i think that the libgmail is a bit older then my python version , but dont know how to solve it, please help :-)
thanks in advance
Amitos80
| [
"Which version of Python are you using? It's possible it's 3.x which doesn't understand exec as a statement (in Python 3, exec, like print became a function and is no longer a special keyword/statement).\nThe solution is to either find a port of libgmail to Python 3, or install Python 2.7 for yourself instead.\n",
... | [
1,
0
] | [] | [] | [
"libgmail",
"python"
] | stackoverflow_0003486920_libgmail_python.txt |
Q:
cron job and Long process problem
Via django iam launching a thread (via middle ware the moment the first request comes) which continously fetches the twitter public steam and puts it down into the database.Assume the thread name is twitterthread.
I also have have several cron jobs which periodically interacts with other third party api services.
Observed the following Problem:
if i don't launch twitterthread cron jobs are running fine.
Where as if i launch twitterthread cron jobs are not running
Any idea on what can go wrong? and any guidelines on the way to fix it.
A:
I'd advice to avoid launching threads inside the django application. Most of the times you can run the thread as a separate application.
If you deploy the app in a Apache server and you don't control it properly each Apache process will assume that a request is the first one and you could end up with more than one instance of twitterthread.
| cron job and Long process problem | Via django iam launching a thread (via middle ware the moment the first request comes) which continously fetches the twitter public steam and puts it down into the database.Assume the thread name is twitterthread.
I also have have several cron jobs which periodically interacts with other third party api services.
Observed the following Problem:
if i don't launch twitterthread cron jobs are running fine.
Where as if i launch twitterthread cron jobs are not running
Any idea on what can go wrong? and any guidelines on the way to fix it.
| [
"I'd advice to avoid launching threads inside the django application. Most of the times you can run the thread as a separate application.\nIf you deploy the app in a Apache server and you don't control it properly each Apache process will assume that a request is the first one and you could end up with more than on... | [
0
] | [] | [] | [
"cron",
"django",
"python"
] | stackoverflow_0002253714_cron_django_python.txt |
Q:
how to use python to run a google search and print out the results
I wonder if you can help. I want to write a script in python that will run a query on google and output the results of the query as
Thanks
adaptive
A:
This should do what you want:
>>> import twill.commands
>>> import BeautifulSoup
>>>
>>> class browser:
... def __init__(self, url="http://www.google.com",log = None):
... self.a=twill.commands
... self.a.config("readonly_controls_writeable", 1)
... self.b = self.a.get_browser()
... self.b.set_agent_string("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14")
... self.log = log
... self.b.clear_cookies()
... self.url=url
... def googleQuery(self, query="python code"):
... self.b.go(self.url)
... #self.b.showforms()
... f = self.b.get_form("f")
... #print "form is %s" % f
... f["q"] = query
... self.b.clicked(f, "btnG")
... self.b.submit()
... pageContent = self.b.get_html()
... soup=BeautifulSoup.BeautifulSoup(pageContent)
... ths = soup.findAll(attrs={"class" : "l"})
... for a in ths:
... print a
...
>>> t=browser()
>>> t.googleQuery("twill queries")
==> at http://www.google.ie/
Note: submit is using submit button: name="btnG", value="Google Search"
<a href="http://pyparsing.wikispaces.com/WhosUsingPyparsing" class="l" onmousedown="return clk (this.href,'','','res','1','','0CBMQFjAA')">pyparsing - WhosUsingPyparsing</a>
<a href="http://www.mail-archive.com/twill@lists.idyll.org/msg00048.html" class="l" onmousedown="return clk(this.href,'','','res','2','','0CBcQFjAB')">Re: [<em>twill</em>] <em>query</em>: docs, and web site.</a>
<a href="http://www.mail-archive.com/twill@lists.idyll.org/msg00050.html" class="l" onmousedown="return clk(this.href,'','','res','3','','0CBkQFjAC')">Re: [<em>twill</em>] <em>query</em>: docs, and web site.</a>
<a href="http://www.genealogytoday.com/surname/finder.mv?Surname=Twill" class="l" onmousedown="return clk(this.href,'','','res','4','','0CB4QFjAD')"><em>Twill</em> Genealogy and Family Tree Resources - Surname Finder</a>
<a href="http://a706cheap-apparel.hobby-site.com/ladies-cotton-faded-twill-le-chameau-breeks-42" class="l" onmousedown="return clk(this.href,'','','res','5','','0CCEQFjAE')">Ladies Cotton Faded <em>Twill</em> Le Chameau Breeks 42</a>
<a href="http://twill.idyll.org/examples.html" class="l" onmousedown="return clk(this.href,'','','res','6','','0CCMQFjAF')"><em>twill</em> Examples</a>
<a href="http://panjiva.com/Sri-Lankan-Manufacturers-Of/twill+capri" class="l" onmousedown="return clk(this.href,'','','res','7','','0CCcQFjAG')">Sri-Lankan <em>Twill</em> Capri Manufacturers | Sri-Lankan Suppliers of <b>...</b></a>
<a href="http://c586cheap-apparel.dyndns.ws/twill-beige-blazer" class="l" onmousedown="return clk(this.href,'','','res','8','','0CCoQFjAH')"><em>Twill</em> beige blazer</a>
<a href="http://stackoverflow.com/questions/2267537/how-do-you-use-relative-paths-for-twill-tests" class="l" onmousedown="return clk(this.href,'','','res','9','','0CCwQFjAI')">How do you use Relative Paths for <em>Twill</em> tests? - Stack Overflow</a>
<a href="http://mytextilenotes.blogspot.com/2010/01/introduction-to-twill-weave.html" class="l" onmousedown="return clk(this.href,'','','res','10','','0CC8QFjAJ')">My Textile Notes: Introduction to <em>Twill</em> Weave</a>
A:
This example should help you.
| how to use python to run a google search and print out the results | I wonder if you can help. I want to write a script in python that will run a query on google and output the results of the query as
Thanks
adaptive
| [
"This should do what you want:\n>>> import twill.commands\n>>> import BeautifulSoup\n>>> \n>>> class browser:\n... def __init__(self, url=\"http://www.google.com\",log = None):\n... self.a=twill.commands\n... self.a.config(\"readonly_controls_writeable\", 1)\n... self.b = self.a.get_browser()\n... | [
3,
2
] | [] | [] | [
"python",
"web"
] | stackoverflow_0003487395_python_web.txt |
Q:
cant send SMS vla libgmail - python
i'm new to python , and trying to write a script in order to send SMS's ,
after quick googling i found this lib: libgmail, and successfully installed it ,
this is the code i use to send SMS:
!/usr/bin/env python
import libgmail
ga = libgmail.GmailAccount("username@gmail.com", "password")
myCellEmail = "phonenumber@message.carrier.end"
ga.login()
msg=libgmail.GmailComposedMessage(myCellEmail, "", "Hello World! From python-libgmail!")
ga.sendMessage(msg)
i get the following error when trying to run it:
Traceback (most recent call last):
File "C:\Users\Amit\Desktop\SMS\sms.py", line 14, in
ga.login()
File "C:\Python27\lib\site-packages\libgmail.py", line 305, in login
pageData = self._retrievePage(req)
File "C:\Python27\lib\site-packages\libgmail.py", line 340, in _retrievePage
req = ClientCookie.Request(urlOrRequest)
File "build\bdist.win32\egg\mechanize_request.py", line 31, in init
File "build\bdist.win32\egg\mechanize_rfc3986.py", line 62, in is_clean_uri
TypeError: expected string or buffer
if you have any ideas , please share ..
thanks a lot
amitos80
A:
As far as I know libgmail is not compatible with the current Gmail interface. If I am not mistaken libgmail is not actively maintained either. You might want to look at alternative options.
| cant send SMS vla libgmail - python | i'm new to python , and trying to write a script in order to send SMS's ,
after quick googling i found this lib: libgmail, and successfully installed it ,
this is the code i use to send SMS:
!/usr/bin/env python
import libgmail
ga = libgmail.GmailAccount("username@gmail.com", "password")
myCellEmail = "phonenumber@message.carrier.end"
ga.login()
msg=libgmail.GmailComposedMessage(myCellEmail, "", "Hello World! From python-libgmail!")
ga.sendMessage(msg)
i get the following error when trying to run it:
Traceback (most recent call last):
File "C:\Users\Amit\Desktop\SMS\sms.py", line 14, in
ga.login()
File "C:\Python27\lib\site-packages\libgmail.py", line 305, in login
pageData = self._retrievePage(req)
File "C:\Python27\lib\site-packages\libgmail.py", line 340, in _retrievePage
req = ClientCookie.Request(urlOrRequest)
File "build\bdist.win32\egg\mechanize_request.py", line 31, in init
File "build\bdist.win32\egg\mechanize_rfc3986.py", line 62, in is_clean_uri
TypeError: expected string or buffer
if you have any ideas , please share ..
thanks a lot
amitos80
| [
"As far as I know libgmail is not compatible with the current Gmail interface. If I am not mistaken libgmail is not actively maintained either. You might want to look at alternative options. \n"
] | [
0
] | [] | [] | [
"libgmail",
"python",
"scripting",
"sms"
] | stackoverflow_0003487447_libgmail_python_scripting_sms.txt |
Q:
django Queryset with year(date) = '2010'
I'm trying to build this query
select * from m_orders where year(order_date) = '2010'
the field order_date is a DateTime field. I just don't want to use raw sql queries here. Is it even possible to use e.g. MySQL functions in django quersets?
A:
You can achieve this without using raw SQL. Use the built in __ mechanism instead (see the documentation for more details). Something like this:
MyOrder.objects.filter(order_date__year = 2010)
A:
you can use django's builtin query API for this. no need for any vendor specific code or raw SQL.
it would probably look something like this:
Orders.objects.filter(order_date__year=2010)
http://docs.djangoproject.com/en/dev/topics/db/queries/
| django Queryset with year(date) = '2010' | I'm trying to build this query
select * from m_orders where year(order_date) = '2010'
the field order_date is a DateTime field. I just don't want to use raw sql queries here. Is it even possible to use e.g. MySQL functions in django quersets?
| [
"You can achieve this without using raw SQL. Use the built in __ mechanism instead (see the documentation for more details). Something like this:\nMyOrder.objects.filter(order_date__year = 2010)\n\n",
"you can use django's builtin query API for this. no need for any vendor specific code or raw SQL.\nit would prob... | [
26,
6
] | [] | [] | [
"django",
"django_queryset",
"python",
"sql"
] | stackoverflow_0003487484_django_django_queryset_python_sql.txt |
Q:
Python .format - error
I'm trying to get the following to work in a Python interpreter, however it gives me an error and I cannot seem to find where my mistake is? (I'm a python newbie)
>>> print 'THe value of PI is approx {}.'.format(math.pi)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'format'
Any ideas?
A:
You may use Python version < 2.6, version >= 2.6 support {0}, version >= 2.7 support {} format.
A:
You're using a too old version of python that does not support this string formatting method. On Python 2.6 this is the result (with a small correction):
>>> print 'THe value of PI is approx {0}.'.format(math.pi)
THe value of PI is approx 3.14159265359.
This method is the new way of string formatting (PEP 3101) and is supposed to replace the old way (with the %). I'm still used to the old way but in the long run I'll probably switch to the new way.
| Python .format - error | I'm trying to get the following to work in a Python interpreter, however it gives me an error and I cannot seem to find where my mistake is? (I'm a python newbie)
>>> print 'THe value of PI is approx {}.'.format(math.pi)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'format'
Any ideas?
| [
"You may use Python version < 2.6, version >= 2.6 support {0}, version >= 2.7 support {} format.\n",
"You're using a too old version of python that does not support this string formatting method. On Python 2.6 this is the result (with a small correction):\n>>> print 'THe value of PI is approx {0}.'.format(math.pi... | [
3,
1
] | [
"This works: \n>>> print \"The value of PI is approx {'%s'}.\" % format(math.pi)\nThe value of PI is approx {'3.14159265359'}.\n\nSo does this: \n>>> print \"The value of PI is approx '%f'\" % math.pi\nThe value of PI is approx '3.141593'\n\n"
] | [
-1
] | [
"format",
"python"
] | stackoverflow_0003487770_format_python.txt |
Q:
How to plot data against specific dates on the x-axis using matplotlib
I have a dataset consisting of date-value pairs. I want to plot them in a bar graph with the specific dates in the x-axis.
My problem is that matplotlib distributes the xticks over the entire date range; and also plots the data using points.
The dates are all datetime objects. Here's a sample of the dataset:
data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123),
(DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678),
(DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987),
(DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)]
Here is a runnable code sample using pyplot
import datetime as DT
from matplotlib import pyplot as plt
data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123),
(DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678),
(DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987),
(DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)]
x = [date for (date, value) in data]
y = [value for (date, value) in data]
fig = plt.figure()
graph = fig.add_subplot(111)
graph.plot_date(x,y)
plt.show()
QUESTION SUMMARY:
My situation is more like I have an Axes instance ready (referenced by graph in the code above) and I want to do the following:
Make the xticks correspond to the exact date values. I have heard of matplotlib.dates.DateLocator but I have no idea how create one and then associate it with a specific Axes object.
Get tighter control over the type of graph being used (bar, line, points, etc.)
A:
What you're doing is simple enough that it's easiest to just using plot, rather than plot_date. plot_date is great for more complex cases, but setting up what you need can be easily accomplished without it.
e.g., Based on your example above:
import datetime as DT
from matplotlib import pyplot as plt
from matplotlib.dates import date2num
data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123),
(DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678),
(DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987),
(DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)]
x = [date2num(date) for (date, value) in data]
y = [value for (date, value) in data]
fig = plt.figure()
graph = fig.add_subplot(111)
# Plot the data as a red line with round markers
graph.plot(x,y,'r-o')
# Set the xtick locations to correspond to just the dates you entered.
graph.set_xticks(x)
# Set the xtick labels to correspond to just the dates you entered.
graph.set_xticklabels(
[date.strftime("%Y-%m-%d") for (date, value) in data]
)
plt.show()
If you'd prefer a bar plot, just use plt.bar(). To understand how to set the line and marker styles, see plt.plot()
Plot with date labels at marker locations http://www.geology.wisc.edu/~jkington/matplotlib_date_labels.png
| How to plot data against specific dates on the x-axis using matplotlib | I have a dataset consisting of date-value pairs. I want to plot them in a bar graph with the specific dates in the x-axis.
My problem is that matplotlib distributes the xticks over the entire date range; and also plots the data using points.
The dates are all datetime objects. Here's a sample of the dataset:
data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123),
(DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678),
(DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987),
(DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)]
Here is a runnable code sample using pyplot
import datetime as DT
from matplotlib import pyplot as plt
data = [(DT.datetime.strptime('2010-02-05', "%Y-%m-%d"), 123),
(DT.datetime.strptime('2010-02-19', "%Y-%m-%d"), 678),
(DT.datetime.strptime('2010-03-05', "%Y-%m-%d"), 987),
(DT.datetime.strptime('2010-03-19', "%Y-%m-%d"), 345)]
x = [date for (date, value) in data]
y = [value for (date, value) in data]
fig = plt.figure()
graph = fig.add_subplot(111)
graph.plot_date(x,y)
plt.show()
QUESTION SUMMARY:
My situation is more like I have an Axes instance ready (referenced by graph in the code above) and I want to do the following:
Make the xticks correspond to the exact date values. I have heard of matplotlib.dates.DateLocator but I have no idea how create one and then associate it with a specific Axes object.
Get tighter control over the type of graph being used (bar, line, points, etc.)
| [
"What you're doing is simple enough that it's easiest to just using plot, rather than plot_date. plot_date is great for more complex cases, but setting up what you need can be easily accomplished without it.\ne.g., Based on your example above:\nimport datetime as DT\nfrom matplotlib import pyplot as plt\nfrom matpl... | [
31
] | [] | [] | [
"date",
"matplotlib",
"python"
] | stackoverflow_0003486121_date_matplotlib_python.txt |
Q:
Grab product code from a url, do I need regex for this?
A url looks like:
http://www.example.com/cgi-bin/blahblah?&PC=abd23423&uy=020
I need to extract the value: abc23423
I tried this regex but its not working:
rx = re.compile(r'PC=(\w*)&uy=')
I then I did:
pc = rx.search(url).groups()
but I get an error:
attribute error: nonetype object has no attribute groups.
A:
Try urlparse.
A:
Update
Sheesh. What was I thinking?
import urlparse
u = 'http://www.example.com/cgi-bin/blahblah?&PC=abd23423&uy=020'
query = urlparse.urlparse(u).query
urlparse.parse_qs(query) # {'PC': ['abd23423'], 'uy': ['020']}
Original Answer
This code snippet worked for me. Take a look:
import urlparse, re
u = 'http://www.example.com/cgi-bin/blahblah?&PC=abd23423&uy=020'
query = urlparse.urlparse(u).query
pattern = re.compile('PC=(\w*)&uy')
pattern.findall(query) # ['abd23423']
A:
lol = "http://www.example.com/cgi-bin/blahblah?&PC=abd23423&uy=020"
s = re.compile("&PC=(\w+)&uy=")
g = s.search(lol)
g.groups()
('abd23423',)
This seems to work for me.
| Grab product code from a url, do I need regex for this? | A url looks like:
http://www.example.com/cgi-bin/blahblah?&PC=abd23423&uy=020
I need to extract the value: abc23423
I tried this regex but its not working:
rx = re.compile(r'PC=(\w*)&uy=')
I then I did:
pc = rx.search(url).groups()
but I get an error:
attribute error: nonetype object has no attribute groups.
| [
"Try urlparse.\n",
"Update\nSheesh. What was I thinking?\nimport urlparse\nu = 'http://www.example.com/cgi-bin/blahblah?&PC=abd23423&uy=020'\nquery = urlparse.urlparse(u).query\nurlparse.parse_qs(query) # {'PC': ['abd23423'], 'uy': ['020']}\n\nOriginal Answer\nThis code snippet worked for me. Take a look:\nimport... | [
4,
2,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003486313_python_regex.txt |
Q:
What tricks do you use to avoid being tripped up by python whitespace syntax?
I'm an experienced programmer, but still a little green at python. I just got caught by an error in indentation, which cost me a significant amount of debugging time. I was wondering what experienced python programmers do to avoid creating such problems in the first place.
Here's the code (Part of a much larger program) :
class Wizvar():
def select(self):
self.selected = True
def unselect(self):
self.selected = False
value = None
The problem is that 'value = None' should be outdented one level. As it is, the variable gets clobbered every time the unselect method is called, rather than once only. I stared at this many times without seeing what was wrong.
A:
Put all the class attributes (e.g. value) up at the top, right under the class Wizvar declaration (below the doc string, but above all method definitions). If you always place class attributes in the same place, you may not run into this particular error as often.
Notice that if you follow the above convention and had written:
class Wizvar():
value = None
def select(self):
self.selected = True
def unselect(self):
self.selected = False
then Python would have raised an IndentationError:
% test.py
File "/home/unutbu/pybin/test.py", line 7
def select(self):
^
IndentationError: unindent does not match any outer indentation level
A:
In general: a lot of unit testing. Code reviews also help a lot.
This specific error seems like an easy one to identify since if value was supposed to be outdented once it would have been a class variable, proper unit testing would have spotted that it isn't in this case.
Tools like PyDev do a good job at finding some other common mistakes so you might want to consider those.
A:
I don't have such problems ;) At least I have them less often than a superfluous, missing or misplaces brace or the classic:
if (foo)
bar();
baz();
in language that use braces.
That being said, certain coding styles help. For example, I always list class variables at the top of the class body, so if I accidentally the indentation, I'll get an IndentationError instead of creating an unused local variable. By the way, I've always seen it like this. Consistent indentation (I'm with PEP 8 and use 4 spaces) also helps, some people use only one space for some blocks - that's really easy to overlook.
Static code analysis (like PyLint) may point such errors out, but I don't have much experience with these. As I wrote, it just works most of the time.
| What tricks do you use to avoid being tripped up by python whitespace syntax? | I'm an experienced programmer, but still a little green at python. I just got caught by an error in indentation, which cost me a significant amount of debugging time. I was wondering what experienced python programmers do to avoid creating such problems in the first place.
Here's the code (Part of a much larger program) :
class Wizvar():
def select(self):
self.selected = True
def unselect(self):
self.selected = False
value = None
The problem is that 'value = None' should be outdented one level. As it is, the variable gets clobbered every time the unselect method is called, rather than once only. I stared at this many times without seeing what was wrong.
| [
"Put all the class attributes (e.g. value) up at the top, right under the class Wizvar declaration (below the doc string, but above all method definitions). If you always place class attributes in the same place, you may not run into this particular error as often.\nNotice that if you follow the above convention an... | [
8,
1,
1
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0003488231_python_syntax.txt |
Q:
Python ctypes - dll function accepting structures crashes
I have to access a POS terminal under ms windows xp. I am using python 2.7.
The crucial function in the DLL I load that does the payment accepts two pointer to structures, but it crashes returning 1 (Communication error) but without further messages.
Please note that when the payment function is called, not all the elements of POSData structure receive a value. Other function I tried (GetVersion) does work.
Here specifications and my code:
typedef struct
{
char IPAddress[16]; //xxx.xxx.xxx.xxx
int Port;
} TETHParameters;
typedef struct
{
char TerminalId[8+1];
char AcquirerId[11+1];
char TransactionType[3+1];
char TransactionResult[2+1];
char KODescription[24+1];
char CardType[1+1];
char STAN[6+1];
char PAN[19+1];
char AuthorizationCode[6+1];
char OperationNumber[6+1];
char DataTrs[7+1];
} TPOSData;
typedef struct
{
char Amount[8+1];
char ECRId[8+1];
char PaymentType[1+1];
char TerminalId[8+1];
} TECRData;
__declspec(dllexport) void IAE17_GetVersion(char *Version);
__declspec(dllexport) void IAE17_InitEth(TETHParameters *ETHParameters);
__declspec(dllexport) void IAE17_Free(void);
__declspec(dllexport) int IAE17_Payment(TECRData *ECRData, TPOSData *POSData);
from ctypes import *
#da python 3.x sara' configparser
import ConfigParser
import logging
from time import localtime, strftime
#STRUTTURE DATI
class TETHParameters(Structure):
_fields_ = [("IPAddress" , c_char_p), ("Port" , c_int )]
class TECRData(Structure):
_fields_ = [("Amount" , c_char_p),
("ECRId", c_char_p),
("PaymentType", c_char_p),
("TerminalId", c_char_p),
("Contract", c_char_p),
("PreauthorizationCode", c_char_p),
("STAN", c_char_p),
("Ticket2Ecr", c_char_p)]
class TPOSData(Structure):
_fields_ = [
("TerminalId" , c_char_p),
("AcquirerId" , c_char_p),
("TransactionType" , c_char_p),
("TransactionResult" , c_char_p),
("KODescription" , c_char_p),
("CardType" , c_char_p),
("STAN" , c_char_p),
("POSBalance" , c_char_p),
("BankBalance" , c_char_p),
("PAN" , c_char_p),
("AuthorizationCode" , c_char_p),
("OperationNumber" , c_char_p),
("AmountAuth" , c_char_p),
("PreauthorizationCode" , c_char_p),
("ActionCode" , c_char_p),
("DataTrs" , c_char_p),
("AmountEcho" , c_char_p),
("Ticket" , c_char_p)
]
ECRData = TECRData( ECRId = c_char_p( '012345678' ),
Amount = c_char_p( '00000000') ,
TerminalID = c_char_p( '01234567' ),
PaymentType = c_char_p ("0")
)
POSData = TPOSData( KODescription = c_char_p(' '),
TerminalId = c_char_p(' '),
AcquirerId = c_char_p(' '),
TransactionType = c_char_p(' '),
TransactionResult = c_char_p(' '),
CardType = c_char_p(' '),
STAN = c_char_p(' '),
PAN = c_char_p(' '),
AuthorizationCode = c_char_p(' '),
OperationNumber = c_char_p(' '),
DataTrs = c_char_p(' ')
)
ETHParameters = TETHParameters( IPAddress = c_char_p( '192.168.127.190' ) , Port = c_int(45119))
iae17 = windll.LoadLibrary('iae17')
iae17.IAE17_InitEth( byref( ETHParameters) )
result = iae17.IAE17_Payment( byref(ECRData), byref(POSData))
print result
A:
c_char_p is a direct translation of a C's char *. So, it seems to me that while your C structure is
typedef struct
{
char TerminalId[8+1];
char AcquirerId[11+1];
char TransactionType[3+1];
&c
the allegedly-corresponding one you're making in ctypes is, instead, equivalent to
typedef struct
{
char* TerminalId;
char* AcquirerId;
char* TransactionType;
&c
which is of course a drastically different thing. Why are you using "pointers" instead of ctypes' arrays?
| Python ctypes - dll function accepting structures crashes | I have to access a POS terminal under ms windows xp. I am using python 2.7.
The crucial function in the DLL I load that does the payment accepts two pointer to structures, but it crashes returning 1 (Communication error) but without further messages.
Please note that when the payment function is called, not all the elements of POSData structure receive a value. Other function I tried (GetVersion) does work.
Here specifications and my code:
typedef struct
{
char IPAddress[16]; //xxx.xxx.xxx.xxx
int Port;
} TETHParameters;
typedef struct
{
char TerminalId[8+1];
char AcquirerId[11+1];
char TransactionType[3+1];
char TransactionResult[2+1];
char KODescription[24+1];
char CardType[1+1];
char STAN[6+1];
char PAN[19+1];
char AuthorizationCode[6+1];
char OperationNumber[6+1];
char DataTrs[7+1];
} TPOSData;
typedef struct
{
char Amount[8+1];
char ECRId[8+1];
char PaymentType[1+1];
char TerminalId[8+1];
} TECRData;
__declspec(dllexport) void IAE17_GetVersion(char *Version);
__declspec(dllexport) void IAE17_InitEth(TETHParameters *ETHParameters);
__declspec(dllexport) void IAE17_Free(void);
__declspec(dllexport) int IAE17_Payment(TECRData *ECRData, TPOSData *POSData);
from ctypes import *
#da python 3.x sara' configparser
import ConfigParser
import logging
from time import localtime, strftime
#STRUTTURE DATI
class TETHParameters(Structure):
_fields_ = [("IPAddress" , c_char_p), ("Port" , c_int )]
class TECRData(Structure):
_fields_ = [("Amount" , c_char_p),
("ECRId", c_char_p),
("PaymentType", c_char_p),
("TerminalId", c_char_p),
("Contract", c_char_p),
("PreauthorizationCode", c_char_p),
("STAN", c_char_p),
("Ticket2Ecr", c_char_p)]
class TPOSData(Structure):
_fields_ = [
("TerminalId" , c_char_p),
("AcquirerId" , c_char_p),
("TransactionType" , c_char_p),
("TransactionResult" , c_char_p),
("KODescription" , c_char_p),
("CardType" , c_char_p),
("STAN" , c_char_p),
("POSBalance" , c_char_p),
("BankBalance" , c_char_p),
("PAN" , c_char_p),
("AuthorizationCode" , c_char_p),
("OperationNumber" , c_char_p),
("AmountAuth" , c_char_p),
("PreauthorizationCode" , c_char_p),
("ActionCode" , c_char_p),
("DataTrs" , c_char_p),
("AmountEcho" , c_char_p),
("Ticket" , c_char_p)
]
ECRData = TECRData( ECRId = c_char_p( '012345678' ),
Amount = c_char_p( '00000000') ,
TerminalID = c_char_p( '01234567' ),
PaymentType = c_char_p ("0")
)
POSData = TPOSData( KODescription = c_char_p(' '),
TerminalId = c_char_p(' '),
AcquirerId = c_char_p(' '),
TransactionType = c_char_p(' '),
TransactionResult = c_char_p(' '),
CardType = c_char_p(' '),
STAN = c_char_p(' '),
PAN = c_char_p(' '),
AuthorizationCode = c_char_p(' '),
OperationNumber = c_char_p(' '),
DataTrs = c_char_p(' ')
)
ETHParameters = TETHParameters( IPAddress = c_char_p( '192.168.127.190' ) , Port = c_int(45119))
iae17 = windll.LoadLibrary('iae17')
iae17.IAE17_InitEth( byref( ETHParameters) )
result = iae17.IAE17_Payment( byref(ECRData), byref(POSData))
print result
| [
"c_char_p is a direct translation of a C's char *. So, it seems to me that while your C structure is\ntypedef struct\n{\n char TerminalId[8+1];\n char AcquirerId[11+1];\n char TransactionType[3+1];\n\n&c\n\nthe allegedly-corresponding one you're making in ctypes is, instead, equivalent to\ntypedef struct\n{\n ... | [
5
] | [] | [] | [
"ctypes",
"pointers",
"python",
"structure"
] | stackoverflow_0003488173_ctypes_pointers_python_structure.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.