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:
Using DictWriter to write a subset of a dictionary's keys
I wrote a function that serializes a list of dictionaries as a CSV file using the csv module, with code like this:
data = csv.DictWriter(out_f, fieldnames)
data.writerows(dictrows)
However, I sometimes want to write out to a file only a subset of each dictionary's keys. If I pass as fieldnames a subset of the keys that each dictionary has, I get the error:
"dict contains fields not in fieldnames"
How can I make it so that DictRows will write just a subset of the fields I specify to CSV, ignoring those fields that are in the dictionary but not in fieldnames?
A:
Simplest and most direct approach is to pass extrasaction='ignore' when you initialize your DictWriter instance, as documented here:
If the dictionary passed to the
writerow() method contains a key not
found in fieldnames, the optional
extrasaction parameter indicates what
action to take. If it is set to
'raise' a ValueError is raised. If it
is set to 'ignore', extra values in
the dictionary are ignored.
It also works on writerows, which, internally, just calls writerow repeatedly.
A:
Changes to your code:
Forget Dictwriter, use ordinary writer.
Then loop over your list of dicts:
for d in dictrows:
ordinary_writer.writerow([d[fieldname] for fieldname in fieldnames])
Use d.get(fieldname, "") instead of d[fieldname] if you don't want an exception if there is no entry in d for a fieldname.
Note to anonymous downvoters: This is doing what Alex's solution is doing under the hood (see Lib/csv.py) and doing it a bit better ... csv.py calls a function to get each row in a list, and the guts of that function is
return [rowdict.get(key, self.restval) for key in self.fieldnames]
| Using DictWriter to write a subset of a dictionary's keys | I wrote a function that serializes a list of dictionaries as a CSV file using the csv module, with code like this:
data = csv.DictWriter(out_f, fieldnames)
data.writerows(dictrows)
However, I sometimes want to write out to a file only a subset of each dictionary's keys. If I pass as fieldnames a subset of the keys that each dictionary has, I get the error:
"dict contains fields not in fieldnames"
How can I make it so that DictRows will write just a subset of the fields I specify to CSV, ignoring those fields that are in the dictionary but not in fieldnames?
| [
"Simplest and most direct approach is to pass extrasaction='ignore' when you initialize your DictWriter instance, as documented here:\n\nIf the dictionary passed to the\n writerow() method contains a key not\n found in fieldnames, the optional\n extrasaction parameter indicates what\n action to take. If it is s... | [
52,
0
] | [] | [] | [
"csv",
"dictionary",
"python"
] | stackoverflow_0003208874_csv_dictionary_python.txt |
Q:
How do I do a Rails style before_filter with Google App Engine?
The app is setup as a basic WSGI application. I'm just trying to call a function before the requestHandler is run.
I would like something very much like the way before_filter works in Rails.
Thanks.
A:
I would use decorators, it's not exactly the same as before_filter in rails, but maybe good enough for you:
def before_filter(fn):
def inner_function(self):
# do stuff before
return fn(self)
return inner_function
class MainPage(webapp.RequestHandler):
@before_filter
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Hello, webapp World!')
A:
You can install your "before" as WSGI middleware -- App Engine uses WSGI, like just about every web framework and server in Python these days. Here's an example -- it's doing things after the handler runs, but it's even easier to do them before... in any case, your middleware "wraps" the WSGI application that's the actual app;-), so of course you can do things before, after, or instead;-).
For more on WSGI, see here.
| How do I do a Rails style before_filter with Google App Engine? | The app is setup as a basic WSGI application. I'm just trying to call a function before the requestHandler is run.
I would like something very much like the way before_filter works in Rails.
Thanks.
| [
"I would use decorators, it's not exactly the same as before_filter in rails, but maybe good enough for you:\ndef before_filter(fn):\n def inner_function(self):\n # do stuff before\n return fn(self)\n return inner_function\n\nclass MainPage(webapp.RequestHandler):\n\n @before_filter\n def ... | [
1,
1
] | [] | [] | [
"django_middleware",
"google_app_engine",
"python",
"wsgi"
] | stackoverflow_0003208869_django_middleware_google_app_engine_python_wsgi.txt |
Q:
binding generic c++ libraries to python with boost.python
I would like to know what's the process, when binding C++ libraries that are written with in a generic way.
Is there a posibility of binding a template class, or you can only bind only a template generated class ?
A:
You can only bind a generated class. However, it is possible to write a template function to export your class, and call this function for each concrete types you want to export. For example:
template<class T>
struct foo {};
template<class T>
void export_foo(std::string name) {
boost::python::class_<foo<T>>(name.c_str());
}
BOOST_PYTHON_MODULE(foo)
{
export_foo<int>("foo_int");
export_foo<std::string>("foo_string");
//...
}
If it is not enough, you can also dive into meta programming (with Boost.MPL for example), to create typelists, and automatically call export_foo for all these types.
| binding generic c++ libraries to python with boost.python | I would like to know what's the process, when binding C++ libraries that are written with in a generic way.
Is there a posibility of binding a template class, or you can only bind only a template generated class ?
| [
"You can only bind a generated class. However, it is possible to write a template function to export your class, and call this function for each concrete types you want to export. For example:\ntemplate<class T>\nstruct foo {};\n\ntemplate<class T>\nvoid export_foo(std::string name) { \n boost::python::class_<fo... | [
3
] | [] | [] | [
"boost",
"c++",
"generics",
"python",
"templates"
] | stackoverflow_0003205561_boost_c++_generics_python_templates.txt |
Q:
Odd Behavior when Connecting to my Program
I'm using Twisted to implement a server, of sorts. When I test it, the first line it receives is always strange:
Starting Server...
New connection from 192.168.1.140
192.168.1.140: ÿûÿû ÿûÿû'ÿýÿûÿý\NAME Blurr
192.168.1.140: \NAME Blurr
(for both inputs I sent \NAME Blurr.)
This is the code that prints the input:
def lineReceived(self, line):
print "{0}: {1}".format(self.name, line)
I'm connecting via Putty through Telnet to a remote host. Is this a telnet protocol I'm missing, or what? When I use Unix's telnet program and connect locally, the first line is fine.
A:
You can find an explanation of the "ÿûÿû mystery" here. Short form: telnet is not a simple protocol, and what you're seeing is a trace of a telnet negotiation (trying to) occur with a server that doesn't speak "telnettese";-). Good guess about "is this a telnet protocol I'm missing";-)
The RFCs involved in defining the telnet protocol are linked from this page, if you want to debug further. I'm no putty expert so I don't know how to tell putty to avoid this negotiation (and act like the good old simple Unix telnet client;-).
A:
It was indeed a telnet protocol I was missing. Connecting as Raw instead Telnet solved the problem.
| Odd Behavior when Connecting to my Program | I'm using Twisted to implement a server, of sorts. When I test it, the first line it receives is always strange:
Starting Server...
New connection from 192.168.1.140
192.168.1.140: ÿûÿû ÿûÿû'ÿýÿûÿý\NAME Blurr
192.168.1.140: \NAME Blurr
(for both inputs I sent \NAME Blurr.)
This is the code that prints the input:
def lineReceived(self, line):
print "{0}: {1}".format(self.name, line)
I'm connecting via Putty through Telnet to a remote host. Is this a telnet protocol I'm missing, or what? When I use Unix's telnet program and connect locally, the first line is fine.
| [
"You can find an explanation of the \"ÿûÿû mystery\" here. Short form: telnet is not a simple protocol, and what you're seeing is a trace of a telnet negotiation (trying to) occur with a server that doesn't speak \"telnettese\";-). Good guess about \"is this a telnet protocol I'm missing\";-)\nThe RFCs involved i... | [
5,
1
] | [] | [] | [
"networking",
"putty",
"python",
"telnet",
"twisted"
] | stackoverflow_0003208993_networking_putty_python_telnet_twisted.txt |
Q:
Detect Caps Lock in Python curses
For such a basic question, I'm surprised I couldn't find anything by searching...
Anyways, I made a curses app in Python that assists in solving puzzles of a certain DSiWare game. With it, you can take a puzzle and inspect the components of it individually. The keys qweasdzx are used to paint tiles (the keys are arranged in some sort of palette). Pressing one of these keys while holding Shift highlights tiles with that color. I couldn't ask for a more natural control scheme.
So it's a shame that, once again, Shift is giving me issues (last time I had issues with Shift, I earned a Tumbleweed badge). Though this time, the problem is more or less Caps Lock, which completely screws up my program by reversing the functions.
How can I detect the state of Caps Lock in Python with curses?
EDIT: If you're going to suggest using a separate module, I probably should remind you that curses - and therefore my program - is in UNIX territory.
A:
I found a solution on my own:
Since curses is completely unaware of the Caps Lock setting according to ΤΖΩΤΖΙΟΥ, I tried an alternative solution. Specifically, I looked up how to check Caps Lock in a BASH script. What I found was this:
Linux only. Requires X Window System.
$ xset q | grep LED
> auto repeat: on key click percent: 0 LED mask: 00000000
The last 0 in that output (the 66th character in the string) is the Caps Lock flag. 1 if it's on, 0 if it's off.
Python can run UNIX system commands with the Linux-only commands module. commands does not appear to interfere with curses.
>>> import commands
>>> # Caps Lock is off.
>>> commands.getoutput("xset q | grep LED")[65]
'0'
>>> # Setting Caps Lock on now.
>>> commands.getoutput("xset q | grep LED")[65]
'1'
This works fine for me; this is a personal-use script, and it's not like my program wasn't already Linux-exclusive. But I do hope somebody has another, more Windows-compatible solution.
I'm going to accept this self-answer for now, but if somebody else can come up with a better working solution, I'd like to see it.
A:
The short answer: you can't.
A longer answer:
curses was created as a terminfo-based library to ease the creation of character-based UIs independent of the terminal used (for terminal in 'vt220', 'wyse100', …).
These terminals connected through a serial line and the communication to-and-fro the host were through either plain text (input by the user or output by the host) or special sequences ("escape" sequences; input by the user if special keys were pressed, like ↑ or Prev, or output by the host if special operations like cursor positioning or screen clearing was requested).
I have no knowledge of any dumb terminal sending a special sequence whenever the Caps Lock key was depressed, or the host querying for the Caps Lock status; locking capitals was part of the job of the terminal, and the host had no need for any knowledge. This is similar to the reason you can't have a curses program act when the Control key is depressed on its own.
Everything about curses relates to terminfo capabilities; there isn't any related capability for what you ask.
| Detect Caps Lock in Python curses | For such a basic question, I'm surprised I couldn't find anything by searching...
Anyways, I made a curses app in Python that assists in solving puzzles of a certain DSiWare game. With it, you can take a puzzle and inspect the components of it individually. The keys qweasdzx are used to paint tiles (the keys are arranged in some sort of palette). Pressing one of these keys while holding Shift highlights tiles with that color. I couldn't ask for a more natural control scheme.
So it's a shame that, once again, Shift is giving me issues (last time I had issues with Shift, I earned a Tumbleweed badge). Though this time, the problem is more or less Caps Lock, which completely screws up my program by reversing the functions.
How can I detect the state of Caps Lock in Python with curses?
EDIT: If you're going to suggest using a separate module, I probably should remind you that curses - and therefore my program - is in UNIX territory.
| [
"I found a solution on my own:\nSince curses is completely unaware of the Caps Lock setting according to ΤΖΩΤΖΙΟΥ, I tried an alternative solution. Specifically, I looked up how to check Caps Lock in a BASH script. What I found was this:\nLinux only. Requires X Window System.\n$ xset q | grep LED\n> auto repeat:... | [
7,
3
] | [] | [] | [
"capslock",
"curses",
"python"
] | stackoverflow_0003207032_capslock_curses_python.txt |
Q:
Is it possible to use readline instead of libedit in Python's raw_input under OS X?
From the readline module documentation, it mentions:
On MacOS X the readline module can be implemented using the libedit library instead of GNU readline. The configuration file for libedit is different from that of GNU readline.
Is it possible to use the readline library in /usr/lib/libreadline.dylib for example, or even compiled with MacPorts or Homebrew?
A:
$ sudo easy_install readline
A:
It is possible to use GNU readline from MacPorts or elsewhere when building Python by specifying the additional library and include files when invoking the configure script. See the python installer build script in the Python source tree (Mac/BuildScript/build-installer.py) for an example. It builds a local copy of GNU readline when building for targets of 10.4 or earlier.
Keep in mind that on current OS X releases, /usr/lib/libreadline.dylib is merely a symlink to libedit; AFAIK, Apple does not ship GNU readline as a library in OS X:
$ ls -l /usr/lib/libreadline.dylib
lrwxr-xr-x 1 root wheel 15 Sep 5 2009 /usr/lib/libreadline.dylib@ -> libedit.2.dylib
| Is it possible to use readline instead of libedit in Python's raw_input under OS X? | From the readline module documentation, it mentions:
On MacOS X the readline module can be implemented using the libedit library instead of GNU readline. The configuration file for libedit is different from that of GNU readline.
Is it possible to use the readline library in /usr/lib/libreadline.dylib for example, or even compiled with MacPorts or Homebrew?
| [
"$ sudo easy_install readline\n\n",
"It is possible to use GNU readline from MacPorts or elsewhere when building Python by specifying the additional library and include files when invoking the configure script. See the python installer build script in the Python source tree (Mac/BuildScript/build-installer.py) fo... | [
3,
2
] | [] | [] | [
"macos",
"python",
"readline"
] | stackoverflow_0003138574_macos_python_readline.txt |
Q:
Restrictons of Python compared to Ruby: lambda's
I was going over some pages from WikiVS, that I quote from:
because lambdas in Python are restricted to expressions and cannot
contain statements
I would like to know what would be a good example (or more) where this restriction would be, preferably compared to the Ruby language.
Thank you for your answers, comments and feedback!
A:
I don't think you're really asking about lambdas, but inline functions.
This is genuinely one of Python's seriously annoying limitations: you can't define a function (a real function, not just an expression) inline; you have to give it a name. This is very frustrating, since every other modern scripting language does this and it's often very painful to have to move functions out-of-line. It's also frustrating because I have a feeling Python bytecode can represent this trivially--it's just the language syntax that can't.
Javascript:
responses = {
"resp1": {
"start": function() { ... },
"stop": function() { ... },
},
"resp2": {
"start": function() { ... },
"stop": function() { ... },
},
...
}
responses["resp1"]["start"]();
Lua:
responses = {
resp1 = {
start = function() ... end;
end = function() ... end;
};
...
}
responses.resp1.start();
Ruby:
responses = {
"resp1" => {
"start" => lambda { },
"stop" => lambda { },
},
}
responses["resp1"]["start"].call
Python:
def resp1_start():
pass
def resp1_stop():
pass
responses = {
"resp1": {
"start": resp1_start,
"stop": resp1_stop,
},
}
responses["resp1"]["start"]()
Note that JavaScript and Lua don't have lambdas: they have no reason to exist, since inline functions cover them in a much more natural and general way.
I'd probably rate this as the single most annoying day-to-day Python limitation.
A:
The most commonly encountered situation regarding statements is probably Python 2.X's print statement.
For example,
say_hi = lambda name: "Hello " + name
works as expected.
But this will not compile:
say_hi = lambda name: print "Hello " + name
because print is not a proper function in Python 2.
>>> say_hi = lambda name: "Hello " + name
>>> say_hi("Mark")
'Hello Mark'
>>>
>>> say_hi = lambda name: print "Hello " + name
SyntaxError: invalid syntax
The rest of the statements besides print can be found in the Python documentation online:
simple_stmt ::= expression_stmt
| assert_stmt
| assignment_stmt
| augmented_assignment_stmt
| pass_stmt
| del_stmt
| print_stmt
| return_stmt
| yield_stmt
| raise_stmt
| break_stmt
| continue_stmt
| import_stmt
| global_stmt
| exec_stmt
You can try the rest of these out in the REPL if you want to see them fail:
>> assert(True)
>>> assert_lambda = lambda: assert(True)
SyntaxError: invalid syntax
>>> pass
>>> pass_lambda = lambda: pass
SyntaxError: invalid syntax
I'm not sure what parallels there are between Python's lambda restrictions and Ruby's proc or lambda. In Ruby, everything is a message, so you don't have keywords (okay, you do have keywords, but you don't have keywords that appear to be functions like Python's print). Off the top of my head, there's no easily-mistaken Ruby constructs that will fail in a proc.
A:
An example that has sometimes come up with me is something like this:
def convert(value):
n = expensive_op(value)
return (n, n + 1)
new_list = map(convert, old_list)
Although it is short and sweet enough, you can't convert it to a lambda without having to run expensive_op() twice (which, as the name suggests, you don't want to), i.e. you would have to do
new_list = map(lambda v: (expensive_op(v), expensive_op(v) + 1), old_list)
because assignment (n = ...) is a statement.
A:
Instead of f=lambda s:pass you can do f=lambda s:None.
A:
lambda is simply a shortcut way in Python to define a function that returns a simple expression.
This isn't a restriction in any meaningful way. If you need more than a single expression then just use a function: there is nothing you can do with a lambda that you cannot do with a function.
The only disadvantages to using a function instead of a lambda are that the function has to be defined on 1 or more separate lines (so you may lose some locality compared to the lambda), and you have to invent a name for the function (but if you can't think of one then f generally works).
All the other reasons people think they have to use a lambda (such as accessing nested variables or generating lots of lambdas with separate default arguments) will work just as well with a function.
The big advantage of using a named function is of course that when it goes wrong you get a meaningful stack trace. I had that bite me yesterday when I got a stack trace involving a lambda and no context about which lambda it was.
| Restrictons of Python compared to Ruby: lambda's | I was going over some pages from WikiVS, that I quote from:
because lambdas in Python are restricted to expressions and cannot
contain statements
I would like to know what would be a good example (or more) where this restriction would be, preferably compared to the Ruby language.
Thank you for your answers, comments and feedback!
| [
"I don't think you're really asking about lambdas, but inline functions.\nThis is genuinely one of Python's seriously annoying limitations: you can't define a function (a real function, not just an expression) inline; you have to give it a name. This is very frustrating, since every other modern scripting language... | [
14,
9,
4,
2,
1
] | [] | [] | [
"lambda",
"python",
"restriction",
"ruby"
] | stackoverflow_0002654425_lambda_python_restriction_ruby.txt |
Q:
How to replace an instance in __init__() with a different object?
I am calling a constructor in ClassA and want to have the resulting object be of a different class (ClassB) if a certain condition is met. I've tried replacing the first argument to __init__() ('self' in the example below) within __init__() but it doesn't seem to do what I want.
in main:
import ClassA
my_obj = ClassA.ClassA(500)
# unfortunately, my_obj is a ClassA, but I want a ClassB!
in ClassA/__init__.py:
import ClassB
class ClassA:
def __init__(self,theirnumber):
if(theirnumber > 10):
# all big numbers should be ClassB objects:
self = ClassB.ClassB(theirnumber)
return
else:
# numbers under 10 are ok in ClassA.
return
in ClassB/__init__.py:
class ClassB:
pass
A:
You need __new__() for that. (And you also need to make it a new-style class, assuming you're using Python 2, by subclassing object.)
class ClassA(object):
def __new__(cls,theirnumber):
if theirnumber > 10:
# all big numbers should be ClassB objects:
return ClassB.ClassB(theirnumber)
else:
# numbers under 10 are ok in ClassA.
return super(ClassA, cls).__new__(cls, theirnumber)
__new__() runs as part of the class instantiation process before __init__(). Basically __new__() is what actually creates the new instance, and __init__() is then called to initialize its properties. That's why you can use __new__() but not __init__() to alter the type of object created: once __init__() starts, the object has already been created and it's too late to change its type. (Well... not really, but that gets into very arcane Python black magic.) See the documentation.
In this case, though, I'd say a factory function is more appropriate, something like
def thingy(theirnumber):
if theirnumber > 10:
return ClassB.ClassB(theirnumber)
else:
return ClassA.ClassA(theirnumber)
By the way, note that if you do what I did with __new__() above, if a ClassB is returned, the __init__() method you wrote in ClassA will not be called on the ClassB instance! When you construct the ClassB instance inside ClassA.__new__(), its own __init__() method (ClassB.__init__()) will be run at that point, so hopefully it makes sense that Python shouldn't run another unrelated __init__() method on the same object. But this can get kind of confusing, which is probably another argument in favor of the factory function approach.
A:
I would suggest using a factory pattern for this. For example:
def get_my_inst(the_number):
if the_number > 10:
return ClassB(the_number)
else:
return ClassA(the_number)
class_b_inst = get_my_inst(500)
class_a_inst = get_my_inst(5)
A:
Don't try to pervert the purpose of constructors: use a factory function. Calling a constructor for one class and being returned an instance of a different class is a sure way to cause confusion.
| How to replace an instance in __init__() with a different object? | I am calling a constructor in ClassA and want to have the resulting object be of a different class (ClassB) if a certain condition is met. I've tried replacing the first argument to __init__() ('self' in the example below) within __init__() but it doesn't seem to do what I want.
in main:
import ClassA
my_obj = ClassA.ClassA(500)
# unfortunately, my_obj is a ClassA, but I want a ClassB!
in ClassA/__init__.py:
import ClassB
class ClassA:
def __init__(self,theirnumber):
if(theirnumber > 10):
# all big numbers should be ClassB objects:
self = ClassB.ClassB(theirnumber)
return
else:
# numbers under 10 are ok in ClassA.
return
in ClassB/__init__.py:
class ClassB:
pass
| [
"You need __new__() for that. (And you also need to make it a new-style class, assuming you're using Python 2, by subclassing object.)\nclass ClassA(object):\n def __new__(cls,theirnumber):\n if theirnumber > 10:\n # all big numbers should be ClassB objects:\n return ClassB.ClassB(th... | [
47,
18,
16
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003209233_oop_python.txt |
Q:
How can I refactor this django query to not select each individual object?
Here's my view:
def rsvp_list(request, id, template="rsvp/rsvp_list.html"):
rsvp = RSVP.objects.get(id=id)
return render_to_response(template, {
'attendees': rsvp.attendee_set.all().order_by('email__first_name'),
}, context_instance=RequestContext(request))
and here's my template:
{% for attendee in attendees %}
{{ attendee.email.get_name }}{{ attendee.guests }}
{% endfor %}
When the request is run, the template then runs a query for each attendee to get their first and last name (get name just puts the two together). Here's an example query that django fires from the template:
SELECT `rsvp_email`.`id`, `rsvp_email`.`added`, `rsvp_email`.`first_name`, `rsvp_email`.`last_name`, `rsvp_email`.`address` FROM `rsvp_email` WHERE `rsvp_email`.`id` = 1038
How can I retrieve the first and last name of each attendee is the first query without looping through it 400 times in the template?
A:
I should have read a bit further in the documentation.
In order to reduce the queries that are going to happen on related object later, just use select_related. So my query becomes:
attendees = rsvp.attendee_set.select_related().all().order_by('email__first_name')
| How can I refactor this django query to not select each individual object? | Here's my view:
def rsvp_list(request, id, template="rsvp/rsvp_list.html"):
rsvp = RSVP.objects.get(id=id)
return render_to_response(template, {
'attendees': rsvp.attendee_set.all().order_by('email__first_name'),
}, context_instance=RequestContext(request))
and here's my template:
{% for attendee in attendees %}
{{ attendee.email.get_name }}{{ attendee.guests }}
{% endfor %}
When the request is run, the template then runs a query for each attendee to get their first and last name (get name just puts the two together). Here's an example query that django fires from the template:
SELECT `rsvp_email`.`id`, `rsvp_email`.`added`, `rsvp_email`.`first_name`, `rsvp_email`.`last_name`, `rsvp_email`.`address` FROM `rsvp_email` WHERE `rsvp_email`.`id` = 1038
How can I retrieve the first and last name of each attendee is the first query without looping through it 400 times in the template?
| [
"I should have read a bit further in the documentation.\nIn order to reduce the queries that are going to happen on related object later, just use select_related. So my query becomes:\nattendees = rsvp.attendee_set.select_related().all().order_by('email__first_name')\n\n"
] | [
1
] | [] | [] | [
"django",
"python",
"sql"
] | stackoverflow_0003209228_django_python_sql.txt |
Q:
python - appending different columns from a file to different lists?
I have a tab-delimited file as below:
A 3 A 6
B 6 B 9
C 0 C 2
I wish to read the file in as below:
LIST = [['A', '3'], ['B', '6'], ['C', '0'], ['A', '6'], ['B', '9'], ['C', '2']]
The order is not important. I am only concerned that each row is read in increments of two and assigned to a sub list.
Any suggestions?
Thanks,
S :-)
A:
The most straightforward way would be:
>>> n = []
>>> for line in open(fname):
els = line.split('\t')
n.append(els[:2])
n.append(els[2:])
>>> n
[['A', '3'], ['A', '6'], ['B', '6'], ['B', '9'], ['C', '0'], ['C', '2']]
maybe slightly more efficient would be:
>>> g = (line.split('\t') for line in open(fname))
>>> [els[i:i+2] for els in g for i in range(0, 4, 2)]
[['A', '3'], ['A', '6'], ['B', '6'], ['B', '9'], ['C', '0'], ['C', '2']]
A:
This question actually allows for some Pythonic solutions.
l = open(fname).read().split()
LIST = zip(l[::2], l[1::2])
That's all there is to it. "Bam!"
Or we can "knock it up a notch":
def couple(i):
while True:
yield (i.next(), i.next())
LIST = [w for w in couple(iter(open(fname).read().split()))]
Additional benefits of those are that they will read the file in pairs, no matter if there are 4 columns (as in the example) or 6, 2... whatever
See also
pythonic-way-to-split-comma-separated-numbers-into-pairs and
how-do-you-split-a-list-into-evenly-sized-chunks-in-python
| python - appending different columns from a file to different lists? | I have a tab-delimited file as below:
A 3 A 6
B 6 B 9
C 0 C 2
I wish to read the file in as below:
LIST = [['A', '3'], ['B', '6'], ['C', '0'], ['A', '6'], ['B', '9'], ['C', '2']]
The order is not important. I am only concerned that each row is read in increments of two and assigned to a sub list.
Any suggestions?
Thanks,
S :-)
| [
"The most straightforward way would be:\n>>> n = []\n>>> for line in open(fname):\n els = line.split('\\t')\n n.append(els[:2])\n n.append(els[2:])\n\n\n>>> n\n[['A', '3'], ['A', '6'], ['B', '6'], ['B', '9'], ['C', '0'], ['C', '2']]\n\nmaybe slightly more efficient would be:\n>>> g = (line.split('\\t') for... | [
3,
0
] | [] | [] | [
"file",
"list",
"python"
] | stackoverflow_0003204114_file_list_python.txt |
Q:
Initialized string variable in Python?
Create a string variable that is initialized to your entire name??
Im a little lost
Thanks Kim:)
A:
You want to create a string variable with my name? Sure, here it is:
my_name = 'Samuel Robert Dolan'
If that's not what you want, please be more descriptive in your question. :)
| Initialized string variable in Python? | Create a string variable that is initialized to your entire name??
Im a little lost
Thanks Kim:)
| [
"You want to create a string variable with my name? Sure, here it is:\n my_name = 'Samuel Robert Dolan'\n\nIf that's not what you want, please be more descriptive in your question. :)\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003209326_python.txt |
Q:
How to remove values from item list
I am new to python. I have a item list looks like this:
rank_item = [
(9, 0.99999999745996648),
(8, 0.99999996796861101),
(1, 0.99999996796861101),
(10, 0.0) ]
The question is how do i remove the item list with value 0.0 and return
[(9, 0.99999999745996648), (8, 0.99999996796861101), (1, 0.99999996796861101)]
A:
Use list.remove - which will modify your rank_item list in-place:
rank_item.remove( (10, 0.0) )
rank_item will contain:
[(9, 0.99999999745996648), (8, 0.99999996796861101), (1, 0.99999996796861101)]
Or, if you want to remove all tuples from your list, which have a the value 0.0 at position 1, you can try a list comprehension, e.g.:
[ x for x in rank_item if x[1] != 0.0 ]
A:
[x for x in rank_item if x[1] != 0.0]
A:
>>> [i for i in rank_item if i[1]]
[(9, 0.9999999974599665), (8, 0.999999967968611), (1, 0.999999967968611)]
A:
For a more general case, you can use a list comprehension:
new_list = [(a, b) for a, b in old_list if b != 0]
This would only return the tuples where the second element is different from zero; you can adjust this behavior to fit your needs.
This approach favors a clear labeling of each element, as opposed to using an index.
A:
Speed test:
>>> import timeit
>>> it = lambda : list(filter(lambda x: x[1]!=0, rank_item))
>>> timeit.timeit(it)
3.7716277663630535
>>> it2 = lambda: [x for x in rank_item if x[1] != 0.0]
>>> timeit.timeit(it2)
1.2550897693390652
>>> it3 = lambda: [i for i in rank_item if i[1]]
>>> timeit.timeit(it3)
1.147179730129892
>>> it4 = lambda: list(itertools.takewhile(lambda x: x[1] != 0, rank_item))
>>> timeit.timeit(it4)
3.8272935335999136
| How to remove values from item list | I am new to python. I have a item list looks like this:
rank_item = [
(9, 0.99999999745996648),
(8, 0.99999996796861101),
(1, 0.99999996796861101),
(10, 0.0) ]
The question is how do i remove the item list with value 0.0 and return
[(9, 0.99999999745996648), (8, 0.99999996796861101), (1, 0.99999996796861101)]
| [
"Use list.remove - which will modify your rank_item list in-place:\n rank_item.remove( (10, 0.0) )\n\nrank_item will contain:\n[(9, 0.99999999745996648), (8, 0.99999996796861101), (1, 0.99999996796861101)]\n\nOr, if you want to remove all tuples from your list, which have a the value 0.0 at position 1, you can try ... | [
5,
5,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003205956_python.txt |
Q:
Reference ID in GAE
I have a feeling the answer is simple and documented, but I'm absolutely missing it:
Is there a way, using Python and webapp through Google App Engine, to pass the id field of a record to the template? I'm fairly new to the app engine, and yes, I have searched all around the Google Documentation to find this.
A:
I can reference it through record.key().id(). I just found this RIGHT AFTER I posted this question (as luck would have it). Sorry for wasting anybody's time.
A:
Assuming you're using the built-in Django 0.96 templates, you can access the ID (assuming the entity has one; it might have a key name instead if you saved it with one) with {{entity.key.id}}.
| Reference ID in GAE | I have a feeling the answer is simple and documented, but I'm absolutely missing it:
Is there a way, using Python and webapp through Google App Engine, to pass the id field of a record to the template? I'm fairly new to the app engine, and yes, I have searched all around the Google Documentation to find this.
| [
"I can reference it through record.key().id(). I just found this RIGHT AFTER I posted this question (as luck would have it). Sorry for wasting anybody's time.\n",
"Assuming you're using the built-in Django 0.96 templates, you can access the ID (assuming the entity has one; it might have a key name instead if you ... | [
3,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003207671_google_app_engine_google_cloud_datastore_python.txt |
Q:
data.dat python
say i have the following data in a .dat file:
*A-1-2-3-4*B-8-2-4*C-4-2-5-1-5
how can i print the these data like this?:
A : 1 2 3 4
B : 8 2 4
C : 4 2 5 1 5
randomly print any one number for each letter.
A, B and C can be any word.
and the amount of the numbers can be different.
i know that it has some thing to do with the * and the -
A:
Read in the file, then split() the characters:
contents = open("file.dat").read()
for line in contents.split("*"):
if not line: continue # Remove initial empty string.
line = line.strip() # Remove whitespace from beginning/end of lines.
items = line.split("-")
print items[0], ":", " ".join(items[1:])
A:
Also another option
line = "*A-1-2-3-4*B-8-2-4*C-4-2-5-1-5"
s = filter(bool, line.split("*"))
for i in s:
i = i.split("-")
print i[0], ":", i[1:]
A:
Use .split()
data_string = '*A-1-2-3-4*B-8-2-4*C-4-2-5-1-5' #read in the data
data = data_string.split('*') #split the data at the '*'
for entry in data:
items = entry.split('-') #split data entries at the '-'
letter = items[0] #you know that the first item is a letter
if not items[0]: continue #exclude the empty string
print letter, ':',
for num in items[1:]:
print int(num),
print '\n',
| data.dat python | say i have the following data in a .dat file:
*A-1-2-3-4*B-8-2-4*C-4-2-5-1-5
how can i print the these data like this?:
A : 1 2 3 4
B : 8 2 4
C : 4 2 5 1 5
randomly print any one number for each letter.
A, B and C can be any word.
and the amount of the numbers can be different.
i know that it has some thing to do with the * and the -
| [
"Read in the file, then split() the characters:\ncontents = open(\"file.dat\").read()\nfor line in contents.split(\"*\"):\n if not line: continue # Remove initial empty string.\n line = line.strip() # Remove whitespace from beginning/end of lines.\n items = line.split(\"-\")\n print items[0], \":\", \" \".jo... | [
4,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003209529_python.txt |
Q:
Information about computer in python
How would i go about gathering information about a system in python? Seems most of the commands are made for Unix... Are there any options in windows?
Thanks,
Jake.
A:
Getting system information under Windows (Python), from ActiveState code recipes.
A:
What about the platform module
A:
This page highlights the list of infos you can get from the OS and for each tells you the OS availability.
http://docs.python.org/library/os.html
Also check out this page
http://code.activestate.com/recipes/511491-getting-system-information-under-windows/
A:
Try the os module. link
| Information about computer in python | How would i go about gathering information about a system in python? Seems most of the commands are made for Unix... Are there any options in windows?
Thanks,
Jake.
| [
"Getting system information under Windows (Python), from ActiveState code recipes.\n",
"What about the platform module\n",
"This page highlights the list of infos you can get from the OS and for each tells you the OS availability.\nhttp://docs.python.org/library/os.html\nAlso check out this page\nhttp://code.ac... | [
1,
1,
0,
0
] | [] | [] | [
"python",
"system",
"windows"
] | stackoverflow_0003208827_python_system_windows.txt |
Q:
How do I change out the underlying object inside a method call?
I thought all function and method arguments in Python were passed by reference, leading me to believe that the following code would work:
class Insect:
def status(self):
print "i am a %s" % self
class Caterpillar(Insect):
def grow_up(self):
self = Butterfly() # replace myself with a new object
return
class Butterfly(Insect):
pass
my_obj = Caterpillar()
my_obj.status() # i am a <__main__.Caterpillar instance at 0x100494710>
# ok, time to grow up:
my_obj.grow_up()
my_obj.status() # want new Butterfly object, but it is still Caterpillar! :(
How do I go about changing the object itself within a method call?
-- EDIT:
So far, the responses have been:
1) Change self.__class__ to change the class associated with the current object.
2) "Don't hold it that way."
The original question: How do I make a new object that takes the place of the old one from within a method call defined on the old class?
I think the answer might actually be "you can't."
-- EDIT2:
Why is everyone deathly afraid of saying "It's not possible"?
A:
When you say self = Butterfly() all you're doing is changing what the variable self points to; you're not changing what self is, any more than:
x = 1
x = 2
... changes the number 1 to 2.
In general, when people need this, rather than change the type of the object (which many languages flat out forbid) people use a composition strategy:
class Lepidoptera(Insect):
def __init__(self):
self.stage = Caterpillar()
def status(self):
print 'I am a %s' % self.stage
def grow_up(self):
if self.stage.adult:
raise TypeError('Already an adult')
self.stage = Butterfly()
A:
self.__class__ = Butterfly may work, because it's rebinding a qualified name (which is a completely different thing from rebinding a bare name).
Rebinding a barename never has any effect on whatever object was previously bound to it (unless that barename was the only reference to that "previous object", in which case the latter may be destroyed -- but that's obviously not the case here, since self is a reference to the same objects as my_obj and so self cannot be the only reference to it).
Edit:
You refer to needing to initialize the newly-re-classed object -- that's easy:
self.__dict__.clear()
self.__class__ = Butterfly
self.__init__(whatever, you, want)
But then in a comment you mention needing to "back up the attributes" -- I don't know what exactly you mean, or why that would at all differ from your "dream case" of assigning directly to self (which would of course blow the attributes away, too). Maybe the idea is that (some of) the arguments to __init__ need to be attributes of self? Then, for example, you could code it like:
d, self.__dict__ = self.__dict__, {}
self.__class__ = Butterfly
self.__init__(d['whatever'], d['you'], d['want'])
A:
Remember that variables in Python are names that are bound to objects. Read section 4.1 of the Language Reference for more details. The gist of it is that a method parameter is a name that is bound to the object that is passed in the invocation.
When you "assign a new value" to the variable, you are simply binding the local name to a new object. The object that it originally referred to is unchanged.
When you invoke a mutating method on a variable, the method can change the internal state of the object by using a qualified name such as self.var which is what Alex is referring to in his answer. If you rebind self, you are not modifying the object.
This is one of the more interesting features of Python. It is a little different than most other languages in that you really have no way to access the raw object pointer (e.g., this) within a method. The only thing that you have access to is the bound name of the instance.
Edit: I don't know how I managed to forget to answer your actual question, but the answer is certainly that you cannot change the underlying object from within a method call. My rambling was the why part without actually providing an answer.
A:
Your design is fundamentally flawed. A caterpillar and butterfly are not different creatures, they are different states of the same creature.
class Lepidoptera(Insect):
# Just use strings for states
CATERPILLAR = "caterpillar"
BUTTERFLY = "butterfly"
def __init__(self):
self.state = Lepidoptera.CATERPILLAR
def grow_up(self):
self.state = Lepidoptera.BUTTERFLY
def status(self):
""" Override superclass method. """
print "I am a %s, currently in the state: %s" % (self, self.state)
If you needed something more sophisticated, the states should be more sophisticated objects that take extra parameters (or simply let the Lepidoptera class take care of it internally).
You are effectively asking how to change a lepidoptera into a cricket, which cannot happen. This is why you cannot find a way to represent this concept in your program (or why it seems so hacky). You've decided to use objects to represent insects, but then you actually create classes that represent insect states. Then you wonder why you can't model the insect behaviour properly.
Working the other way, if you want classes to represent insect states, then clearly you need other classes to represent to insects themselves, which would then contain these states and the methods to change them.
In terms of your real problem, it sounds like you're confusing "the thing with the state" with "the state itself".
A:
As Alex puts it clearly, there is no way to do that strictly.
And I can't think of a way it such a thing could be desirable. Maybe you need a factory function insetad? Or different states of the same object?
However, Python being what it is, you can have a "shell" object whose only purpose would be to grant access to an underlyign object. The underlying object could then be modified: while the shell object remains the same, the underlying object is another one.
One possible implementation is as follows (and I've tried again with an unclean implementation for __getattribute__ - it can be made better)
# -*- coding: utf-8 -*-
class Insect(object):
pass
class Catterpillar(Insect):
a = "I am a caterpillar"
class Butterfly(Insect):
a = "I am a butterfly"
class Cocoon(object):
def __init__(self, *args, **kw):
self._true = Catterpillar(*args, **kw)
def __getattribute__(self, attr):
try:
if attr != "_true":
return getattr(object.__getattribute__(self, "_true"),attr)
except AttributeError:
pass
return object.__getattribute__(self, attr)
def __setattr__(self, attr, val):
if attr != "_true":
setattr(self._true, attr, val)
else:
object.__setattr__(self, attr, val)
def change(self, *args, **kw):
self._true = Butterfly(*args, **kw)
WIth this you can get stuff like:
>>>
>>> a= Cocoon()
>>> a.a
'I am a caterpillar'
>>> a.__class__
<class '__main__.Catterpillar'>
>>> a.change()
>>> a.a
'I am a butterfly'
>>> a.__class__
<class '__main__.Butterfly'>
>>>
.
On the change function you can backup whatever attributes you want, and you can exempt other attributes from change in the __getattribute__ method.
| How do I change out the underlying object inside a method call? | I thought all function and method arguments in Python were passed by reference, leading me to believe that the following code would work:
class Insect:
def status(self):
print "i am a %s" % self
class Caterpillar(Insect):
def grow_up(self):
self = Butterfly() # replace myself with a new object
return
class Butterfly(Insect):
pass
my_obj = Caterpillar()
my_obj.status() # i am a <__main__.Caterpillar instance at 0x100494710>
# ok, time to grow up:
my_obj.grow_up()
my_obj.status() # want new Butterfly object, but it is still Caterpillar! :(
How do I go about changing the object itself within a method call?
-- EDIT:
So far, the responses have been:
1) Change self.__class__ to change the class associated with the current object.
2) "Don't hold it that way."
The original question: How do I make a new object that takes the place of the old one from within a method call defined on the old class?
I think the answer might actually be "you can't."
-- EDIT2:
Why is everyone deathly afraid of saying "It's not possible"?
| [
"When you say self = Butterfly() all you're doing is changing what the variable self points to; you're not changing what self is, any more than:\nx = 1\nx = 2\n\n... changes the number 1 to 2.\nIn general, when people need this, rather than change the type of the object (which many languages flat out forbid) people... | [
3,
2,
1,
1,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003209419_oop_python.txt |
Q:
"self" inside plain function?
I've got a bunch of functions (outside of any class) where I've set attributes on them, like funcname.fields = 'xxx'. I was hoping I could then access these variables from inside the function with self.fields, but of course it tells me:
global name 'self' is not defined
So... what can I do? Is there some magic variable I can access? Like __this__.fields?
A few people have asked "why?". You will probably disagree with my reasoning, but I have a set of functions that all must share the same signature (accept only one argument). For the most part, this one argument is enough to do the required computation. However, in a few limited cases, some additional information is needed. Rather than forcing every function to accept a long list of mostly unused variables, I've decided to just set them on the function so that they can easily be ignored.
Although, it occurs to me now that you could just use **kwargs as the last argument if you don't care about the additional args. Oh well...
Edit: Actually, some of the functions I didn't write, and would rather not modify to accept the extra args. By "passing in" the additional args as attributes, my code can work both with my custom functions that take advantage of the extra args, and with third party code that don't require the extra args.
Thanks for the speedy answers :)
A:
self isn't a keyword in python, its just a normal variable name. When creating instance methods, you can name the first parameter whatever you want, self is just a convention.
You should almost always prefer passing arguments to functions over setting properties for input, but if you must, you can do so using the actual functions name to access variables within it:
def a:
if a.foo:
#blah
a.foo = false
a()
see python function attributes - uses and abuses for when this comes in handy. :D
A:
def foo():
print(foo.fields)
foo.fields=[1,2,3]
foo()
# [1, 2, 3]
There is nothing wrong with adding attributes to functions. Many memoizers use this to cache results in the function itself.
For example, notice the use of func.cache:
from decorator import decorator
@decorator
def memoize(func, *args, **kw):
# Author: Michele Simoniato
# Source: http://pypi.python.org/pypi/decorator
if not hasattr(func, 'cache'):
func.cache = {}
if kw: # frozenset is used to ensure hashability
key = args, frozenset(kw.iteritems())
else:
key = args
cache = func.cache # attribute added by memoize
if key in cache:
return cache[key]
else:
cache[key] = result = func(*args, **kw)
return result
A:
Example:
>>> def x(): pass
>>> x
<function x at 0x100451050>
>>> x.hello = "World"
>>> x.hello
"World"
You can set attributes on functions, as these are just plain objects, but I actually never saw something like this in real code.
Plus. self is not a keyword, just another variable name, which happens to be the particular instance of the class. self is passed implicitly, but received explicitly.
A:
You can't do that "function accessing its own attributes" correctly for all situations - see for details here how can python function access its own attributes? - but here is a quick demonstration:
>>> def f(): return f.x
...
>>> f.x = 7
>>> f()
7
>>> g = f
>>> g()
7
>>> del f
>>> g()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<interactive input>", line 1, in f
NameError: global name 'f' is not defined
Basically most methods directly or indirectly rely on accessing the function object through lookup by name in globals; and if original function name is deleted, this stops working. There are other kludgey ways of accomplishing this, like defining class, or factory - but thanks to your explanation it is clear you don't really need that.
Just do the mentioned keyword catch-all argument, like so:
def fn1(oneArg):
// do the due
def fn2(oneArg, **kw):
if 'option1' in kw:
print 'called with option1=', kw['option1']
//do the rest
fn2(42)
fn2(42, option1='something')
Not sure what you mean in your comment of handling TypeError - that won't arise when using **kw. This approach works very well for some python system functions - check min(), max(), sort(). Recently sorted(dct,key=dct.get,reverse=True) came very handy to me in CodeGolf challenge :)
A:
if you want globally set parameters for a callable 'thing' you could always create a class and implement the __call__ method?
A:
There is no special way, within a function's body, to refer to the function object whose code is executing. Simplest is just to use funcname.field (with funcname being the function's name within the namespace it's in, which you indicate is the case -- it would be harder otherwise).
A:
This isn't something you should do. I can't think of any way to do what you're asking except some walking around on the call stack and some weird introspection -- which isn't something that should happen in production code.
That said, I think this actually does what you asked:
import inspect
_code_to_func = dict()
def enable_function_self(f):
_code_to_func[f.func_code] = f
return f
def get_function_self():
f = inspect.currentframe()
code_obj = f.f_back.f_code
return _code_to_func[code_obj]
@enable_function_self
def foo():
me = get_function_self()
print me
foo()
A:
While I agree with the the rest that this is probably not good design, the question did intrigue me. Here's my first solution, which I may update once I get decorators working. As it stands, it relies pretty heavily on being able to read the stack, which may not be possible in all implementations (something about sys._getframe() not necessarily being present...)
import sys, inspect
def cute():
this = sys.modules[__name__].__dict__.get(inspect.stack()[0][3])
print "My face is..." + this.face
cute.face = "very cute"
cute()
What do you think? :3
A:
You could use the following (hideously ugly) code:
class Generic_Object(object):
pass
def foo(a1, a2, self=Generic_Object()):
self.args=(a1,a2)
print "len(self.args):", len(self.args)
return None
... as you can see it would allow you to use "self" as you described. You can't use an "object()" directly because you can't "monkey patch(*)" values into an object() instance. However, normal subclasses of object (such as the Generic_Object() I've shown here) can be "monkey patched"
If you wanted to always call your function with a reference to some object as the first argument that would be possible. You could put the defaulted argument first, followed by a *args and optional **kwargs parameters (through which any other arguments or dictionaries of options could be passed during calls to this function).
This is, as I said hideously ugly. Please don't ever publish any code like this or share it with anyone in the Python community. I'm only showing it here as a sort of strange educational exercise.
An instance method is like a function in Python. However, it exists within the namespace of a class (thus it must be accessed via an instance ... myobject.foo() for example) and it is called with a reference to "self" (analagous to the "this" pointer in C++) as the first argument. Also there's a method resolution process which causes the interpreter to search the namespace of the instance, then it's class, and then each of the parent classes and so on ... up through the inheritance tree.
An unbound function is called with whatever arguments you pass to it. There can't bee any sort of automatically pre-pended object/instance reference to the argument list. Thus, writing a function with an initial argument named "self" is meaningless. (It's legal because Python doesn't place any special meaning on the name "self." But meaningless because callers to your function would have to manually supply some sort of object reference to the argument list and it's not at all clear what that should be. Just some bizarre "Generic_Object" which then floats around in the global variable space?).
I hope that clarifies things a bit. It sounds like you're suffering from some very fundamental misconceptions about how Python and other object-oriented systems work.
("Monkey patching" is a term used to describe the direct manipulation of an objects attributes -- or "instance variables" by code that is not part of the class hierarchy of which the object is an instance).
A:
As another alternative, you can make the functions into bound class methods like so:
class _FooImpl(object):
a = "Hello "
@classmethod
def foo(cls, param):
return cls.a + param
foo = _FooImpl.foo
# later...
print foo("World") # yes, Hello World
# and if you have to change an attribute:
foo.im_self.a = "Goodbye "
If you want functions to share attribute namespaecs, you just make them part of the same class. If not, give each its own class.
A:
What exactly are you hoping "self" would point to, if the function is defined outside of any class? If your function needs some global information to execute properly, you need to send this information to the function in the form of an argument.
If you want your function to be context aware, you need to declare it within the scope of an object.
| "self" inside plain function? | I've got a bunch of functions (outside of any class) where I've set attributes on them, like funcname.fields = 'xxx'. I was hoping I could then access these variables from inside the function with self.fields, but of course it tells me:
global name 'self' is not defined
So... what can I do? Is there some magic variable I can access? Like __this__.fields?
A few people have asked "why?". You will probably disagree with my reasoning, but I have a set of functions that all must share the same signature (accept only one argument). For the most part, this one argument is enough to do the required computation. However, in a few limited cases, some additional information is needed. Rather than forcing every function to accept a long list of mostly unused variables, I've decided to just set them on the function so that they can easily be ignored.
Although, it occurs to me now that you could just use **kwargs as the last argument if you don't care about the additional args. Oh well...
Edit: Actually, some of the functions I didn't write, and would rather not modify to accept the extra args. By "passing in" the additional args as attributes, my code can work both with my custom functions that take advantage of the extra args, and with third party code that don't require the extra args.
Thanks for the speedy answers :)
| [
"self isn't a keyword in python, its just a normal variable name. When creating instance methods, you can name the first parameter whatever you want, self is just a convention.\nYou should almost always prefer passing arguments to functions over setting properties for input, but if you must, you can do so using the... | [
12,
3,
2,
2,
1,
1,
1,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003207572_python.txt |
Q:
What is the easiest method to compare large amounts of similar text?
somewhat open ended question here as I am mostly looking for opinions. I am grabbing some data from craigslist for apt ads in my area since I am looking to move. My goal is to be able to compare items to see when something is a duplicate so that I don't spend all day looking at the same 3 ads. The problem is that they change things around a little to get past CL's filters.
I already have some regex to look for address and phone numbers to compare, but that isn't the most reliable. Is anyone familiar with an easy-ish method to compare the whole document and maybe show something simple like "80% similar"? I can't think of anything offhand, so I suspect I'll have to start from scratch on my own solution, but figured it would be worth asking the collective genius of stackoverflow :)
Preferred languages/methods would be python/php/perl, but if it's a great solution I'm pretty open.
Update: one thing worth noting is that since I will be storing the scraped data of the rss feed for apts in my area (los angeles) in a local DB, the preferred method would include a way to compare it to everything I currently know. This could be a bit of a showstopper since that could become a very long process as the post counts grow.
A:
You could calculate the Levenshtein difference between both strings - after some sane normalizing like minimizing duplicate whitespace and what not. After you run through enough "duplicates" you should get an idea of what your threshold is - then you can run Levenshtein on all new incoming data and if its less-than-equal to your threshold than you can consider it a duplicate.
A:
There are few quite complex projects to find text duplications. One of them is Simian. Take a look at it.
A:
You could use xdiff. There is an xdiff PECL extension for PHP available.
Or use similar_text to calculate the similarity between two strings
A:
You can use difflib to calculate differences in python directly.
Edit: you can consider creating a hash of the content in some way to reduce the amount of text that needs to be "diffed". For example, remove all whitespace, punctuation, tags etc and just look at the actual content.
A:
If you wanted to do this a lot and with some reliability, you might want to use a semi-advanced approach like a "bag of words" technique. I actually sat down and wrote a sketch of a more-or-less working (if horribly unoptimized) algorithm to do it, but I'm not sure if it would really be appropriate to include here. There are pre-made libraries that you can use for text classification instead.
| What is the easiest method to compare large amounts of similar text? | somewhat open ended question here as I am mostly looking for opinions. I am grabbing some data from craigslist for apt ads in my area since I am looking to move. My goal is to be able to compare items to see when something is a duplicate so that I don't spend all day looking at the same 3 ads. The problem is that they change things around a little to get past CL's filters.
I already have some regex to look for address and phone numbers to compare, but that isn't the most reliable. Is anyone familiar with an easy-ish method to compare the whole document and maybe show something simple like "80% similar"? I can't think of anything offhand, so I suspect I'll have to start from scratch on my own solution, but figured it would be worth asking the collective genius of stackoverflow :)
Preferred languages/methods would be python/php/perl, but if it's a great solution I'm pretty open.
Update: one thing worth noting is that since I will be storing the scraped data of the rss feed for apts in my area (los angeles) in a local DB, the preferred method would include a way to compare it to everything I currently know. This could be a bit of a showstopper since that could become a very long process as the post counts grow.
| [
"You could calculate the Levenshtein difference between both strings - after some sane normalizing like minimizing duplicate whitespace and what not. After you run through enough \"duplicates\" you should get an idea of what your threshold is - then you can run Levenshtein on all new incoming data and if its less-t... | [
2,
1,
1,
1,
0
] | [] | [] | [
"perl",
"php",
"python",
"regex",
"sql"
] | stackoverflow_0003095057_perl_php_python_regex_sql.txt |
Q:
Determining number of sites on a website in python
I have the following link:
http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-0001&language=EN
the reference part of the url has the following information:
A7 == The parliament (current is the seventh parliament, the former is A6 and so forth)
2010 == year
0001 == document number
For every year and parliament I would like to identify the number of documents on the website. The task is complicated by the fact that for 2010, for instance, numbers 186, 195,196 have empty pages, while the max number is 214. Ideally the output should be a vector with all the document numbers, excluding the missing ones.
Can anyone tell me if this is possible in python?
Best, Thomas
A:
First, make sure that scraping their site is legal.
Second, notice that when a document is not present, the HTML file contains:
<title>Application Error</title>
Third, use urllib to iterate over all the things you want to:
for p in range(1,7):
for y in range(2000, 2011):
doc = 1
while True:
# use urllib to open the url: (root)+p+y+doc
# if the HTML has the string "application error" break from the while
doc+=1
A:
Here's a slightly more complete (but hacky) example which seems to work(using urllib2) - I'm sure you can customise it for your specific needs.
I'd also repeat Arrieta's warning about making sure the site's owner doesn't mind you scraping it's content.
#!/usr/bin/env python
import httplib2
h = httplib2.Http(".cache")
parliament = "A7"
year = 2010
#Create two lists, one list of URLs and one list of document numbers.
urllist = []
doclist = []
urltemplate = "http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=%s-%d-%04u&language=EN"
for document in range(0,9999):
url = urltemplate % (parliament,year,document)
resp, content = h.request(url, "GET")
if content.find("Application Error") == -1:
print "Document %04u exists" % (document)
urllist.append(urltemplate % (parliament,year,document))
doclist.append(document)
else:
print "Document %04u doesn't exist" % (document)
print "Parliament %s, year %u has %u documents" % (parliament,year,len(doclist))
A:
Here is a solution, but adding some timeout between request is a good idea:
import urllib
URL_TEMPLATE="http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-%d-%.4d&language=EN"
maxRange=300
for year in [2010, 2011]:
for page in range(1,maxRange):
f=urllib.urlopen(URL_TEMPLATE%(year, page))
text=f.read()
if "<title>Application Error</title>" in text:
print "year %d and page %.4d NOT found" %(year, page)
else:
print "year %d and page %.4d FOUND" %(year, page)
f.close()
| Determining number of sites on a website in python | I have the following link:
http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-0001&language=EN
the reference part of the url has the following information:
A7 == The parliament (current is the seventh parliament, the former is A6 and so forth)
2010 == year
0001 == document number
For every year and parliament I would like to identify the number of documents on the website. The task is complicated by the fact that for 2010, for instance, numbers 186, 195,196 have empty pages, while the max number is 214. Ideally the output should be a vector with all the document numbers, excluding the missing ones.
Can anyone tell me if this is possible in python?
Best, Thomas
| [
"First, make sure that scraping their site is legal.\nSecond, notice that when a document is not present, the HTML file contains:\n<title>Application Error</title>\n\nThird, use urllib to iterate over all the things you want to:\nfor p in range(1,7):\n for y in range(2000, 2011):\n doc = 1\n while True:\n # us... | [
3,
1,
1
] | [] | [] | [
"python",
"url",
"web_scraping"
] | stackoverflow_0003210012_python_url_web_scraping.txt |
Q:
Unable to upload file using django
I'm unable to upload a file using django. When I hit submit button I get "This webpage is not available. The webpage at http://127.0.0.1:8000/results might be temporarily down or it may have moved permanently to a new web address." error in chrome.
For the file upload HTTP query the corresponding webserver's log entry is:
[02/Jul/2010 17:36:06] "POST /results HTTP/1.1" 403 2313
This is the form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Content Based Image Retrieval System</title>
<link rel="stylesheet" href="site-content/css/style.css" />
</head>
<body>
<div><img src="site-content/images/logo.jpg" /> </div>
<form name="myform" action="results" method="POST" ENCTYPE="multipart/form-data>
<div align="center">
<br><br>
<input type="file" size="25" name="queryImage">
<br><input type="submit" value="Search"><br>
</div>
</form>
</body>
entry in urls.py:
(r'^results$',upload_and_search),
view that handles the file upload:
def upload_and_search(request):
if request.method != 'POST' or request.FILES is None:
output = 'Some thing wrong with file uploading'
handle_uploaded_file(request.FILES['queryImage'])
output = 'success'
return HttpResponse(output)
def handle_uploaded_file(f):
destination = open('queryImage', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
EDIT:
I've also tried changing the destination line destination = open('queryImage', 'wb+') to destination = open(os.environ['TMP']+'\\'+filename, 'wb+'). Its still giving the same error. Also the file I'm trying to upload is less than 2.5MB.
EDIT 2:
I've added a print statement in the first line of upload_and_search.Its not printing anything. i.e.. its not not even entering the function. I also checked if something is wrong with my url mapping by directly accessing the url http:// 127.0.0.1:8000/results. Its working fine. I think there is some problem with server configuration. I've no clue how to configure this server or what to configure. I'm stuck! I've no clue about what to do.
A:
I guess its because of csrf http://docs.djangoproject.com/en/dev/ref/contrib/csrf/
try changing your from
<form name="myform" action="results" method="POST" ENCTYPE="multipart/form-data">{% csrf_token %}
an the view generating it
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
def showIndexPage(request):
c = {}
c.update(csrf(request))
return render_to_response("index.html", c)
A:
Try this:
filename = f['filename']
destination = open('%s/%s' % (MEDIA_ROOT, filename), 'wb')
| Unable to upload file using django | I'm unable to upload a file using django. When I hit submit button I get "This webpage is not available. The webpage at http://127.0.0.1:8000/results might be temporarily down or it may have moved permanently to a new web address." error in chrome.
For the file upload HTTP query the corresponding webserver's log entry is:
[02/Jul/2010 17:36:06] "POST /results HTTP/1.1" 403 2313
This is the form:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Content Based Image Retrieval System</title>
<link rel="stylesheet" href="site-content/css/style.css" />
</head>
<body>
<div><img src="site-content/images/logo.jpg" /> </div>
<form name="myform" action="results" method="POST" ENCTYPE="multipart/form-data>
<div align="center">
<br><br>
<input type="file" size="25" name="queryImage">
<br><input type="submit" value="Search"><br>
</div>
</form>
</body>
entry in urls.py:
(r'^results$',upload_and_search),
view that handles the file upload:
def upload_and_search(request):
if request.method != 'POST' or request.FILES is None:
output = 'Some thing wrong with file uploading'
handle_uploaded_file(request.FILES['queryImage'])
output = 'success'
return HttpResponse(output)
def handle_uploaded_file(f):
destination = open('queryImage', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
EDIT:
I've also tried changing the destination line destination = open('queryImage', 'wb+') to destination = open(os.environ['TMP']+'\\'+filename, 'wb+'). Its still giving the same error. Also the file I'm trying to upload is less than 2.5MB.
EDIT 2:
I've added a print statement in the first line of upload_and_search.Its not printing anything. i.e.. its not not even entering the function. I also checked if something is wrong with my url mapping by directly accessing the url http:// 127.0.0.1:8000/results. Its working fine. I think there is some problem with server configuration. I've no clue how to configure this server or what to configure. I'm stuck! I've no clue about what to do.
| [
"I guess its because of csrf http://docs.djangoproject.com/en/dev/ref/contrib/csrf/\ntry changing your from\n<form name=\"myform\" action=\"results\" method=\"POST\" ENCTYPE=\"multipart/form-data\">{% csrf_token %}\n\nan the view generating it\nfrom django.core.context_processors import csrf\nfrom django.shortcuts ... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003165526_django_python.txt |
Q:
How to call C functions from python?
I have a scenario where GUI (Developed in VB) is sending commands to the target system application developed in C language (Xilinx).
User on a PC sends the commands to target using GUI.
But now I need to remove the GUI and want to send commands (call C functions in target system application) using Python.
I found some useful info from ctypes but don't know the exact procedure so getting budded up frequently.
Question :
Can anyone tell me the exact procedure to develop a python script for this. I know fair amount of python scripting.
A:
Invoke a SWIG wrapper to make C functions look like Python functions. Take a look at this example.
| How to call C functions from python? | I have a scenario where GUI (Developed in VB) is sending commands to the target system application developed in C language (Xilinx).
User on a PC sends the commands to target using GUI.
But now I need to remove the GUI and want to send commands (call C functions in target system application) using Python.
I found some useful info from ctypes but don't know the exact procedure so getting budded up frequently.
Question :
Can anyone tell me the exact procedure to develop a python script for this. I know fair amount of python scripting.
| [
"Invoke a SWIG wrapper to make C functions look like Python functions. Take a look at this example. \n"
] | [
1
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003210435_ctypes_python.txt |
Q:
How to get pynotify to display line breaks and HTML?
How can I make pynotify display line breaks and HTML in the notifications?
Here is what I got:
>>> import pynotify
>>> n = pynotify.Notification ("This is a test.\n\nAnd this too!",
"","notification-message-im")
>>> n.show()
Contrary to what is expected, there is no line-break between the two sentences. (At least not on Ubuntu 10.04)
Also, is there a way to include simple HTML in the notifications, like <b>, <br>, or <i>?
A:
You can use '\n' in message body but not in summary.
>>> n = pynotify.Notification("summary", "body\n next line", "dialog-warning")
>>> n.show()
| How to get pynotify to display line breaks and HTML? | How can I make pynotify display line breaks and HTML in the notifications?
Here is what I got:
>>> import pynotify
>>> n = pynotify.Notification ("This is a test.\n\nAnd this too!",
"","notification-message-im")
>>> n.show()
Contrary to what is expected, there is no line-break between the two sentences. (At least not on Ubuntu 10.04)
Also, is there a way to include simple HTML in the notifications, like <b>, <br>, or <i>?
| [
"You can use '\\n' in message body but not in summary. \n>>> n = pynotify.Notification(\"summary\", \"body\\n next line\", \"dialog-warning\")\n>>> n.show()\n\n"
] | [
2
] | [] | [] | [
"pynotify",
"python",
"ubuntu"
] | stackoverflow_0003209981_pynotify_python_ubuntu.txt |
Q:
centos libjpeg error _imaging
I am trying to get my libjpeg working with python with little or no luck.
I have followed this tutorial to get it up and running http://blaolao.com/setting-up-django-mysql-mysql-python-pil-etc on my 10.6, worked like a charm
now that I am looking at getting this onto my server I am getting stuck
I believe it already had libjpeg 6.x.x on their and wanted to update
I downloaded libjpeg 8b,
extracted ./configured sudo make sudo
make install
worked fine and actually says
jpeg support available
then ran the Imaging installation, also worked fine.
now when i go into python and execute
import _imaging
i get a traceback of
Traceback (most recent call last):
File "", line 1, in
ImportError: libjpeg.so.8: cannot open shared object file: No such file or directory
Can anybody help?
A:
I managed to CentOS working with a lot of the defaults.
I now have a running django app, with mod_wsgi, git, django-south, django-imagekit, rackspace CDN, apache, mysql etc.
I've found that there were so many people having issues with this, however all the answers only took me half-way, I have tracked what I have done and published all this info into a handy tutorial.
http://appelfreelance.com/2010/07/a-working-copy-django-pil-imaging-libjpeg-mysql-git-apache-mod_wsgi-easy_install-pip-django-imagekit-cdn-storage-on-centos-5-4/
| centos libjpeg error _imaging | I am trying to get my libjpeg working with python with little or no luck.
I have followed this tutorial to get it up and running http://blaolao.com/setting-up-django-mysql-mysql-python-pil-etc on my 10.6, worked like a charm
now that I am looking at getting this onto my server I am getting stuck
I believe it already had libjpeg 6.x.x on their and wanted to update
I downloaded libjpeg 8b,
extracted ./configured sudo make sudo
make install
worked fine and actually says
jpeg support available
then ran the Imaging installation, also worked fine.
now when i go into python and execute
import _imaging
i get a traceback of
Traceback (most recent call last):
File "", line 1, in
ImportError: libjpeg.so.8: cannot open shared object file: No such file or directory
Can anybody help?
| [
"I managed to CentOS working with a lot of the defaults.\nI now have a running django app, with mod_wsgi, git, django-south, django-imagekit, rackspace CDN, apache, mysql etc.\nI've found that there were so many people having issues with this, however all the answers only took me half-way, I have tracked what I hav... | [
2
] | [] | [] | [
"libjpeg",
"python",
"python_imaging_library"
] | stackoverflow_0003037381_libjpeg_python_python_imaging_library.txt |
Q:
Python No Longers Sees MySQLdb
Whilst writing working my way through a list of scripts I need to write I started using the MySQLdb package. This all worked fine in my Terminal by doing a simple python at the command line then import MySQLdb. However after about 30 minutes I figured I better move this to Eclipse incase I start making some stupid mistakes... Eclipse for some reason cannot see MySQLdb:
Unresolved import: MySQLdb
MySQLdb Found at:
I then proceeded to scratch my head and go back to the terminal to see if it works... and low and behold:
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/MySQLdb/__init__.py", line 19, in <module>
File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/_mysql.py", line 7, in <module>
File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/_mysql.py", line 3, in __bootstrap__
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 2553, in <module>
working_set = WorkingSet()
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 384, in __init__
self.add_entry(entry)
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 399, in add_entry
for dist in find_distributions(entry, True):
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1647, in find_on_path
path_item = _normalize_cached(path_item)
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1794, in _normalize_cached
_cache[filename] = result = normalize_path(filename)
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1788, in normalize_path
return os.path.normcase(os.path.realpath(filename))
File "/usr/lib/python2.6/posixpath.py", line 364, in realpath
return abspath(filename)
File "/usr/lib/python2.6/posixpath.py", line 337, in abspath
path = join(os.getcwd(), path)
OSError: [Errno 2] No such file or directory
>>>
I am utterly confused as to what I have done. Could someone please point out my stupid mistake and any solutions? I have yet to master all this python installing/egg business. Cheers
A:
Could this be the answer; your current path does no longer exist: http://bugs.python.org/issue6612 thus os.getcwd () doesn't work.
| Python No Longers Sees MySQLdb | Whilst writing working my way through a list of scripts I need to write I started using the MySQLdb package. This all worked fine in my Terminal by doing a simple python at the command line then import MySQLdb. However after about 30 minutes I figured I better move this to Eclipse incase I start making some stupid mistakes... Eclipse for some reason cannot see MySQLdb:
Unresolved import: MySQLdb
MySQLdb Found at:
I then proceeded to scratch my head and go back to the terminal to see if it works... and low and behold:
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/MySQLdb/__init__.py", line 19, in <module>
File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/_mysql.py", line 7, in <module>
File "/usr/local/lib/python2.6/dist-packages/MySQL_python-1.2.3c1-py2.6-linux-i686.egg/_mysql.py", line 3, in __bootstrap__
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 2553, in <module>
working_set = WorkingSet()
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 384, in __init__
self.add_entry(entry)
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 399, in add_entry
for dist in find_distributions(entry, True):
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1647, in find_on_path
path_item = _normalize_cached(path_item)
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1794, in _normalize_cached
_cache[filename] = result = normalize_path(filename)
File "/usr/lib/python2.6/dist-packages/pkg_resources.py", line 1788, in normalize_path
return os.path.normcase(os.path.realpath(filename))
File "/usr/lib/python2.6/posixpath.py", line 364, in realpath
return abspath(filename)
File "/usr/lib/python2.6/posixpath.py", line 337, in abspath
path = join(os.getcwd(), path)
OSError: [Errno 2] No such file or directory
>>>
I am utterly confused as to what I have done. Could someone please point out my stupid mistake and any solutions? I have yet to master all this python installing/egg business. Cheers
| [
"Could this be the answer; your current path does no longer exist: http://bugs.python.org/issue6612 thus os.getcwd () doesn't work.\n"
] | [
2
] | [] | [] | [
"import",
"mysql",
"python"
] | stackoverflow_0003203698_import_mysql_python.txt |
Q:
python file read
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
fo.read(3)
fo.close()
file_open("file_ro.py")
I expect above program to return first 3 bytes from file . But it returns nothing. When I ran these in interactive python command prompt - I get expected output!
A:
While your own answer prints the bytes read, it doesn't return them, so you won't be able to use the result somewhere else. Also, there's room for a few other improvements:
file_open isn't a good name for the function, since it reads and returns bytes from a file rather than just opening it.
You should make sure that you close the file even if fo.read(3) fails. You can use the with statement to solve this issue.
The modified code could look something like this:
def read_first_bytes(filename):
with open(filename,'r') as f:
return f.read(3)
Usage:
>>> print read_first_bytes("file.py")
A:
fo.read() returns the data that was read and you never assign it to anything. You are talking about 'output', but your code isn't supposed to output anything. Are you trying to print those three bytes? In that case you are looking for something like
f = open('file_ro.py', 'r')
print f.read(3)
You are getting the 'expected output' in the interactive prompt, because it prints the result of the evaluation if it is not assigned anywhere (and if it is not None?), just like in the fo.read(3) line. Or something along those lines, - maybe someone can explain it better.
A:
import sys
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
read_data=fo.read(3)
fo.close()
print read_data
file_open("file.py")
| python file read | def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
fo.read(3)
fo.close()
file_open("file_ro.py")
I expect above program to return first 3 bytes from file . But it returns nothing. When I ran these in interactive python command prompt - I get expected output!
| [
"While your own answer prints the bytes read, it doesn't return them, so you won't be able to use the result somewhere else. Also, there's room for a few other improvements:\n\nfile_open isn't a good name for the function, since it reads and returns bytes from a file rather than just opening it.\nYou should make s... | [
7,
1,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003211031_file_python.txt |
Q:
No module named django.core
I'm following the step by step guide here and I hit an error at the "Create Django Project" step when I try the command;
django-admin.py startproject myproject
The error:
Traceback (most recent call last):
File "/usr/local/bin/django-admin.py",
line 2, in
from django.core import management ImportError: No module named
django.core
Running on Ubuntu Server with Python 2.6.
I'm sure it's a really simple error, and something do with Python paths, but I'm a Linux newbie. Thanks!
A:
Thanks to Daniel Roseman's comment, I investigated and found my symlink was broken. Just had to recreate that and it worked nicely.
| No module named django.core | I'm following the step by step guide here and I hit an error at the "Create Django Project" step when I try the command;
django-admin.py startproject myproject
The error:
Traceback (most recent call last):
File "/usr/local/bin/django-admin.py",
line 2, in
from django.core import management ImportError: No module named
django.core
Running on Ubuntu Server with Python 2.6.
I'm sure it's a really simple error, and something do with Python paths, but I'm a Linux newbie. Thanks!
| [
"Thanks to Daniel Roseman's comment, I investigated and found my symlink was broken. Just had to recreate that and it worked nicely.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003211110_django_python.txt |
Q:
How to deploy a python webapp with dependencies using virtualenv?
I'm looking for a way to automate deployment of web applications written in Python to a server. I would like to use virtualenv to have a clean environment for this application.
However, I am wondering how to manage dependencies when deploying to the server ?
In development, I have a virtualenv in which I install external libraries using pip, so I am looking for a way to automatically install those dependencies in production ?
Thank you for your time
A:
With pip you can create a requirements file:
$ pip freeze > requirements.txt
Then in the server to install all of these you do:
$ pip install -r requirements.txt
And with this (if the server has everything necessary to build the binary packages that you might have included) all is ready.
| How to deploy a python webapp with dependencies using virtualenv? | I'm looking for a way to automate deployment of web applications written in Python to a server. I would like to use virtualenv to have a clean environment for this application.
However, I am wondering how to manage dependencies when deploying to the server ?
In development, I have a virtualenv in which I install external libraries using pip, so I am looking for a way to automatically install those dependencies in production ?
Thank you for your time
| [
"With pip you can create a requirements file:\n$ pip freeze > requirements.txt\n\nThen in the server to install all of these you do:\n$ pip install -r requirements.txt\n\nAnd with this (if the server has everything necessary to build the binary packages that you might have included) all is ready.\n"
] | [
9
] | [] | [] | [
"python",
"virtualenv"
] | stackoverflow_0003211080_python_virtualenv.txt |
Q:
How should I share and store data in a small multithreaded python application?
I'm writing a small multithreaded client-side python application that contains a small webserver (only serves page to the localhost) and a daemon. The webserver loads and puts data into a persistent "datastore", and the daemon processes this data, modifies it and adds some more. It should also takes care of the synchronization with the disk.
I'd like to avoid complicated external things like SQL or other databases as much as possible.
What are good and simple ways to design the datastore? Bonus points if your solution uses only standard python.
A:
What you're seeking isn't too Python specific, because AFAIU you want to communicate between two different processes, which are only incidentally written in Python. If this indeed is your problem, you should look for a general solution, not a Python-specific one.
I think that a simple No-SQL key-value datastore such as Redis, for example, could be a very nice solution for your situation. Contrary to "complicated" using a tool designed specifically for such a purpose will actually make your code simpler.
If you insist on a Python-only solution, then consider using the Python bindings for SQLite which come pre-installed with Python. An SQLite DB can be concurrently used by two processes in a safe manner, as long as your semantics of data access are well defined (i.e. problems you have to solve anyway, the tool nonwithstanding).
| How should I share and store data in a small multithreaded python application? | I'm writing a small multithreaded client-side python application that contains a small webserver (only serves page to the localhost) and a daemon. The webserver loads and puts data into a persistent "datastore", and the daemon processes this data, modifies it and adds some more. It should also takes care of the synchronization with the disk.
I'd like to avoid complicated external things like SQL or other databases as much as possible.
What are good and simple ways to design the datastore? Bonus points if your solution uses only standard python.
| [
"What you're seeking isn't too Python specific, because AFAIU you want to communicate between two different processes, which are only incidentally written in Python. If this indeed is your problem, you should look for a general solution, not a Python-specific one.\nI think that a simple No-SQL key-value datastore s... | [
0
] | [] | [] | [
"concurrency",
"datastore",
"multithreading",
"python"
] | stackoverflow_0003211379_concurrency_datastore_multithreading_python.txt |
Q:
SQLAlchemy and Elixir?
I have been using django ORM, it's nice and very easy, but this time I'm doing a desktop app and I found SQLAlchemy, but I'm not sure to use it with Elixir. What do you think? is it really useful?
A:
I'm not sure you need Elixir any more. With the Declarative mapper, you can create classes that map to your tables similar to the way it's done by Elixir. Is there a specific elixir feature that you're looking for?
A:
Use SQLAlchemy with Elixir if you need Django-style (or Rails-style) simple object-relational mapping. If you need complex mapping like concrete table inheritance or dictionary-based collections, I recommend you to use just SQLAlchemy with sqlalchemy.ext.declarative.
| SQLAlchemy and Elixir? | I have been using django ORM, it's nice and very easy, but this time I'm doing a desktop app and I found SQLAlchemy, but I'm not sure to use it with Elixir. What do you think? is it really useful?
| [
"I'm not sure you need Elixir any more. With the Declarative mapper, you can create classes that map to your tables similar to the way it's done by Elixir. Is there a specific elixir feature that you're looking for? \n",
"Use SQLAlchemy with Elixir if you need Django-style (or Rails-style) simple object-relationa... | [
11,
5
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0003112014_python_python_elixir_sqlalchemy.txt |
Q:
Google application engine Datastore - any alternatives to aggregate functions and group by?
As is mentioned in the doc for google app engine, it does not support group by and other aggregation functions. Is there any alternatives to implement the same functionality?
I am working on a project where I need it on urgent basis, being a large database its not efficient to iterate the result set and then perform the logic.
Please suggest.
Thanks in advance.
A:
The best way is to populate the summaries (aggregates) at the time of write. This way your reads will be faster, since they just read - at the cost of writes which will have to update the summaries if its likely to be effected by the write.
Hopefully you will be reading more often than writing/updating summaries.
| Google application engine Datastore - any alternatives to aggregate functions and group by? | As is mentioned in the doc for google app engine, it does not support group by and other aggregation functions. Is there any alternatives to implement the same functionality?
I am working on a project where I need it on urgent basis, being a large database its not efficient to iterate the result set and then perform the logic.
Please suggest.
Thanks in advance.
| [
"The best way is to populate the summaries (aggregates) at the time of write. This way your reads will be faster, since they just read - at the cost of writes which will have to update the summaries if its likely to be effected by the write. \nHopefully you will be reading more often than writing/updating summaries... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003210577_google_app_engine_python.txt |
Q:
Can iterator be restored and can its value/status be assigned?
I have below snippet which use the generator to give the new ID
...
def __init__(self, id_generator = None):
if id_generator is None: id_generator = 0
if isinstance(id_generator, int):
import itertools
self._generator = itertools.count(id_generator)
else:
self._generator = id_generator
...
id = self._generator.next() #0
id = self._generator.next() #1
id = self._generator.next() #2
id = self._generator.next() #3
my question is, suppose I have an existing id number such as int(99) need to be accepted
during the runtime and need the _generator to generate the ID starting from 99.
looks like:
0
1
2
3
4
<---- new id number 99 be given in somehow
99
100
101
how I can feed it back to the _generator?
Just use self._generator = itertools.count(99) or there's a better way?
More, sucn a confuse can be to be more generalized: how I can memo/assign a generator's
status/value if it is not for an int type?
Thanks!
A:
No, generators just generate items, you cannot set or save their state once they have been created. So self._generator = itertools.count(99) is really the best way to go.
What you can do is duplicate a generator with itertools.tee, which memorizes the output sequence from the first iterable and passes it to the new generators.
You can also write a generator that draws from a source you can change:
class counter(object):
def __init__(self, current=0):
self.current = current
def __iter__(self):
def iter():
while True:
yield self.current
self.current += 1 #
return iter()
def set(self,x):
self.current = x
s = counter()
t = iter(s)
print t.next() # 0
s.set(20)
print t.next() # 21
| Can iterator be restored and can its value/status be assigned? | I have below snippet which use the generator to give the new ID
...
def __init__(self, id_generator = None):
if id_generator is None: id_generator = 0
if isinstance(id_generator, int):
import itertools
self._generator = itertools.count(id_generator)
else:
self._generator = id_generator
...
id = self._generator.next() #0
id = self._generator.next() #1
id = self._generator.next() #2
id = self._generator.next() #3
my question is, suppose I have an existing id number such as int(99) need to be accepted
during the runtime and need the _generator to generate the ID starting from 99.
looks like:
0
1
2
3
4
<---- new id number 99 be given in somehow
99
100
101
how I can feed it back to the _generator?
Just use self._generator = itertools.count(99) or there's a better way?
More, sucn a confuse can be to be more generalized: how I can memo/assign a generator's
status/value if it is not for an int type?
Thanks!
| [
"No, generators just generate items, you cannot set or save their state once they have been created. So self._generator = itertools.count(99) is really the best way to go.\nWhat you can do is duplicate a generator with itertools.tee, which memorizes the output sequence from the first iterable and passes it to the n... | [
1
] | [] | [] | [
"duplicates",
"generator",
"iterator",
"python",
"restore"
] | stackoverflow_0003211478_duplicates_generator_iterator_python_restore.txt |
Q:
PyGTK Window not hiding when told to
In my PyGTK application, I am asking a user to find a file so that operations can be performed on it. The application asks the user for the file, and relays that filename to the necessary methods. Unfortunately, when calling the gtk.dispose() method on that dialog, it just hangs there until the method being called upon to perform the file-IO is complete. I have even tried placing the file manipulations inside of another thread, but that did not have any effect.
My indented purpose is to have the program display a dialog box to the user informing them that the file they selected for manipulation is taking place. With the current implementation, the dialog appears after the gtk.FileChooserDialog is disposed.
Below is my code:
def performFileManipulation(self, widget, data=None):
# Create the file chooser dialog:
dialog = gtk.FileChooserDialog("Open..", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialog.set_default_response(gtk.RESPONSE_OK)
# Display the file selector and obtain the response back
response = dialog.run()
# If the user selected a file, then get the filename:
if response == gtk.RESPONSE_OK:
dataLocation = dialog.get_filename()
# If the file was not chosen, then just close the window:
else:
print "Closed, no files selected" # Just for now
########## Problem Area ##########
# The dialog is told to get destroyed, however, it hangs here in an
# unresponsive state until the the file-manipulations performed in a new thread
# below are completed. Then, the status dialog (declared below) is displayed.
dialog.destroy() # Close the dialog.
## Show a dialog informing the user that the file manipulation is taking place:
statusDialog = gtk.Dialog("Performing File Operations...", parent=None, flags=0, buttons=None)
statusLabel = gtk.Label("Performing File Operations.\nPlease wait...")
statusLabel.set_justify(gtk.JUSTIFY_CENTER)
statusLabel.show()
statusDialog.vbox.pack_start(statusLabel, True, True, 0)
statusDialog.set_default_size(350, 150)
statusDialog.show()
# Create the thread to perform the file conversion:
errorBucket = Queue.Queue() # Make a bucket to catch all errors that may occur:
theFileOperationThread = doStuffToTheFile(dataLocation, errorBucket) # Declare the thread object.
## Perform the file operations:
theFileOperationThread.start() # Begin the thread
# Check on the thread. See if it's still running:
while True:
theFileOperationThread.join(0.1)
if theFileOperationThread.isAlive():
continue
else:
break
# Check if there was an error in the bucket:
try:
errorFound = errorBucket.get(False)
# If no errors were found, then the copy was successful!
except Queue.Empty:
pass
# There was an error in the bucket! Alert the user
else:
print errorFound
statusDialog.destroy()
Please note that this code is not yet completed, for instance, it does not yet properly handle the user not selecting a file and canceling the operation.
EDIT: Upon further investigation, there appears to be a threading issue with PyGTK. The problem is occurring in the while True loop. I replaced that code with a time.sleep(15), and similarly, the file select dialog will pause. This is quite odd behavior, and everything should operate inside of a different thread. I guess the question now is to find out how to place the File Selection dialog inside of it's own thread.
A:
There's probably no need to perform the file operations in a separate thread, since you're not really doing anything in this thread while the file operations are running -- just busy-waiting. And that brings me to why the code doesn't work: GUI updates are processed within the GTK main loop. But the whole time while you're waiting for the file thread to finish, the GTK main loop isn't executing, because it's stuck waiting for your performFileManipulation function to end.
What you need to do is perform iterations of the GTK main loop during your while True loop. That looks like this:
while True:
theFileOperationThread.join(0.1)
if theFileOperationThread.isAlive():
while gtk.events_pending():
gtk.main_iteration(block=False)
else:
break
But again, I would consider just doing the file operations in this thread, it seems redundant to start another thread and then do nothing while it's running.
A:
Mixing threads and GTK apps (from what I recall) tends to produce weird results.
The problem is that even though you call gtk.dispose, you're probably calling the methods directly, which blocks the next iteration of gtk.mainloop.
What you need to do is create another function to do the file processing and call it from a callback funciton:
def doFileStuff(filename):
with open(filename, 'r') as f:
for line in f:
#do something
return False # On success
And then change this function:
def performFileManipulation(self, widget, data=None):
# Create the file chooser dialog:
dialog = gtk.FileChooserDialog("Open..",
None,
gtk.FILE_CHOOSER_ACTION_OPEN,
(gtk.STOCK_CANCEL,
gtk.RESPONSE_CANCEL,
gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialog.set_default_response(gtk.RESPONSE_OK)
# Display the file selector and obtain the response back
response = dialog.run()
# If the user selected a file, then get the filename:
if response == gtk.RESPONSE_OK:
dataLocation = dialog.get_filename()
# If the file was not chosen, then just close the window:
else:
print "Closed, no files selected" # Just for now
# You'll need to import gobject
gobject.timeout_add(100, doFileStuff, dataLocation)
That should at least let you close the dialog, and I think it will launch the file processing stuff in the background. If not it will at least give you somewhere to launch your new thread from.
HTH
| PyGTK Window not hiding when told to | In my PyGTK application, I am asking a user to find a file so that operations can be performed on it. The application asks the user for the file, and relays that filename to the necessary methods. Unfortunately, when calling the gtk.dispose() method on that dialog, it just hangs there until the method being called upon to perform the file-IO is complete. I have even tried placing the file manipulations inside of another thread, but that did not have any effect.
My indented purpose is to have the program display a dialog box to the user informing them that the file they selected for manipulation is taking place. With the current implementation, the dialog appears after the gtk.FileChooserDialog is disposed.
Below is my code:
def performFileManipulation(self, widget, data=None):
# Create the file chooser dialog:
dialog = gtk.FileChooserDialog("Open..", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
dialog.set_default_response(gtk.RESPONSE_OK)
# Display the file selector and obtain the response back
response = dialog.run()
# If the user selected a file, then get the filename:
if response == gtk.RESPONSE_OK:
dataLocation = dialog.get_filename()
# If the file was not chosen, then just close the window:
else:
print "Closed, no files selected" # Just for now
########## Problem Area ##########
# The dialog is told to get destroyed, however, it hangs here in an
# unresponsive state until the the file-manipulations performed in a new thread
# below are completed. Then, the status dialog (declared below) is displayed.
dialog.destroy() # Close the dialog.
## Show a dialog informing the user that the file manipulation is taking place:
statusDialog = gtk.Dialog("Performing File Operations...", parent=None, flags=0, buttons=None)
statusLabel = gtk.Label("Performing File Operations.\nPlease wait...")
statusLabel.set_justify(gtk.JUSTIFY_CENTER)
statusLabel.show()
statusDialog.vbox.pack_start(statusLabel, True, True, 0)
statusDialog.set_default_size(350, 150)
statusDialog.show()
# Create the thread to perform the file conversion:
errorBucket = Queue.Queue() # Make a bucket to catch all errors that may occur:
theFileOperationThread = doStuffToTheFile(dataLocation, errorBucket) # Declare the thread object.
## Perform the file operations:
theFileOperationThread.start() # Begin the thread
# Check on the thread. See if it's still running:
while True:
theFileOperationThread.join(0.1)
if theFileOperationThread.isAlive():
continue
else:
break
# Check if there was an error in the bucket:
try:
errorFound = errorBucket.get(False)
# If no errors were found, then the copy was successful!
except Queue.Empty:
pass
# There was an error in the bucket! Alert the user
else:
print errorFound
statusDialog.destroy()
Please note that this code is not yet completed, for instance, it does not yet properly handle the user not selecting a file and canceling the operation.
EDIT: Upon further investigation, there appears to be a threading issue with PyGTK. The problem is occurring in the while True loop. I replaced that code with a time.sleep(15), and similarly, the file select dialog will pause. This is quite odd behavior, and everything should operate inside of a different thread. I guess the question now is to find out how to place the File Selection dialog inside of it's own thread.
| [
"There's probably no need to perform the file operations in a separate thread, since you're not really doing anything in this thread while the file operations are running -- just busy-waiting. And that brings me to why the code doesn't work: GUI updates are processed within the GTK main loop. But the whole time whi... | [
2,
1
] | [] | [] | [
"gtk",
"linux",
"multithreading",
"pygtk",
"python"
] | stackoverflow_0003203783_gtk_linux_multithreading_pygtk_python.txt |
Q:
append a particular column from a csv file to another using python
I'll explain my whole problem:
I have 2 csv files:
project-table.csv (has about 50 columns)
interaction-matrix.csv (has about 45 columns)
I want to append the string in col[43] from project-table.csv with string in col[1] of interaction-matrix.csv with a dot(.) in between both the strings
next,
interaction-matrix.csv has a set of headers..
its 1st col will now have the appended string after doing what I've mentioned above
all other remaining columns have only 0's and 1's
I'm supposed to extract only those columns with 1's from this interaction-matrix.csv and copy it to a new csv file... (with the first column intact)
this is the code i ve come up with...
I'm getting an error with the keepcols line...
import csv
reader=csv.reader(open("project-table.csv","r"))
writer=csv.writer(open("output.csv","w"),delimiter=" ")
for data in reader:
name1=data[1].strip()+'.'+data[43].strip()
writer.writerow((name1, None))
reader=csv.DictReader(open("interaction-matrix.csv","r"),[])
allrows = list(reader)
keepcols = [c for c in allrows[0] if all(r[c] != '0' for r in allrows)]
print keepcols
writer=csv.DictWriter(open("output1.csv","w"),fieldnames='keepcols',extrasaction='ignore')
writer.writerows(allrows)
this is the error i get:
Traceback (most recent call last):
File "prg1.py", line 23, in ?
keepcols = [c for c in allrows[0] if all([r[c] != '0' for r in allrows])]
NameError: name 'all' is not defined
project table and interaction-matrix both have the same data in their respective 1st columns .. so i just appended col[43] of prj-table to col[1] of the same table itself...
A:
Edit your question to show what error message are you getting. Update: NameError probably means you are using an (older) version of Python (which one?) without all() or (you have used all as a variable name AND are not showing the exact code that you ran)
Note: open both files in binary mode ("rb" and "wb") respectively.
You say "I want to append the string in col[43] from project-table.csv with string in col[1] of interaction-matrix.csv with a dot(.) in between both the strings" HOWEVER you are using col[2] (not col[1]) of project-table.csv (not interaction-matrix.csv, which you haven't opened at that stage).
| append a particular column from a csv file to another using python | I'll explain my whole problem:
I have 2 csv files:
project-table.csv (has about 50 columns)
interaction-matrix.csv (has about 45 columns)
I want to append the string in col[43] from project-table.csv with string in col[1] of interaction-matrix.csv with a dot(.) in between both the strings
next,
interaction-matrix.csv has a set of headers..
its 1st col will now have the appended string after doing what I've mentioned above
all other remaining columns have only 0's and 1's
I'm supposed to extract only those columns with 1's from this interaction-matrix.csv and copy it to a new csv file... (with the first column intact)
this is the code i ve come up with...
I'm getting an error with the keepcols line...
import csv
reader=csv.reader(open("project-table.csv","r"))
writer=csv.writer(open("output.csv","w"),delimiter=" ")
for data in reader:
name1=data[1].strip()+'.'+data[43].strip()
writer.writerow((name1, None))
reader=csv.DictReader(open("interaction-matrix.csv","r"),[])
allrows = list(reader)
keepcols = [c for c in allrows[0] if all(r[c] != '0' for r in allrows)]
print keepcols
writer=csv.DictWriter(open("output1.csv","w"),fieldnames='keepcols',extrasaction='ignore')
writer.writerows(allrows)
this is the error i get:
Traceback (most recent call last):
File "prg1.py", line 23, in ?
keepcols = [c for c in allrows[0] if all([r[c] != '0' for r in allrows])]
NameError: name 'all' is not defined
project table and interaction-matrix both have the same data in their respective 1st columns .. so i just appended col[43] of prj-table to col[1] of the same table itself...
| [
"Edit your question to show what error message are you getting. Update: NameError probably means you are using an (older) version of Python (which one?) without all() or (you have used all as a variable name AND are not showing the exact code that you ran)\nNote: open both files in binary mode (\"rb\" and \"wb\") r... | [
1
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003211570_csv_python.txt |
Q:
How to guarantee two related models get saved?
How do I guarantee data only gets saved when the related objects are both filled with data?
class A(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
class B(A):
author = models.CharField(max_length=255)
url = models.URLField()
I insert data by accessing model B:
b = B()
b.title = 'title'
b.slug = 'slug'
b.author = 'author'
b.url = 'www.google.com'
b.save()
If an error occurs in model B then model A still gets saved.
How can I prevent model A from saving when model B doesn't get saved?
A:
Depending on your environment, transactions are probably the answer
A:
Database transactions?
A:
Override B's save method (as described in the docs), have it call A's full_clean method. if it raises an exception, just don't save the model.
| How to guarantee two related models get saved? | How do I guarantee data only gets saved when the related objects are both filled with data?
class A(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
class B(A):
author = models.CharField(max_length=255)
url = models.URLField()
I insert data by accessing model B:
b = B()
b.title = 'title'
b.slug = 'slug'
b.author = 'author'
b.url = 'www.google.com'
b.save()
If an error occurs in model B then model A still gets saved.
How can I prevent model A from saving when model B doesn't get saved?
| [
"Depending on your environment, transactions are probably the answer\n",
"Database transactions?\n",
"Override B's save method (as described in the docs), have it call A's full_clean method. if it raises an exception, just don't save the model.\n"
] | [
3,
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003211976_django_django_models_python.txt |
Q:
sparse file usage in python
I'm creating sparse files in python as follows:
>>> f = open('testfile', 'ab')
>>> f.truncate(1024000)
>>> f.close()
when the file is done, it takes up 0 disk space, but its inode size is set to my truncated value (1000K):
igor47@piglet:~/test$ ls -lh testfile
-rw-r--r-- 1 igor47 igor47 1000K 2010-07-09 04:02 testfile
igor47@piglet:~/test$ du -hs testfile
0 testfile
How do I get the file's real space usage (allocated size) inside python? The stat call returns the file's apparent size, and I have no idea how else to get the real usage other than to read the entire file (it may become quite large)
>>> os.stat('testfile').st_size
1024000
A:
>>> os.stat('testfile').st_blocks*512
0
Tadaa :)
st_blocks is the number of 512-byte blocks actually allocated to the file. Note that st_blocks is not guaranteed to be present in all operating systems, but those that support sparse files generally do.
| sparse file usage in python | I'm creating sparse files in python as follows:
>>> f = open('testfile', 'ab')
>>> f.truncate(1024000)
>>> f.close()
when the file is done, it takes up 0 disk space, but its inode size is set to my truncated value (1000K):
igor47@piglet:~/test$ ls -lh testfile
-rw-r--r-- 1 igor47 igor47 1000K 2010-07-09 04:02 testfile
igor47@piglet:~/test$ du -hs testfile
0 testfile
How do I get the file's real space usage (allocated size) inside python? The stat call returns the file's apparent size, and I have no idea how else to get the real usage other than to read the entire file (it may become quite large)
>>> os.stat('testfile').st_size
1024000
| [
">>> os.stat('testfile').st_blocks*512\n0\n\nTadaa :)\nst_blocks is the number of 512-byte blocks actually allocated to the file. Note that st_blocks is not guaranteed to be present in all operating systems, but those that support sparse files generally do.\n"
] | [
18
] | [] | [] | [
"file",
"filesize",
"macos",
"python",
"sparse_file"
] | stackoverflow_0003211999_file_filesize_macos_python_sparse_file.txt |
Q:
Windows Server cannot execute a py2exe-generated app
A simple python script needs to run on a windows server with no python installed.
I used py2exe, which generated a healthy dist subdirectory, with script.exe that runs fine on the local machine.
However, when I run it on the server (Windows Server 2003 R2), it produces this:
The system cannot execute the specified program.
and ERRORLEVEL is 9020.
Any ideas?
A:
For py2exe to work, you have to include the correct version of the Microsoft C runtime DLL with your application.
For Python2.6, this is MSVCR90.dll version 9.0.21022.8, which can be obtained from the Microsoft Visual C++ 2008 Redistributable Package:
http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en
NOTE that the SP1 of this installer contains a different version of the DLL, and will not work.
I spent a while earlier this year explaining this carefully in the py2exe tutorial, so I'll just link to that:
http://www.py2exe.org/index.cgi/Tutorial#Step5
A:
It could be missing some required DLLs. Try using depends.exe to identify what might be missing. It's probably an msvc-something-something.dll
A:
I did not find the cause to the problem, but using python 2.5 with py2exe on the same script worked fine on the server.
I guess there is something wrong with py2exe under 2.6.
A:
Because Python 2.6 is built against Visual Studio 2008, the target machine must also have the Visual Studio 2008 libraries, available from the Visual C++ 2008 Redistributable package.
I confirmed that on a clean build of Windows XP or Server 2003 (neither of which have the Visual Studio 2008 redistributable), a Python 2.6 py2exe executable will fail with the aforementioned error, but after installing the redistributable package, the executable runs normally.
| Windows Server cannot execute a py2exe-generated app | A simple python script needs to run on a windows server with no python installed.
I used py2exe, which generated a healthy dist subdirectory, with script.exe that runs fine on the local machine.
However, when I run it on the server (Windows Server 2003 R2), it produces this:
The system cannot execute the specified program.
and ERRORLEVEL is 9020.
Any ideas?
| [
"For py2exe to work, you have to include the correct version of the Microsoft C runtime DLL with your application.\nFor Python2.6, this is MSVCR90.dll version 9.0.21022.8, which can be obtained from the Microsoft Visual C++ 2008 Redistributable Package:\nhttp://www.microsoft.com/downloads/details.aspx?FamilyID=9b2d... | [
6,
2,
1,
1
] | [] | [] | [
"py2exe",
"python",
"windows"
] | stackoverflow_0001959811_py2exe_python_windows.txt |
Q:
how to find target path of link if the file is a link file
how to find if the file is a link file, and find the path of the target file (actual file pointed by the link file)
A:
os.path.islink (is it a link?) and os.path.realpath (get ultimate pointed to path, regardless of whether it's a link).
If os.path.islink is True, and you only want to follow the first link, use os.readlink.
A:
Use os.lstat(), then inspect the st_mode field.
| how to find target path of link if the file is a link file | how to find if the file is a link file, and find the path of the target file (actual file pointed by the link file)
| [
"os.path.islink (is it a link?) and os.path.realpath (get ultimate pointed to path, regardless of whether it's a link).\nIf os.path.islink is True, and you only want to follow the first link, use os.readlink.\n",
"Use os.lstat(), then inspect the st_mode field.\n"
] | [
33,
0
] | [] | [] | [
"file",
"hyperlink",
"python"
] | stackoverflow_0003212712_file_hyperlink_python.txt |
Q:
generating equation representations in python/on the web
Is it possible to take something like x^2+5 and have it generate this: http://imgur.com/Muq2X.gif
I'll be using Python so anything based in Python would work, but I'm open to other solutions such as latex output.
A:
Sympy can output LaTeX code and MathML, from there you can create images or other forms of display, depending on what exactly you need. You'll find some methods for that in this old StackOverflow question.
In theory, MathML would be ideal to display equations in a browser, but not all browsers support MathML.
A:
You might take a look at this LaTeX module for Python: http://www.pytex.org/
A:
May be you need SVGMath, it is pure python and converts MathML expressions to SVG.
| generating equation representations in python/on the web | Is it possible to take something like x^2+5 and have it generate this: http://imgur.com/Muq2X.gif
I'll be using Python so anything based in Python would work, but I'm open to other solutions such as latex output.
| [
"Sympy can output LaTeX code and MathML, from there you can create images or other forms of display, depending on what exactly you need. You'll find some methods for that in this old StackOverflow question.\nIn theory, MathML would be ideal to display equations in a browser, but not all browsers support MathML.\n",... | [
3,
2,
1
] | [] | [] | [
"equations",
"latex",
"math",
"python"
] | stackoverflow_0003212367_equations_latex_math_python.txt |
Q:
wx.CreateStatusBar() without the resize handle
I am creating a wx.Frame that cannot be resized.
How do I disable the size grip at the right side of a status bar?
Quoting http://docs.wxwidgets.org/2.6/wx_wxstatusbar.html#wxstatusbar :
Window styles
wxST_SIZEGRIP -- On Windows 95, displays a gripper at right-hand side of the status bar.
Translating to wxPython, it should read wx.ST_SIZEGRIP. Here is my code:
import wx
class Frame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
style=wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX),
pos=(20, 20))
self.createStatusBar()
self.Show()
def createStatusBar(self):
statusBar = self.CreateStatusBar()
statusBar.SetWindowStyle(statusBar.GetWindowStyle() ^ wx.ST_SIZEGRIP)
if __name__ == '__main__':
app = wx.PySimpleApp(False)
frame = Frame(parent=None, title="Any title")
app.MainLoop()
Unfortunately, the size grip is still there. Any ideas on how to make it disappear?
A:
Instead of setting style later, set it at creation time e.g.
statusBar = self.CreateStatusBar(style=0)
You may try other styles for statusbar if they exist.
| wx.CreateStatusBar() without the resize handle | I am creating a wx.Frame that cannot be resized.
How do I disable the size grip at the right side of a status bar?
Quoting http://docs.wxwidgets.org/2.6/wx_wxstatusbar.html#wxstatusbar :
Window styles
wxST_SIZEGRIP -- On Windows 95, displays a gripper at right-hand side of the status bar.
Translating to wxPython, it should read wx.ST_SIZEGRIP. Here is my code:
import wx
class Frame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent=parent, id=wx.ID_ANY, title=title,
style=wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX),
pos=(20, 20))
self.createStatusBar()
self.Show()
def createStatusBar(self):
statusBar = self.CreateStatusBar()
statusBar.SetWindowStyle(statusBar.GetWindowStyle() ^ wx.ST_SIZEGRIP)
if __name__ == '__main__':
app = wx.PySimpleApp(False)
frame = Frame(parent=None, title="Any title")
app.MainLoop()
Unfortunately, the size grip is still there. Any ideas on how to make it disappear?
| [
"Instead of setting style later, set it at creation time e.g.\nstatusBar = self.CreateStatusBar(style=0)\n\nYou may try other styles for statusbar if they exist.\n"
] | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003211615_python_wxpython.txt |
Q:
python.exe is getting crashed at time of frame close
I am making an application using wxpython in which i have imported some modules and added the some widgets but when i am closing the application window ie Frame(wxFrame) python.exe getting crashed and showing the following message "python.exe get encountered a problem and need to be close... Tell microsoft donttell smt smt".
My app is working fine but this msg is coming while closing the app there is no message coming why its occur.
Should i do something like deleting the wxwindows or bitmap of wxpython (i think some handle or some obj of wxpython/python like dict or list are in memory so manually i shd delete that, its my perception only may be wrong or right) if i am right then what thing of wxpython shd be deleted manually so this message shd not be appear.
Any help really appreciable.
Thanks in advance!
A:
Start debugging it, and see where it crashes. If you are not familiar with pdb or such debugger try print statements to pinpoint the location where it crashes, once you are sure what code crashes may be we can help then.
| python.exe is getting crashed at time of frame close | I am making an application using wxpython in which i have imported some modules and added the some widgets but when i am closing the application window ie Frame(wxFrame) python.exe getting crashed and showing the following message "python.exe get encountered a problem and need to be close... Tell microsoft donttell smt smt".
My app is working fine but this msg is coming while closing the app there is no message coming why its occur.
Should i do something like deleting the wxwindows or bitmap of wxpython (i think some handle or some obj of wxpython/python like dict or list are in memory so manually i shd delete that, its my perception only may be wrong or right) if i am right then what thing of wxpython shd be deleted manually so this message shd not be appear.
Any help really appreciable.
Thanks in advance!
| [
"Start debugging it, and see where it crashes. If you are not familiar with pdb or such debugger try print statements to pinpoint the location where it crashes, once you are sure what code crashes may be we can help then.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003211613_python.txt |
Q:
conditionally including queries in an advanced query in zope
I'm building a quite thorough searching mechanism for a zope site. There are lots of different ways of searching, and because it might want to search for multiple values on the same index (and match all of them) I need to do it using AdvanceQuery. I've built my queries like this:
if self.text():
text_query = And()
for t in self.text():
text_query.addSubquery(Eq('SearchableText',t))
if self.sector()
sector_query = And()
for s in self.sector()
sector_query.addSubquery(Eq('sector',s))
if self.region():
region_query = Eq('region',self.region())
if self.role():
role_query = Eq('role',self.role())
self.text() etc. are defined elsewhere and will return False if the query doesn't exist, and self.text() and self.sector() always produce a list even if there is only a single value so no worries there.
I also know how to do the last bit e.g.
return self.context.portal_catalog.evalAdvancedQuery(query)
What I cannot figure out is how to stitch it together to define 'query'. If I do something like this it breaks if not all of them are present:
query = text_query & sector_query & region_query & role_query
Bear in mind this probably isn't the complete list of variables to search using so where looking at hundreds of possible combinations. How can I define 'query' conditionally so it doesn't break?
A:
As I said in the comment, using the &= within the if statement seems to do the trick
| conditionally including queries in an advanced query in zope | I'm building a quite thorough searching mechanism for a zope site. There are lots of different ways of searching, and because it might want to search for multiple values on the same index (and match all of them) I need to do it using AdvanceQuery. I've built my queries like this:
if self.text():
text_query = And()
for t in self.text():
text_query.addSubquery(Eq('SearchableText',t))
if self.sector()
sector_query = And()
for s in self.sector()
sector_query.addSubquery(Eq('sector',s))
if self.region():
region_query = Eq('region',self.region())
if self.role():
role_query = Eq('role',self.role())
self.text() etc. are defined elsewhere and will return False if the query doesn't exist, and self.text() and self.sector() always produce a list even if there is only a single value so no worries there.
I also know how to do the last bit e.g.
return self.context.portal_catalog.evalAdvancedQuery(query)
What I cannot figure out is how to stitch it together to define 'query'. If I do something like this it breaks if not all of them are present:
query = text_query & sector_query & region_query & role_query
Bear in mind this probably isn't the complete list of variables to search using so where looking at hundreds of possible combinations. How can I define 'query' conditionally so it doesn't break?
| [
"As I said in the comment, using the &= within the if statement seems to do the trick\n"
] | [
0
] | [] | [] | [
"python",
"zope"
] | stackoverflow_0003212303_python_zope.txt |
Q:
Numpy transpose multiplication problem
I tried to find the eigenvalues of a matrix multiplied by its transpose but I couldn't do it using numpy.
testmatrix = numpy.array([[1,2],[3,4],[5,6],[7,8]])
prod = testmatrix * testmatrix.T
print eig(prod)
I expected to get the following result for the product:
5 11 17 23
11 25 39 53
17 39 61 83
23 53 83 113
and eigenvalues:
0.0000
0.0000
0.3929
203.6071
Instead I got ValueError: shape mismatch: objects cannot be broadcast to a single shape when multiplying testmatrix with its transpose.
This works (the multiplication, not the code) in MatLab but I need to use it in a python application.
Can someone tell me what I'm doing wrong?
A:
You might find this tutorial useful since you know MATLAB.
Also, try multiplying testmatrix with the dot() function, i.e. numpy.dot(testmatrix,testmatrix.T)
Apparently numpy.dot is used between arrays for matrix multiplication! The * operator is for element-wise multiplication (.* in MATLAB).
A:
You're using element-wise multiplication - the * operator on two Numpy matrices is equivalent to the .* operator in Matlab. Use
prod = numpy.dot(testmatrix, testmatrix.T)
| Numpy transpose multiplication problem | I tried to find the eigenvalues of a matrix multiplied by its transpose but I couldn't do it using numpy.
testmatrix = numpy.array([[1,2],[3,4],[5,6],[7,8]])
prod = testmatrix * testmatrix.T
print eig(prod)
I expected to get the following result for the product:
5 11 17 23
11 25 39 53
17 39 61 83
23 53 83 113
and eigenvalues:
0.0000
0.0000
0.3929
203.6071
Instead I got ValueError: shape mismatch: objects cannot be broadcast to a single shape when multiplying testmatrix with its transpose.
This works (the multiplication, not the code) in MatLab but I need to use it in a python application.
Can someone tell me what I'm doing wrong?
| [
"You might find this tutorial useful since you know MATLAB.\nAlso, try multiplying testmatrix with the dot() function, i.e. numpy.dot(testmatrix,testmatrix.T)\nApparently numpy.dot is used between arrays for matrix multiplication! The * operator is for element-wise multiplication (.* in MATLAB).\n",
"You're using... | [
27,
8
] | [] | [] | [
"eigenvalue",
"numpy",
"python",
"scipy"
] | stackoverflow_0003213105_eigenvalue_numpy_python_scipy.txt |
Q:
Django: ImportError: No module named ?z?
Hi I am trying to deploy a django app with uwsgi. I keep getting Import Errors that look like this:
ImportError: No module named ?z?
-or-
ImportError: No module named ?j?
-or-
ImportError: No module named `?6
So basically the output of the module seems like gibberish and I am unable to figure out the problem. Does anybody have an idea what the problem could be?
A:
Seems like you have missed a comma in the settings.INSTALLED_APPS, after the app name. Go, check!
| Django: ImportError: No module named ?z? | Hi I am trying to deploy a django app with uwsgi. I keep getting Import Errors that look like this:
ImportError: No module named ?z?
-or-
ImportError: No module named ?j?
-or-
ImportError: No module named `?6
So basically the output of the module seems like gibberish and I am unable to figure out the problem. Does anybody have an idea what the problem could be?
| [
"Seems like you have missed a comma in the settings.INSTALLED_APPS, after the app name. Go, check!\n"
] | [
1
] | [] | [] | [
"django",
"importerror",
"python",
"uwsgi"
] | stackoverflow_0003212396_django_importerror_python_uwsgi.txt |
Q:
Case-insensitive query that supports multiple search words
I'm trying to perform a case-insensitive query. I would generally use __icontains, but since it doesn't support the .split() method, I'm stuck to using __in instead:
def search(request):
query = request.GET.get('q', '')
query = query.lower()
product_results = []
category_results = []
if query:
product_results = Product.objects.filter(Q(title__in=query.split())|
Q(brand__in=query.split())|
Q(description__in=query).split())
category_results = Category.objects.filter(title__in=query.split())
My problem is that the object fields usually have a the first letter capitalized, so an all lowercase query always returns negative.
Anyway around this?
A:
I have solved this problem by using exec to generate code from a string using icontains instead of in. I admit, it's sloppy and not elegant, and should be audited for security but it worked.
see the untested/pseudocode:
query = "product_results = Product.objects.filter("
for word in words:
query += "Q(title__icontains(word))|"
query += "Q(brand__icontains(word))|"
query += "Q(description__icontains(word))|"
query = query[:-1] # remove the trailing |
query += ")"
exec("product_results = "+query)
Again, this is probably not advisable, and I'm sure there's a better way to do this, but this fixed me up in a pinch once so I thought I would share. Also note, I don't use this code anymore as I've switched over to sqlalchemy which makes these kinds of dynamic queries a bit easier since it's "or" object accepts a list.
A:
thanks for sharing, i wrote up this quick hack, not elegant at all....
def search(request):
query = request.GET.get('q', '')
query = query.split()
product_results = []
category_results = []
if query:
for x in query:
product_results.extend(Product.objects.filter(Q(title__icontains=x)|
Q(brand__icontains=x)|
Q(description__icontains=x)))
category_results.extend(Category.objects.filter(title__icontains=x))
query = request.GET.get('q', '')
product_results = list(set(product_results))
category_results = list(set(category_results))
return render_to_response('search_results.html', {'query': query,
'product_results': product_results,
'category_results': category_results})
| Case-insensitive query that supports multiple search words | I'm trying to perform a case-insensitive query. I would generally use __icontains, but since it doesn't support the .split() method, I'm stuck to using __in instead:
def search(request):
query = request.GET.get('q', '')
query = query.lower()
product_results = []
category_results = []
if query:
product_results = Product.objects.filter(Q(title__in=query.split())|
Q(brand__in=query.split())|
Q(description__in=query).split())
category_results = Category.objects.filter(title__in=query.split())
My problem is that the object fields usually have a the first letter capitalized, so an all lowercase query always returns negative.
Anyway around this?
| [
"I have solved this problem by using exec to generate code from a string using icontains instead of in. I admit, it's sloppy and not elegant, and should be audited for security but it worked.\nsee the untested/pseudocode:\nquery = \"product_results = Product.objects.filter(\"\nfor word in words:\n query += \"Q... | [
1,
1
] | [] | [] | [
"case_sensitive",
"django",
"python"
] | stackoverflow_0003213284_case_sensitive_django_python.txt |
Q:
Many-to-many relationships in Google AppEngine - efficient?
I'm using Google Appengine to store a list of favorites, linking a Facebook UserID to one or more IDs from Bing. I need function calls returning the number of users who have favorited an item, and the number of times an item has been favorited (and by whom).
My question is, should I resolve this relationship into two tables for efficiency? If I have a table with columns for Facebook ID and Bing ID, I can easily use select queries for both of the functions above, however this will require that each row is searched in each query. The alternative is having two tables, one for each Facebook user's favorites and the other for each Bing item's favorited users, and using transactions to keep them in sync. The two tables option has the advantage of being able to use JSON or CSV in the database so that only one row needs to be fetched, and little manipulation needs to be done for an API.
Which option is better, in terms of efficiency and minimising cost?
Thanks,
Matt
A:
I don't think there's a hard and fast answer to questions like this. "Is this optimization worth it" always depends on many variables such as, is the lack of optimization actually a problem to start with? How much of a problem is it? What's the cost in terms of extra time and effort and risk of bugs of a more complex optimized implementation, relative to the benefits? What might be the extra costs of implementing the optimization later, such as data migration to a new schema?
| Many-to-many relationships in Google AppEngine - efficient? | I'm using Google Appengine to store a list of favorites, linking a Facebook UserID to one or more IDs from Bing. I need function calls returning the number of users who have favorited an item, and the number of times an item has been favorited (and by whom).
My question is, should I resolve this relationship into two tables for efficiency? If I have a table with columns for Facebook ID and Bing ID, I can easily use select queries for both of the functions above, however this will require that each row is searched in each query. The alternative is having two tables, one for each Facebook user's favorites and the other for each Bing item's favorited users, and using transactions to keep them in sync. The two tables option has the advantage of being able to use JSON or CSV in the database so that only one row needs to be fetched, and little manipulation needs to be done for an API.
Which option is better, in terms of efficiency and minimising cost?
Thanks,
Matt
| [
"I don't think there's a hard and fast answer to questions like this. \"Is this optimization worth it\" always depends on many variables such as, is the lack of optimization actually a problem to start with? How much of a problem is it? What's the cost in terms of extra time and effort and risk of bugs of a more co... | [
0
] | [] | [] | [
"google_app_engine",
"many_to_many",
"performance",
"python"
] | stackoverflow_0003210994_google_app_engine_many_to_many_performance_python.txt |
Q:
form.cleaned_data as a dictionary
Why when I call a function like this :
function(request, **form.cleaned_data)
I can send form's data as a dictionary, but when I try doing like this :
data = **form.cleaned_data
I'm getting error ?
A:
The ** trick only works when a dictionary is expanded in a function call; you can't use it outside of a function call.
| form.cleaned_data as a dictionary | Why when I call a function like this :
function(request, **form.cleaned_data)
I can send form's data as a dictionary, but when I try doing like this :
data = **form.cleaned_data
I'm getting error ?
| [
"The ** trick only works when a dictionary is expanded in a function call; you can't use it outside of a function call.\n"
] | [
2
] | [] | [] | [
"dictionary",
"django",
"django_forms",
"keyword_argument",
"python"
] | stackoverflow_0003213881_dictionary_django_django_forms_keyword_argument_python.txt |
Q:
Unknown Python Syntax
I've found the following syntax in a python file:
units = (
(100, 1 << 30, _('%.0f GB')),
(10, 1 << 30, _('%.1f GB')),
(1, 1 << 30, _('%.2f GB')),
(100, 1 << 20, _('%.0f MB')),
(10, 1 << 20, _('%.1f MB')),
(1, 1 << 20, _('%.2f MB')),
(100, 1 << 10, _('%.0f KB')),
(10, 1 << 10, _('%.1f KB')),
(1, 1 << 10, _('%.2f KB')),
(1, 1, _('%.0f bytes')),
)
Does anyone know for what this underscore stands for?
Thanks in advance.
A:
Underscore is a valid variable name, so you have to look at the context of your example code. Obviously the underscore is a method which has been defined somewhere else. Usually it's used for translation stuff or similar things.
A:
As said in other answers, _ is a valid name for a Python function. It's probable you will find _() used as translation function in some I18N packages.
A:
Look further up in the file. With some luck you'll find a statement like this:
from Language import _
Underscore is often used for i18n.
A:
As others have mentioned, the _ is a function. The usual convention is that it used for localisation and internationalisation
A:
The _ function is usually aliased to the GetText get function: http://docs.python.org/library/gettext.html
| Unknown Python Syntax | I've found the following syntax in a python file:
units = (
(100, 1 << 30, _('%.0f GB')),
(10, 1 << 30, _('%.1f GB')),
(1, 1 << 30, _('%.2f GB')),
(100, 1 << 20, _('%.0f MB')),
(10, 1 << 20, _('%.1f MB')),
(1, 1 << 20, _('%.2f MB')),
(100, 1 << 10, _('%.0f KB')),
(10, 1 << 10, _('%.1f KB')),
(1, 1 << 10, _('%.2f KB')),
(1, 1, _('%.0f bytes')),
)
Does anyone know for what this underscore stands for?
Thanks in advance.
| [
"Underscore is a valid variable name, so you have to look at the context of your example code. Obviously the underscore is a method which has been defined somewhere else. Usually it's used for translation stuff or similar things.\n",
"As said in other answers, _ is a valid name for a Python function. It's probabl... | [
4,
3,
3,
2,
0
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0003212819_python_syntax.txt |
Q:
How to retrieve a time stamp with the right formatting from a sql database using python
I want to retrieve a time stamp from a sql database with proper formatting. This is the partial code I am using:
import MySQLdb
def connectDB(self):
global cursor
DATABASE = MySQLdb.connect(
host = self.HOST,
user = self.USER,
passwd = self.PASS,
db = self.DB,
port = self.PORT,
ssl = self.SSL_SETTINGS
)
cursor = DATABASE.cursor()
def getLastReport(self):
sql = "SELECT timestamp FROM dataset Limit 0,1;"
self.connectDB()
cursor.execute(sql)
lastReport = cursor.fetchone()
return lastReport
and last report returns:
(datetime.datetime(2010, 7, 7, 19, 55),)
I want something like this:
2010-7-7 19:55
I know how to change this to a string and then reformat it but there should be an easy way to grab the time stamp so that it is already formatted. also how would one grab a float or int or string so that it is already formatted rather then trying to format it yourself. I am new to sql but there must be a way to grab data formatted correctly seeing that you have to declare the data types when creating the tables.
A:
You could use the DATE_FORMAT mysql function, though this is no easier than doing it on the Python side. In fact, it is much more limited, because fetchone returns a Python string instead of a datetime object.
sql = "SELECT DATE_FORMAT(timestamp,"%Y-%m-%d %k:%i") FROM dataset Limit 0,1;"
compared to
adate=datetime.datetime(2010, 7, 7, 19, 55)
adate.strftime('%Y-%m-%d %H:%M')
# 2010-07-07 19:55
| How to retrieve a time stamp with the right formatting from a sql database using python | I want to retrieve a time stamp from a sql database with proper formatting. This is the partial code I am using:
import MySQLdb
def connectDB(self):
global cursor
DATABASE = MySQLdb.connect(
host = self.HOST,
user = self.USER,
passwd = self.PASS,
db = self.DB,
port = self.PORT,
ssl = self.SSL_SETTINGS
)
cursor = DATABASE.cursor()
def getLastReport(self):
sql = "SELECT timestamp FROM dataset Limit 0,1;"
self.connectDB()
cursor.execute(sql)
lastReport = cursor.fetchone()
return lastReport
and last report returns:
(datetime.datetime(2010, 7, 7, 19, 55),)
I want something like this:
2010-7-7 19:55
I know how to change this to a string and then reformat it but there should be an easy way to grab the time stamp so that it is already formatted. also how would one grab a float or int or string so that it is already formatted rather then trying to format it yourself. I am new to sql but there must be a way to grab data formatted correctly seeing that you have to declare the data types when creating the tables.
| [
"You could use the DATE_FORMAT mysql function, though this is no easier than doing it on the Python side. In fact, it is much more limited, because fetchone returns a Python string instead of a datetime object.\nsql = \"SELECT DATE_FORMAT(timestamp,\"%Y-%m-%d %k:%i\") FROM dataset Limit 0,1;\"\n\ncompared to\nadat... | [
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003214345_mysql_python.txt |
Q:
Creating square subplots (of equal height and width) in matplotlib
When I run this code
from pylab import *
figure()
ax1 = subplot(121)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
I get two subplots which are "squished" in the X-dimension. How do I get these subplots such that the height of the Y-axis equals the width of the X-axis, for both subplots?
I am using matplotlib v.0.99.1.2 on Ubuntu 10.04.
Update 2010-07-08: Let's look at some things that don't work.
After Googling around all day, I thought that it might be related to auto-scaling. So I tried fiddling with that.
from pylab import *
figure()
ax1 = subplot(121, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
matplotlib insists on auto-scaling.
from pylab import *
figure()
ax1 = subplot(121, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
In this one, the data completely disappears. WTF, matplotlib? Just WTF?
Okay, well maybe if we fix the aspect ratio?
from pylab import *
figure()
ax1 = subplot(121, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
axes().set_aspect('equal')
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
This one causes the first subplot to disappear entirely. That's hilarious! Who came up with that one?
In all seriousness, now... should this really be such a hard thing to accomplish?
A:
Your problem in setting the aspect of the plots is coming in when you're using sharex and sharey.
One workaround is to just not used shared axes. For example, you could do this:
from pylab import *
figure()
subplot(121, aspect='equal')
plot([1, 2, 3], [1, 2, 3])
subplot(122, aspect='equal')
plot([1, 2, 3], [1, 2, 3])
show()
However, a better workaround is to change the "adjustable" keywarg... You want adjustable='box', but when you're using shared axes, it has to be adjustable='datalim' (and setting it back to 'box' gives an error).
However, there's a third option for adjustable to handle exactly this case: adjustable="box-forced".
For example:
from pylab import *
figure()
ax1 = subplot(121, aspect='equal', adjustable='box-forced')
plot([1, 2, 3], [1, 2, 3])
subplot(122, aspect='equal', adjustable='box-forced', sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
show()
Or in more modern style (note: this part of the answer wouldn't have worked in 2010):
import matplotlib.pyplot as plt
fig, axes = plt.subplots(ncols=2, sharex=True, sharey=True)
for ax in axes:
ax.plot([1, 2, 3], [1, 2, 3])
ax.set(adjustable='box-forced', aspect='equal')
plt.show()
Either way, you'll get something similar to:
A:
Give this a try:
from pylab import *
figure()
ax1 = subplot(121, autoscale_on=False, aspect='equal', xlim=[1,3], ylim=[1,3])
plot([1, 2, 3], [1, 2, 3])
##axes().set_aspect('equal')
ax2 = subplot(122, autoscale_on=False, aspect='equal', xlim=[1,3], ylim=[1,3])
plot([1, 2, 3], [1, 2, 3])
draw()
show()
I commented out the axes() line as that would create a new axes at an arbitrary location, rather than a pre-fabricated subplot with a calculated position.
Calling subplot actually creates an Axes instance, which means it can use the same properties as that of an Axes.
I hope this helps :)
| Creating square subplots (of equal height and width) in matplotlib | When I run this code
from pylab import *
figure()
ax1 = subplot(121)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
I get two subplots which are "squished" in the X-dimension. How do I get these subplots such that the height of the Y-axis equals the width of the X-axis, for both subplots?
I am using matplotlib v.0.99.1.2 on Ubuntu 10.04.
Update 2010-07-08: Let's look at some things that don't work.
After Googling around all day, I thought that it might be related to auto-scaling. So I tried fiddling with that.
from pylab import *
figure()
ax1 = subplot(121, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
matplotlib insists on auto-scaling.
from pylab import *
figure()
ax1 = subplot(121, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
In this one, the data completely disappears. WTF, matplotlib? Just WTF?
Okay, well maybe if we fix the aspect ratio?
from pylab import *
figure()
ax1 = subplot(121, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
axes().set_aspect('equal')
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
This one causes the first subplot to disappear entirely. That's hilarious! Who came up with that one?
In all seriousness, now... should this really be such a hard thing to accomplish?
| [
"Your problem in setting the aspect of the plots is coming in when you're using sharex and sharey. \nOne workaround is to just not used shared axes. For example, you could do this:\nfrom pylab import *\n\nfigure()\nsubplot(121, aspect='equal')\nplot([1, 2, 3], [1, 2, 3])\nsubplot(122, aspect='equal')\nplot([1, 2,... | [
25,
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0003207850_matplotlib_python.txt |
Q:
Python: Print in rows
Say I have a list
food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
How would I print the list in rows containing 4 columns, so it would look like:
apple pear tomato bean
carrot grape
A:
food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
for i in xrange(0, len(food_list), 4):
print '\t'.join(food_list[i:i+4])
A:
Try with this
food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
size = 4
g = (food_list[i:i+size] for i in xrange(0, len(food_list), size))
for i in g:
print i
A:
food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
index = 0
for each_food in food_list:
if index < 3:
print each_food,
index += 1
else:
print each_food
index = 0
| Python: Print in rows | Say I have a list
food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']
How would I print the list in rows containing 4 columns, so it would look like:
apple pear tomato bean
carrot grape
| [
"food_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']\nfor i in xrange(0, len(food_list), 4):\n print '\\t'.join(food_list[i:i+4])\n\n",
"Try with this\nfood_list = ['apple', 'pear', 'tomato', 'bean', 'carrot', 'grape']\nsize = 4\ng = (food_list[i:i+size] for i in xrange(0, len(food_list), size))... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003214926_python.txt |
Q:
Matplotlib autoscale
I need to get a plot that fits the data automatically using matplotlib. This is the code I was given:
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
....
lines = LineCollection(mpl.line_holder, colors=mpl.colorholder , linestyle='solid')
plt.axes().add_collection(lines)
plt.axes().set_aspect('equal', 'datalim')
plt.draw()
plt.show()
This creates a plot, however the window is always the same (0-~.8) no matter what the data is, even if all of the data is outside that window. The resulting window has no ability to zoom out, only in, so this is a major problem. I can't find anywhere where any kind of sizing is set, nor can II find details on what defaults are. I need the window to automatically fit the data, but I can't find any function that does it (for some reason, autoscale_on(True) doesn't do it). The data is highly variable, so setting hard limits is not an option. How can i get this to display properly?
A:
Not sure if this what you wanted, but I can change it if this was not what you were looking for.
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import pylab as p
fig = plt.figure()
pts1 = []
pts2 = []
for i in range(100):
pts1.append([i,i])
pts2.append([-i-3,-i])
lines = LineCollection([pts1,pts2], linestyles='solid')
subplt = fig.add_subplot(111,aspect='equal')
subplt.add_collection(lines)
subplt.autoscale_view(True,True,True)
p.show()
Hope that helps.
A:
Have a look at Eli Bendersky's Website, specifically this post. The example at the bottom of the post can be downloaded. It allows you to set whether the x axis will follow the plot or will remain static while the y axis changes with the data.
| Matplotlib autoscale | I need to get a plot that fits the data automatically using matplotlib. This is the code I was given:
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
....
lines = LineCollection(mpl.line_holder, colors=mpl.colorholder , linestyle='solid')
plt.axes().add_collection(lines)
plt.axes().set_aspect('equal', 'datalim')
plt.draw()
plt.show()
This creates a plot, however the window is always the same (0-~.8) no matter what the data is, even if all of the data is outside that window. The resulting window has no ability to zoom out, only in, so this is a major problem. I can't find anywhere where any kind of sizing is set, nor can II find details on what defaults are. I need the window to automatically fit the data, but I can't find any function that does it (for some reason, autoscale_on(True) doesn't do it). The data is highly variable, so setting hard limits is not an option. How can i get this to display properly?
| [
"Not sure if this what you wanted, but I can change it if this was not what you were looking for.\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\n\nimport pylab as p\n\nfig = plt.figure()\npts1 = []\npts2 = []\nfor i in range(100):\n pts1.append([i,i])\n pts2.append([-i-3,... | [
13,
1
] | [] | [] | [
"matplotlib",
"plot",
"python",
"visualization"
] | stackoverflow_0003214576_matplotlib_plot_python_visualization.txt |
Q:
lists and sublists
say i have an output of this, i think its a list
['', 'AB-a-b-c-d', 'BC-f-c-a-r', 'CD-i-s-r']
i want to make the following:
['',[AB,a,b,c,d],[BC,f,c,a,r],[CD,i,s,r]]
or
['',[AB,BC,CD],[a,b,c,d],[f,c,a,r],[i,s,r]]
A:
newlist = [item.split("-") for item in oldlist]
or (this works better because the empty string is kept as is)
newlist = []
for item in oldlist:
if not item:
newlist.append(item)
else:
newlist.append(item.split("-"))
A:
I'll try to point you in the right direction rather than solve your homework for you: Try split and some for loops.
| lists and sublists | say i have an output of this, i think its a list
['', 'AB-a-b-c-d', 'BC-f-c-a-r', 'CD-i-s-r']
i want to make the following:
['',[AB,a,b,c,d],[BC,f,c,a,r],[CD,i,s,r]]
or
['',[AB,BC,CD],[a,b,c,d],[f,c,a,r],[i,s,r]]
| [
"newlist = [item.split(\"-\") for item in oldlist]\n\nor (this works better because the empty string is kept as is)\nnewlist = []\nfor item in oldlist:\n if not item:\n newlist.append(item)\n else:\n newlist.append(item.split(\"-\"))\n\n",
"I'll try to point you in the right direction rather t... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003215045_python.txt |
Q:
How do I debug code that segfaults unless run through gdb?
That's a single threaded code.
In particular: ahocorasick Python extension module (easy_install ahocorasick).
I isolated the problem to a trivial example:
import ahocorasick
t = ahocorasick.KeywordTree()
t.add("a")
When I run it in gdb, all is fine, same happens when I enter these instructions into Python CLI. However, when I try to run the script regularily, I get a segfault.
To make it even weirder, the line that causes segfault (identified by core dump analysis) is a regular int incrementation (see the bottom of the function body).
I'm completely stuck by this moment, what can I do?
int
aho_corasick_addstring(aho_corasick_t *in, unsigned char *string, size_t n)
{
aho_corasick_t* g = in;
aho_corasick_state_t *state,*s = NULL;
int j = 0;
state = g->zerostate;
// As long as we have transitions follow them
while( j != n &&
(s = aho_corasick_goto_get(state,*(string+j))) != FAIL )
{
state = s;
++j;
}
if ( j == n ) {
/* dyoo: added so that if a keyword ends up in a prefix
of another, we still mark that as a match.*/
aho_corasick_output(s) = j;
return 0;
}
while( j != n )
{
// Create new state
if ( (s = xalloc(sizeof(aho_corasick_state_t))) == NULL )
return -1;
s->id = g->newstate++;
debug(printf("allocating state %d\n", s->id)); /* debug */
s->depth = state->depth + 1;
/* FIXME: check the error return value of
aho_corasick_goto_initialize. */
aho_corasick_goto_initialize(s);
// Create transition
aho_corasick_goto_set(state,*(string+j), s);
debug(printf("%u -> %c -> %u\n",state->id,*(string+j),s->id));
state = s;
aho_corasick_output(s) = 0;
aho_corasick_fail(s) = NULL;
++j; // <--- HERE!
}
aho_corasick_output(s) = n;
return 0;
}
A:
There are other tools you can use that will find faults that does not necessarily crash the program.
valgrind, electric fence, purify, coverity, and lint-like tools may be able to help you.
You might need to build your own python in some cases for this to be usable. Also, for memory corruption things, there is (or was, haven't built exetensions in a while) a possibility to let python use direct memory allocation instead of pythons own.
A:
Have you tried translating that while loop to a for loop? Maybe there's some subtle misunderstanding with the ++j that will disappear if you use something more intuitive.
| How do I debug code that segfaults unless run through gdb? | That's a single threaded code.
In particular: ahocorasick Python extension module (easy_install ahocorasick).
I isolated the problem to a trivial example:
import ahocorasick
t = ahocorasick.KeywordTree()
t.add("a")
When I run it in gdb, all is fine, same happens when I enter these instructions into Python CLI. However, when I try to run the script regularily, I get a segfault.
To make it even weirder, the line that causes segfault (identified by core dump analysis) is a regular int incrementation (see the bottom of the function body).
I'm completely stuck by this moment, what can I do?
int
aho_corasick_addstring(aho_corasick_t *in, unsigned char *string, size_t n)
{
aho_corasick_t* g = in;
aho_corasick_state_t *state,*s = NULL;
int j = 0;
state = g->zerostate;
// As long as we have transitions follow them
while( j != n &&
(s = aho_corasick_goto_get(state,*(string+j))) != FAIL )
{
state = s;
++j;
}
if ( j == n ) {
/* dyoo: added so that if a keyword ends up in a prefix
of another, we still mark that as a match.*/
aho_corasick_output(s) = j;
return 0;
}
while( j != n )
{
// Create new state
if ( (s = xalloc(sizeof(aho_corasick_state_t))) == NULL )
return -1;
s->id = g->newstate++;
debug(printf("allocating state %d\n", s->id)); /* debug */
s->depth = state->depth + 1;
/* FIXME: check the error return value of
aho_corasick_goto_initialize. */
aho_corasick_goto_initialize(s);
// Create transition
aho_corasick_goto_set(state,*(string+j), s);
debug(printf("%u -> %c -> %u\n",state->id,*(string+j),s->id));
state = s;
aho_corasick_output(s) = 0;
aho_corasick_fail(s) = NULL;
++j; // <--- HERE!
}
aho_corasick_output(s) = n;
return 0;
}
| [
"There are other tools you can use that will find faults that does not necessarily crash the program. \nvalgrind, electric fence, purify, coverity, and lint-like tools may be able to help you.\nYou might need to build your own python in some cases for this to be usable. Also, for memory corruption things, there is ... | [
2,
0
] | [] | [] | [
"gdb",
"python",
"segmentation_fault"
] | stackoverflow_0003211667_gdb_python_segmentation_fault.txt |
Q:
Admin site registering models
I have those models
class A(models.Model):
name = CharField(max_length=255)
class B(models.Model):
name = CharField(max_length=255)
relation = ForeignKey(A)
And I can register like this:
admin.site.register(A)
admin.site.register(B)
In /admin/ page, I can see A and B registered.
and "Add B" admin page, will display a combo with (+) icon to add a new "A".
What I want is only register "B" and keep the (+) icon, the problem is: if "A" is not registered this icon dissapears of this place :( so and I cant add "A" when adding "B"s
Thanks :)
A:
relation = ForeignKey(A, null=True, blank=True) will let you save a B without needing to link it to an A. Does that help?
| Admin site registering models | I have those models
class A(models.Model):
name = CharField(max_length=255)
class B(models.Model):
name = CharField(max_length=255)
relation = ForeignKey(A)
And I can register like this:
admin.site.register(A)
admin.site.register(B)
In /admin/ page, I can see A and B registered.
and "Add B" admin page, will display a combo with (+) icon to add a new "A".
What I want is only register "B" and keep the (+) icon, the problem is: if "A" is not registered this icon dissapears of this place :( so and I cant add "A" when adding "B"s
Thanks :)
| [
"relation = ForeignKey(A, null=True, blank=True) will let you save a B without needing to link it to an A. Does that help?\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003214429_django_django_models_python.txt |
Q:
Python AttributeError in using a member variable
I am having an issue with Python throwing an AttributeError on accessing a variable.
The code is below, redacted for clarity.
class mycollection(object):
"""
Collection of stuff.
"""
#"compile-time" define class variables.
__slots__ = ["stuff_list"]
def __init__(self):
self.stuff_list = []
def add_stuff(self, stuff):
self.stuff_list.append(stuff)
#later on..
collection = mycollection()
stuff = stuff()
collection.add_stuff(stuff)
Generating this error.
Traceback (most recent call last):
File "", line 210, in <module>
main()
File "", line 206, in main
thestuff = load_file(inputfile, filetype)
File "pyyft.py", line 121, in load_file
collection.add_stuff(stuff)
File "pyyft.py", line 55, in add_test
self.stuff_list.append(stuff)
AttributeError: stuff_list
Checking through the documentation, I don't understand why this error is arising.
A:
__ini__ should be __init__
A:
Wouldn't this be "more Pythonic"?
collection.stuff_list.append(test_stuff)
| Python AttributeError in using a member variable | I am having an issue with Python throwing an AttributeError on accessing a variable.
The code is below, redacted for clarity.
class mycollection(object):
"""
Collection of stuff.
"""
#"compile-time" define class variables.
__slots__ = ["stuff_list"]
def __init__(self):
self.stuff_list = []
def add_stuff(self, stuff):
self.stuff_list.append(stuff)
#later on..
collection = mycollection()
stuff = stuff()
collection.add_stuff(stuff)
Generating this error.
Traceback (most recent call last):
File "", line 210, in <module>
main()
File "", line 206, in main
thestuff = load_file(inputfile, filetype)
File "pyyft.py", line 121, in load_file
collection.add_stuff(stuff)
File "pyyft.py", line 55, in add_test
self.stuff_list.append(stuff)
AttributeError: stuff_list
Checking through the documentation, I don't understand why this error is arising.
| [
"__ini__ should be __init__\n",
"Wouldn't this be \"more Pythonic\"?\ncollection.stuff_list.append(test_stuff)\n"
] | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003215189_python.txt |
Q:
Elegant parsing of this? "a,b,c",d,"e,f"
I'm looking to parse these kinds of strings into lists in Python:
"a,b,c",d,"e,f" => ['a','b','c'] , ['d'] , ['e','f']
"a,b,c",d,e => ['a','b','c'] , ['d'] , ['e']
a,b,"c,d,e,f" => ['a'],['b'],['c','d','e','f']
a,"b,c,d",{x(a,b,c-d)} => ['a'],['b','c','d'],[('x',['a'],['b'],['c-d'])]
It nests, so I suspect regular expressions are out. All I can think of is to start counting quotes and brackets to parse it, but that seems horribly inelegant. Or perhaps to first match quotes and replace commas between them with somechar, then split on commas, until all the nesting is done, and finally re-split on somechar.
Any thoughts?
A:
So, here you are, your "honest python parser". Coding for you rather than answering the question, but I will be fine if you put it to use :-)
QUOTE = '"'
SEP = ',(){}"'
S_BRACKET = '{'
E_BRACKET = '}'
S_PAREN = '('
def parse_plain(string):
counter = 0
token = ""
while counter<len(string):
if string[counter] in SEP:
counter += 1
break
token += string[counter]
counter += 1
return counter, token
def parse_bracket(string):
counter = 1
fwd, token = parse_plain(string[counter:])
output = [token]
counter += fwd
fwd, token = parse_(string[counter:])
output += token
counter += fwd
output = [tuple(output)]
return counter, output
def parse_quote(string):
counter = 1
output = []
while counter<len(string):
if counter > 1 and string[counter - 1] == QUOTE:
counter += 1
break
fwd, token = parse_plain(string[counter:])
output.append(token)
counter += fwd
return counter, output
def parse_(string):
output = []
counter = 0
while counter < len(string):
if string[counter].isalpha():
fwd, token = parse_plain(string[counter:])
token = [token]
elif string[counter] == QUOTE:
fwd, token = parse_quote(string[counter:])
elif string[counter] == S_BRACKET:
fwd, token = parse_bracket(string[counter:])
elif string[counter] == E_BRACKET:
counter += 1
break
else:
counter += 1
continue
output.append(token)
counter += fwd
return counter, output
def parse(string):
return parse_(string)[1]
And testing the output:
>>> print parse('''"a,b,c",d,"e,f"''')
[['a', 'b', 'c'], ['d'], ['e', 'f']]
>>> print parse('''"a,b,c",d,e ''')
[['a', 'b', 'c'], ['d'], ['e ']]
>>> print parse('''a,b,"c,d,e,f"''')
[['a'], ['b'], ['c', 'd', 'e', 'f']]
>>> print parse('''a,"b,c,d",{x(a,b,c-d)}''')
[['a'], ['b', 'c', 'd'], [('x', ['a'], ['b'], ['c-d'])]]
>>> print parse('''{x(a,{y("b,c,d",e)})},z''')
[[('x', ['a'], [('y', ['b', 'c', 'd'], ['e'], ['z'])])]]
>>>
A:
One method I use in PHP for things like that is to replace the deepest point of a nested expression (in this case, "{x(a,b,c-d)}") with a symbol, like '¶1', then save its parsed value (being [('x',['a'],['b'],['c-d'])]) to the variable $nest1.
You now have the original string 'a,"b,c,d",{x(a,b,c-d)}' looking like 'a,"b,c,d",¶1' which is parsed just like the first three. Then simply search the resultant array for anything that begins with '¶' and replace it with its associated variable.
This method supports as many levels as you want, just keep looping/recursing until all the symbols are gone. For example,
'a,"b,c,d",{x(a,b,{y(j,k,l-m)},c-d)}'
'a,"b,c,d",{x(a,b,¶1,c-d)}' and $nest1=[('y',['j'],['k'],['l-m'])]
'a,"b,c,d",¶2' and $nest2=[('x',['a'],['b'],['¶1'],['c-d'])]
['a'],['b','c','d'],['¶2']
['a'],['b','c','d'],[('x',['a'],['b'],['¶1'],['c-d'])]
['a'],['b','c','d'],[('x',['a'],['b'],[('y',['j'],['k'],['l-m'])],['c-d'])]
For safety, you can even escape any instance of the ¶ that might have occurred in the string before making the change, then unescaping them as the last step, if you think it's necessary.
I don't know Python, so this might not work the same way as PHP. You may need to use an array instead of dynamic variables.
| Elegant parsing of this? "a,b,c",d,"e,f" | I'm looking to parse these kinds of strings into lists in Python:
"a,b,c",d,"e,f" => ['a','b','c'] , ['d'] , ['e','f']
"a,b,c",d,e => ['a','b','c'] , ['d'] , ['e']
a,b,"c,d,e,f" => ['a'],['b'],['c','d','e','f']
a,"b,c,d",{x(a,b,c-d)} => ['a'],['b','c','d'],[('x',['a'],['b'],['c-d'])]
It nests, so I suspect regular expressions are out. All I can think of is to start counting quotes and brackets to parse it, but that seems horribly inelegant. Or perhaps to first match quotes and replace commas between them with somechar, then split on commas, until all the nesting is done, and finally re-split on somechar.
Any thoughts?
| [
"So, here you are, your \"honest python parser\". Coding for you rather than answering the question, but I will be fine if you put it to use :-) \nQUOTE = '\"'\nSEP = ',(){}\"'\nS_BRACKET = '{'\nE_BRACKET = '}'\nS_PAREN = '('\n\ndef parse_plain(string):\n counter = 0\n token = \"\"\n while counter<len(str... | [
2,
0
] | [
"do you have quotes in strings? \nIf no - just replace control characters to make is compatible with JSON and use JSON parser\n",
"For the first three cases, you can just recursively apply the CSV reader:\nimport csv\n\ndef expand( st ):\n if \",\" not in st:\n return st\n return [ expand( col ) for ... | [
-1,
-1
] | [
"parsing",
"python",
"string"
] | stackoverflow_0003214256_parsing_python_string.txt |
Q:
Python and HTML table
I'm using the code below to print out rows containing 4 columns. How would I append each value in the list to a HTML table that also contains rows with four columns?
random_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']
for i in xrange(0, len(food_list), 4):
print '\t'.join(food_list[i:i+4])
A:
With some minor modification...
food_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']
for i in xrange(0, len(food_list), 4):
print '<tr><td>' + '</td><td>'.join(food_list[i:i+4]) + '</td></tr>'
This basically changes the delimiter to not be tab, but the table elements. Also, puts the open row and close row at the beginning and end.
A:
Slight variation on orangeoctopus' answer, using another join, rather than concatenation:
random_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']
print "<table>"
for i in xrange(0, len(random_list), 4):
print ''.join(['<tr><td>','</td><td>'.join(random_list[i:i+4]),'</td></tr>'])
print '</table>'
| Python and HTML table | I'm using the code below to print out rows containing 4 columns. How would I append each value in the list to a HTML table that also contains rows with four columns?
random_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']
for i in xrange(0, len(food_list), 4):
print '\t'.join(food_list[i:i+4])
| [
"With some minor modification...\nfood_list = ['car', 'plane', 'van', 'boat', 'ship', 'jet','shuttle']\nfor i in xrange(0, len(food_list), 4):\n print '<tr><td>' + '</td><td>'.join(food_list[i:i+4]) + '</td></tr>'\n\nThis basically changes the delimiter to not be tab, but the table elements. Also, puts the open ... | [
3,
1
] | [] | [] | [
"html",
"python"
] | stackoverflow_0003215260_html_python.txt |
Q:
subscripting a specific line from python's csv reader?
i'd like to be able to access specific lines of a csv file through the csv reader. For example, the fourth line. Is there a way to do this with python's csv reader module?
A:
You just have to parse all the CSV file, and then use normal sequencing indexing.
Otherwise, you can do something like this
def my_filter(csv_file, lines):
for line_number, line in enumerate(csv_file):
if line_number in lines:
yield line
my_file = open("file.csv")
my_reader = csv.reader(my_filter(my_file, (3,)))
Note that you can't avoid parsing the whole file, in a way or in another, because the lines are of variable lenght. The line count only advances when a '\n' is found, and it has to be found in a character by character basis.
Also, this filter won't work if you happen to have newline characters inside quotes in the csv file -- probably you are just better off parsing the whole file to a list, and retrieving the indexes from there, anyway:
my_file = open("file.csv")
my_reader = csv.reader(my_file)
my_line = list(my_reader)[3]
update
Most important: if you need random access to information which is far too large to fit in memory, just consider dumping it to a SQL database instead. It will spare one reinventing a lot of wheels.
| subscripting a specific line from python's csv reader? | i'd like to be able to access specific lines of a csv file through the csv reader. For example, the fourth line. Is there a way to do this with python's csv reader module?
| [
"You just have to parse all the CSV file, and then use normal sequencing indexing.\nOtherwise, you can do something like this\ndef my_filter(csv_file, lines):\n for line_number, line in enumerate(csv_file):\n if line_number in lines:\n yield line\n\nmy_file = open(\"file.csv\")\nmy_reader = csv.rea... | [
4
] | [] | [] | [
"csv",
"file_io",
"python"
] | stackoverflow_0003215347_csv_file_io_python.txt |
Q:
CGI download image after generating
I have a small python cgi script that accepts an image upload from the user, converts in into a different format, and saves the new file in a temp location. I would like it to then automatically prompt the user to download the converted file. I have tried:
# image conversion stuff....
print "Content-Type: image/eps\n" #have also tried application/postscript, and application/eps
print "Content-Disposition: attachment; filename=%s\n" % new_filename #have tried with and without this...
print open(converted_file_fullpath).read()
print
I have also tried:
print "Location: /path/to/tmp/location/%s" % new_filename
print
My browser either downloads script.cgi or script.cgi.ps. Any help is appreciated.
A:
I'm not sure, but have you tried separating actual data from headers by newline? EDIT: writing print "\n" outputs two newlines, so I think it should be written like that:
print "Content-Type: image/eps"
print "Content-Disposition: attachment; filename=%s" % new_filename
print
print open(converted_file_fullpath).read()
Assuming that new_filename has some reasonable value I can't see what is wrong here.
A:
Turns out, you can use the Location header for this, but it only worked for me with an absolute link. So,
print 'Location: http://example.com/path/to/tmp/location/%s' % new_filename
print
I know, the cgi spec says that relative links should work for internal redirects, but this is what worked for me...
| CGI download image after generating | I have a small python cgi script that accepts an image upload from the user, converts in into a different format, and saves the new file in a temp location. I would like it to then automatically prompt the user to download the converted file. I have tried:
# image conversion stuff....
print "Content-Type: image/eps\n" #have also tried application/postscript, and application/eps
print "Content-Disposition: attachment; filename=%s\n" % new_filename #have tried with and without this...
print open(converted_file_fullpath).read()
print
I have also tried:
print "Location: /path/to/tmp/location/%s" % new_filename
print
My browser either downloads script.cgi or script.cgi.ps. Any help is appreciated.
| [
"I'm not sure, but have you tried separating actual data from headers by newline? EDIT: writing print \"\\n\" outputs two newlines, so I think it should be written like that:\nprint \"Content-Type: image/eps\"\nprint \"Content-Disposition: attachment; filename=%s\" % new_filename\nprint\nprint open(converted_file_f... | [
0,
0
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0003215623_cgi_python.txt |
Q:
Paramiko SSH exec_command (shell script) returns before completion
I launch a shell script from a remote Linux machine using Paramiko. The shell script is launched and execute a command make -j8. However the exec_command returns before the completion of the make.
If I launch the script on the local machine it executes correctly.
Could someone explain me this behaviour?
A:
You need to wait for application to finish, exec_command isn't a blocking call.
print now(), "before call"
stdin, stdout, sterr = ssh.exec_command("sleep(10)")
print now(), "after call"
channel = stdout.channel
print now(), "before status"
status = channel.recv_exit_status()
print now(), "after status"
| Paramiko SSH exec_command (shell script) returns before completion | I launch a shell script from a remote Linux machine using Paramiko. The shell script is launched and execute a command make -j8. However the exec_command returns before the completion of the make.
If I launch the script on the local machine it executes correctly.
Could someone explain me this behaviour?
| [
"You need to wait for application to finish, exec_command isn't a blocking call.\nprint now(), \"before call\"\nstdin, stdout, sterr = ssh.exec_command(\"sleep(10)\")\nprint now(), \"after call\"\nchannel = stdout.channel\nprint now(), \"before status\"\nstatus = channel.recv_exit_status()\nprint now(), \"after sta... | [
28
] | [] | [] | [
"paramiko",
"python",
"ssh"
] | stackoverflow_0003215727_paramiko_python_ssh.txt |
Q:
Problem with deepcopy?
Source
from copy import deepcopy
class Field(object):
def __init__(self):
self.errors = []
class BaseForm(object):
pass
class MetaForm(type):
def __new__(cls, name, bases, attrs):
attrs['fields'] = dict([(name, deepcopy(attrs.pop(name))) for name, obj in attrs.items() if isinstance(obj, Field)])
return type.__new__(cls, name, bases, attrs)
class Form(BaseForm):
__metaclass__ = MetaForm
class MyForm(Form):
field1 = Field()
f1 = MyForm()
f1.fields['field1'].errors += ['error msg']
f2 = MyForm()
print f2.fields['field1'].errors
Output
['error msg']
Question
Why does it output that? I thought I cloned the errors list before modifying it, and that they shouldn't both refer to the same list?
A:
By setting the dict fields in the metaclass, you are creating a class attribute.
The __new__ method you defined is only run once -- on class creation.
Update
You should manipulate attrs in __new__ like you are, but name it something like _fields. Then create an __init__ method that performs a deepcopy into an attribute called fields.
A:
A more explicit solution:
from copy import deepcopy
class Field(object):
def __init__(self):
self.errors = []
class BaseForm(object):
def __init__(self):
self.fields = deepcopy(self.fields)
class MetaForm(type):
def __new__(cls, name, bases, attrs):
attrs['fields'] = dict([(name, attrs.pop(name)) for name, obj in attrs.items() if isinstance(obj, Field)])
return type.__new__(cls, name, bases, attrs)
class Form(BaseForm):
__metaclass__ = MetaForm
class MyForm(Form):
field1 = Field()
f1 = MyForm()
f1.fields['field1'].errors += ['error msg']
f2 = MyForm()
print f2.fields['field1'].errors
Just moved the deepcopy into BaseForm.__init__ instead, which actually is called each time a MyForm is instantiated.
| Problem with deepcopy? | Source
from copy import deepcopy
class Field(object):
def __init__(self):
self.errors = []
class BaseForm(object):
pass
class MetaForm(type):
def __new__(cls, name, bases, attrs):
attrs['fields'] = dict([(name, deepcopy(attrs.pop(name))) for name, obj in attrs.items() if isinstance(obj, Field)])
return type.__new__(cls, name, bases, attrs)
class Form(BaseForm):
__metaclass__ = MetaForm
class MyForm(Form):
field1 = Field()
f1 = MyForm()
f1.fields['field1'].errors += ['error msg']
f2 = MyForm()
print f2.fields['field1'].errors
Output
['error msg']
Question
Why does it output that? I thought I cloned the errors list before modifying it, and that they shouldn't both refer to the same list?
| [
"By setting the dict fields in the metaclass, you are creating a class attribute.\nThe __new__ method you defined is only run once -- on class creation. \nUpdate\nYou should manipulate attrs in __new__ like you are, but name it something like _fields. Then create an __init__ method that performs a deepcopy into an ... | [
2,
0
] | [] | [] | [
"deep_copy",
"python"
] | stackoverflow_0003215363_deep_copy_python.txt |
Q:
Arguments disappear from a dictionary when passed to a function
In my function I read user's data from session and store them in a dictionary. Next I'm sending it to 'register' function from registration.backend but the function somehow get's it empty and a KeyError is thrown. Where are my data gone ? The code from function calling 'register' function :
data = request.session['temp_data']
email = data['email']
logging.debug(email)
password1 = data['password1']
userdata = {'email': email, 'password1': password1}
logging.debug(userdata)
backend = request.session['backend']
logging.debug(backend)
user = backend.register(userdata)
And the register function (whole source here : http://bitbucket.org/ubernostrum/django-registration/src/tip/registration/backends/default/init.py ) :
class DefaultBackend(object):
def register(self, request, **kwargs):
logging.debug("backend.register")
logging.debug(kwargs)
username, email, password = kwargs['email'], kwargs['email'], kwargs['password1']
Debug after invoking them :
2010-07-09 19:24:35,020 DEBUG my@email.com
2010-07-09 19:24:35,020 DEBUG {'password1': u'a', 'email': u'my@email.com'}
2010-07-09 19:24:35,020 DEBUG <registration.backends.default.DefaultBackend object at 0x15c6090>
2010-07-09 19:24:35,021 DEBUG backend.register
2010-07-09 19:24:35,021 DEBUG {}
Why the data could be missing ? Am I doing something wrong ?
@edit for Silent-Ghost
register() takes exactly 2 arguments (3 given)
112. backend = request.session['backend']
113. logging.debug(backend)
114. user = backend.register(request, userdata)
A:
Judging by the method's signature:
you need to unpack your dictionary
you need to pass relevant request variable
Something like this:
backend.register(request, **userdata)
Assuming register is a method on backend instance.
A:
No need to mess with ** in register method. What you want to do is simply pass dictionary to register method:
user = backend.register( request, userdata ) # you need to pass request as definition says
def register( self, request, userdata ): # note lack of **
logging.debug("backend.register")
logging.debug( userdata ) # should work as expected
username, email, password = userdata['email'], userdata['email'], userdata['password1']
A:
this perfectly work
class Logging():
def debug(self,f):
print f
class DefaultBackend(object):
def register(self, request, **kwargs):
logging.debug("backend.register")
logging.debug(kwargs)
username, email, password = kwargs['email'], kwargs['email'], kwargs['password1']
class Request:
def __init__(self):
self.session = {}
request = Request()
logging=Logging()
request.session['temp_data']={'password1': u'a', 'email': u'my@email.com'}
request.session['backend']=DefaultBackend()
data = request.session['temp_data']
email = data['email']
logging.debug(email)
password1 = data['password1']
userdata = {'email': email, 'password1': password1}
logging.debug(userdata)
backend = request.session['backend']
logging.debug(backend)
user = backend.register(request,**userdata)
| Arguments disappear from a dictionary when passed to a function | In my function I read user's data from session and store them in a dictionary. Next I'm sending it to 'register' function from registration.backend but the function somehow get's it empty and a KeyError is thrown. Where are my data gone ? The code from function calling 'register' function :
data = request.session['temp_data']
email = data['email']
logging.debug(email)
password1 = data['password1']
userdata = {'email': email, 'password1': password1}
logging.debug(userdata)
backend = request.session['backend']
logging.debug(backend)
user = backend.register(userdata)
And the register function (whole source here : http://bitbucket.org/ubernostrum/django-registration/src/tip/registration/backends/default/init.py ) :
class DefaultBackend(object):
def register(self, request, **kwargs):
logging.debug("backend.register")
logging.debug(kwargs)
username, email, password = kwargs['email'], kwargs['email'], kwargs['password1']
Debug after invoking them :
2010-07-09 19:24:35,020 DEBUG my@email.com
2010-07-09 19:24:35,020 DEBUG {'password1': u'a', 'email': u'my@email.com'}
2010-07-09 19:24:35,020 DEBUG <registration.backends.default.DefaultBackend object at 0x15c6090>
2010-07-09 19:24:35,021 DEBUG backend.register
2010-07-09 19:24:35,021 DEBUG {}
Why the data could be missing ? Am I doing something wrong ?
@edit for Silent-Ghost
register() takes exactly 2 arguments (3 given)
112. backend = request.session['backend']
113. logging.debug(backend)
114. user = backend.register(request, userdata)
| [
"Judging by the method's signature:\n\nyou need to unpack your dictionary\nyou need to pass relevant request variable\n\nSomething like this:\nbackend.register(request, **userdata)\n\nAssuming register is a method on backend instance.\n",
"No need to mess with ** in register method. What you want to do is simply ... | [
3,
3,
0
] | [] | [] | [
"dictionary",
"django",
"python",
"session"
] | stackoverflow_0003215135_dictionary_django_python_session.txt |
Q:
ImportError: [libraryname].so: undefined symbol: [function name]
I'm extending my Python program with a C module that uses the GstPhotography interface for GStreamer. My C module compiles fine, but when I try running it from Python, I get this error:
$python Program.py
Traceback (most recent call last):
File "Program.py", line 10, in <module>
import MyPythonClass
File "/path/MyPythonClass.py", line 19, in <module>
import my_c_module
ImportError: /path/my_c_module.so: undefined symbol: gst_photography_get_type
I'm not really sure what this means, because I never use gst_photography_get_type in my_c_module.cpp--it's a function implemented in the GstPhotography source code.
A:
It means that you didn't link against enough libraries, either because it wasn't indicated in the pkgconfig file, or you didn't refer to the pkgconfig file in the first place.
| ImportError: [libraryname].so: undefined symbol: [function name] | I'm extending my Python program with a C module that uses the GstPhotography interface for GStreamer. My C module compiles fine, but when I try running it from Python, I get this error:
$python Program.py
Traceback (most recent call last):
File "Program.py", line 10, in <module>
import MyPythonClass
File "/path/MyPythonClass.py", line 19, in <module>
import my_c_module
ImportError: /path/my_c_module.so: undefined symbol: gst_photography_get_type
I'm not really sure what this means, because I never use gst_photography_get_type in my_c_module.cpp--it's a function implemented in the GstPhotography source code.
| [
"It means that you didn't link against enough libraries, either because it wasn't indicated in the pkgconfig file, or you didn't refer to the pkgconfig file in the first place.\n"
] | [
0
] | [] | [] | [
"extending",
"gstreamer",
"importerror",
"python"
] | stackoverflow_0003215818_extending_gstreamer_importerror_python.txt |
Q:
(Django) object is unsubscriptable
When I'm trying to create an extended user profile I'm getting UserProfile object is unsubscriptable. I've googled for solution, but 'your object is not a sequence' does not help here much. Here's the function I'm using, 'temp_data' is the data from my registration form :
def create_user(request):
data = request.session['temp_data']
email = data['email']
password1 = data['password1']
userdata = {'email': email, 'password1': password1}
backend = request.session['backend']
#create User
user = backend.register(request, userdata)
data = UserProfile(user=user)
data.is_active = False
data.first_name = data['first_name']
data.last_name = data['last_name']
(... rest of the fields ...)
data.save()
And my extended model :
class UserProfile(InheritedProfile):
def upload_path(self, field_attname):
filename = hashlib.md5(field_attname).hexdigest()[:4] + "_" + field_attname
return settings.MEDIA_ROOT + "/uploads/users/%s" % (filename,)
user = models.ForeignKey(User, unique=True, related_name='profile',)
first_name = models.CharField(_("Name"), max_length=50, blank=False,)
last_name = models.CharField(_("Surname"), max_length=50, blank=False,)
street = models.CharField(_("Street"), max_length=50, blank=False,)
code = models.CharField(_("Zip code"), max_length=6, blank=False,)
city = models.CharField(_("City"), max_length=50, blank=False,)
image = models.ImageField(_("Avatar"), upload_to=upload_path, blank=True,)
And the Traceback :
File "/home/rails/site-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/rails/registration/views.py" in register_new
115. data.first_name = data['first_name']
A:
data = UserProfile(user=user) rebinds data. It cannot be both the model and the session data at the same time.
| (Django) object is unsubscriptable | When I'm trying to create an extended user profile I'm getting UserProfile object is unsubscriptable. I've googled for solution, but 'your object is not a sequence' does not help here much. Here's the function I'm using, 'temp_data' is the data from my registration form :
def create_user(request):
data = request.session['temp_data']
email = data['email']
password1 = data['password1']
userdata = {'email': email, 'password1': password1}
backend = request.session['backend']
#create User
user = backend.register(request, userdata)
data = UserProfile(user=user)
data.is_active = False
data.first_name = data['first_name']
data.last_name = data['last_name']
(... rest of the fields ...)
data.save()
And my extended model :
class UserProfile(InheritedProfile):
def upload_path(self, field_attname):
filename = hashlib.md5(field_attname).hexdigest()[:4] + "_" + field_attname
return settings.MEDIA_ROOT + "/uploads/users/%s" % (filename,)
user = models.ForeignKey(User, unique=True, related_name='profile',)
first_name = models.CharField(_("Name"), max_length=50, blank=False,)
last_name = models.CharField(_("Surname"), max_length=50, blank=False,)
street = models.CharField(_("Street"), max_length=50, blank=False,)
code = models.CharField(_("Zip code"), max_length=6, blank=False,)
city = models.CharField(_("City"), max_length=50, blank=False,)
image = models.ImageField(_("Avatar"), upload_to=upload_path, blank=True,)
And the Traceback :
File "/home/rails/site-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/home/rails/registration/views.py" in register_new
115. data.first_name = data['first_name']
| [
"data = UserProfile(user=user) rebinds data. It cannot be both the model and the session data at the same time.\n"
] | [
3
] | [] | [] | [
"django",
"object",
"python"
] | stackoverflow_0003215891_django_object_python.txt |
Q:
Python and HTML: Not all arguments converted to a string
I writing HTML to a text file which is then read by the browser, but I get an error stating "not all arguments converted during string formatting"
But i can't see hwere im going wrong.
z.write('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>' % k)
A:
You're missing parentheses:
z.write(('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>') % k)
But it would be better not to mix concatenation and formatting. So consider:
'<td><a href=/Plone/query/species_strain?species=%(k)s>%(k)s</td>' % {'k': k}
You might want to generate HTML using a dedicated tool. Concatenating strings tends to lead to buggy and hard to parse HTML.
A:
You're using string concatenation in combination with substitution. Your substitution formatter %s is in the first string, but the % k applies to the last. You should do this:
'<td><a href=/Plone/query/species_strain?species=%s>%s</td>' % (k,k)
Or this:
('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>') % k
A:
You get wrong and combining + and string formatting through %. If k contains any %-sequence it would look like this:
'<td...species=%s>...%s...</td>' % k
You get two or more %-sequences and only one argument. You probably want this instead:
'...species=%s>%s</td>' % (k, k)
A:
% k must be after string with %s
z.write('<td><a href=/Plone/query/species_strain?species=%s>' % k +k+'</td>')
or better
z.write('<td><a href=/Plone/query/species_strain?species=%s>%s</td>' % (k, k))
| Python and HTML: Not all arguments converted to a string | I writing HTML to a text file which is then read by the browser, but I get an error stating "not all arguments converted during string formatting"
But i can't see hwere im going wrong.
z.write('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>' % k)
| [
"You're missing parentheses:\nz.write(('<td><a href=/Plone/query/species_strain?species=%s>'+k+'</td>') % k)\n\nBut it would be better not to mix concatenation and formatting. So consider:\n'<td><a href=/Plone/query/species_strain?species=%(k)s>%(k)s</td>' % {'k': k}\n\nYou might want to generate HTML using a dedi... | [
4,
4,
0,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0003216150_html_python.txt |
Q:
I'm running nginx with fastcgi, is that all I need to serve python apps also?
I'm running ubuntu with nginx with fastcgi, is that all I need to serve python apps also?
A:
You'll probably also need flup to bridge wsgi and fcgi. You obviously need Python, and whatever libraries your app depends upon. Likely need a database and the appropriate connectors as well, but that should all be in the documentation of whatever project you're trying to host (or framework you're using to write with).
Short answer: almost.
| I'm running nginx with fastcgi, is that all I need to serve python apps also? | I'm running ubuntu with nginx with fastcgi, is that all I need to serve python apps also?
| [
"You'll probably also need flup to bridge wsgi and fcgi. You obviously need Python, and whatever libraries your app depends upon. Likely need a database and the appropriate connectors as well, but that should all be in the documentation of whatever project you're trying to host (or framework you're using to write... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003216222_python.txt |
Q:
MySQLdb Handle Row Lock
I'm using MySQLdb and when I perform an UPDATE to a table row I sometimes get an infinite process hang.
At first I thought, maybe its COMMIT since the table is Innodb, but even with autocommit(True) and db.commit() after each update I still get the hang.
Is it possible there is a row lock and the query just fails to carry out? Is there a way to handle potential row locks or maybe even handle slow queries?
A:
Depending on your user privileges, you can execute SHOW PROCESSLIST or SELECT from information_schema.processlist while the UPDATE hangs to see if there is a contention issue with another query. Also do an EXPLAIN on a SELECT of the WHERE clause used in the UPDATE to see if you need to change the statement.
If it's a lock contention, then you should eventually encounter a Lock Wait Timeout (default = 50 sec, I believe). Otherwise, if you have timing constraints, you can make use of KILL QUERY and KILL CONNECTION to unblock the cursor execution.
| MySQLdb Handle Row Lock | I'm using MySQLdb and when I perform an UPDATE to a table row I sometimes get an infinite process hang.
At first I thought, maybe its COMMIT since the table is Innodb, but even with autocommit(True) and db.commit() after each update I still get the hang.
Is it possible there is a row lock and the query just fails to carry out? Is there a way to handle potential row locks or maybe even handle slow queries?
| [
"Depending on your user privileges, you can execute SHOW PROCESSLIST or SELECT from information_schema.processlist while the UPDATE hangs to see if there is a contention issue with another query. Also do an EXPLAIN on a SELECT of the WHERE clause used in the UPDATE to see if you need to change the statement. \nIf... | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003216027_mysql_python.txt |
Q:
Entering precise degrees into python
What is the standard way to enter degrees into python? My total station gives degrees in degree-minute-second format. I could write a function to convert this to a decimal degree but I would like to know if there is a common way to do this that I am unaware of.
-Chris
A:
Chris: not likely.
Since you need radians, anyway, this should od the trick:
import math
def radians_from_triple(deg, min=0, sec=0):
return math.radians(deg + min * 60 ** -1 + sec * 60 ** -2)
A:
Python uses radians, as a float.
There is no specific "angle" type, although you can write one yourself as needed.
| Entering precise degrees into python | What is the standard way to enter degrees into python? My total station gives degrees in degree-minute-second format. I could write a function to convert this to a decimal degree but I would like to know if there is a common way to do this that I am unaware of.
-Chris
| [
"Chris: not likely.\nSince you need radians, anyway, this should od the trick:\nimport math\ndef radians_from_triple(deg, min=0, sec=0):\n return math.radians(deg + min * 60 ** -1 + sec * 60 ** -2)\n\n",
"Python uses radians, as a float.\nThere is no specific \"angle\" type, although you can write one yourself... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003216654_python.txt |
Q:
lists and sublists
i use this code to split a data to make a list with three sublists.
to split when there is * or -. but it also reads the the \n\n *.. dont know why?
i dont want to read those? can some one tell me what im doing wrong?
this is the data
*Quote of the Day
-Education is the ability to listen to almost anything without losing your temper or your self-confidence - Robert Frost
-Education is what survives when what has been learned has been forgotten - B. F. Skinner
*Fact of the Day
-Fractals, an important part of chaos theory, are very useful in studying a huge amount of areas. They are present throughout nature, and so can be used to help predict many things in nature. They can also help simulate nature, as in graphics design for movies (animating clouds etc), or predict the actions of nature.
-According to a recent survey by Just-Eat, not everyone in The United Kingdom actually knows what the Scottish delicacy, haggis is. Of the 1,623 British people polled:\n\n * 18% of Brits thought haggis was some sort of Scottish animal.\n\n * 15% thought it was a Scottish musical instrument.\n\n * 4% thought it was a character from Harry Potter.\n\n * 41% didn't even know what Scotland's national dish was.\n\nWhile a small number of Scots admitted not knowing what haggis was either, they also discovered that 68% of Scots would like to see Haggis delivered as takeaway.
-With the growing concerns involving Facebook and its ever changing privacy settings, a few software developers have now engineered a website that allows users to trawl through the status updates of anyone who does not have the correct privacy settings to prevent it.\n\nNamed Openbook, the ultimate aim of the site is to further expose the problems with Facebook and its privacy settings to the general public, and show people just how easy it is to access this type of information about complete strangers. The site works as a search engine so it is easy to search terms such as 'don't tell anyone' or 'I hate my boss', and searches can also be narrowed down by gender.
*Pet of the Day
-Scottish Terrier
-Land Shark
-Hamster
-Tse Tse Fly
END
i use this code:
contents = open("data.dat").read()
data = contents.split('*') #split the data at the '*'
newlist = [item.split("-") for item in data if item]
to make that wrong similar to what i have to get list
A:
The "\n\n" is part of the input data, so it's preserved in python. Just add a strip() to remove it:
finallist = [item.strip() for item in newlist]
See the strip() docs: http://docs.python.org/library/stdtypes.html#str.strip
UPDATED FROM COMMENT:
finallist = [item.replace("\\n", "\n").strip() for item in newlist]
A:
open("data.dat").read() - reads all symbols in file, not only those you want.
If you don't need '\n' you can try content.replace("\n",""), or read lines (not whole content), and truncate the last symbol'\n' of each line.
A:
This is going to split any asterisk you have in the text as well.
Better implementation would be to do something like:
lines = []
for line in open("data.dat"):
if line.lstrip.startswith("*"):
lines.append([line.strip()]) # append a list with your line
elif line.lstrip.startswith("-"):
lines[-1].append(line.strip())
For more homework, research what's happening when you use the open() function in this way.
A:
The following solves your problem i believe:
result = [ [subitem.replace(r'\n\n', '\n') for subitem in item.split('\n-')]
for item in open('data.txt').read().split('\n*') ]
# now let's pretty print the result
for i in result:
print '***', i[0], '***'
for j in i[1:]:
print '\t--', j
print
Note I split on new-line + * or -, in this way it won't split on dashes inside the text. Also i replace the textual character sequence \ n \ n (r'\n\n') with a new line character '\n'. And the one-liner expression is list comprehension, a way to construct lists in one gulp, without multiple .append() or +
| lists and sublists | i use this code to split a data to make a list with three sublists.
to split when there is * or -. but it also reads the the \n\n *.. dont know why?
i dont want to read those? can some one tell me what im doing wrong?
this is the data
*Quote of the Day
-Education is the ability to listen to almost anything without losing your temper or your self-confidence - Robert Frost
-Education is what survives when what has been learned has been forgotten - B. F. Skinner
*Fact of the Day
-Fractals, an important part of chaos theory, are very useful in studying a huge amount of areas. They are present throughout nature, and so can be used to help predict many things in nature. They can also help simulate nature, as in graphics design for movies (animating clouds etc), or predict the actions of nature.
-According to a recent survey by Just-Eat, not everyone in The United Kingdom actually knows what the Scottish delicacy, haggis is. Of the 1,623 British people polled:\n\n * 18% of Brits thought haggis was some sort of Scottish animal.\n\n * 15% thought it was a Scottish musical instrument.\n\n * 4% thought it was a character from Harry Potter.\n\n * 41% didn't even know what Scotland's national dish was.\n\nWhile a small number of Scots admitted not knowing what haggis was either, they also discovered that 68% of Scots would like to see Haggis delivered as takeaway.
-With the growing concerns involving Facebook and its ever changing privacy settings, a few software developers have now engineered a website that allows users to trawl through the status updates of anyone who does not have the correct privacy settings to prevent it.\n\nNamed Openbook, the ultimate aim of the site is to further expose the problems with Facebook and its privacy settings to the general public, and show people just how easy it is to access this type of information about complete strangers. The site works as a search engine so it is easy to search terms such as 'don't tell anyone' or 'I hate my boss', and searches can also be narrowed down by gender.
*Pet of the Day
-Scottish Terrier
-Land Shark
-Hamster
-Tse Tse Fly
END
i use this code:
contents = open("data.dat").read()
data = contents.split('*') #split the data at the '*'
newlist = [item.split("-") for item in data if item]
to make that wrong similar to what i have to get list
| [
"The \"\\n\\n\" is part of the input data, so it's preserved in python. Just add a strip() to remove it:\nfinallist = [item.strip() for item in newlist]\n\nSee the strip() docs: http://docs.python.org/library/stdtypes.html#str.strip\nUPDATED FROM COMMENT:\nfinallist = [item.replace(\"\\\\n\", \"\\n\").strip() for i... | [
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003216238_python.txt |
Q:
Django: How do I get every table and all of that table's columns in a project?
I'm creating a set of SQL full database copy scripts using MySQL's INTO OUTFILE and LOAD DATA LOCAL INFILE.
Specifically:
SELECT {columns} FROM {table} INTO OUTFILE '{table}.csv'
LOAD DATA LOCAL INFILE '{table}.csv' REPLACE INTO {table} {columns}
Because of this, I don't need just the tables, I also need the columns for the tables.
I can get all of the tables and columns, but this doesn't include m2m tables:
from django.db.models import get_models()
for model in get_models():
table = model._meta.db_table
columns = [field.column for field in model._meta.fields]
I can also get all of the tables, but this doesn't give me access to the columns:
from django.db import connection
tables = connection.introspection.table_names()
How do you get every table and every corresponding column on that table for a Django project?
More details:
I'm doing this on a reasonably large dataset (>1GB) so using the flat file method seems to be the only reasonable way to make this large of a copy in MySQL. I already have the schema copied over (using ./manage.py syncdb --migrate) and the issue I'm having is specifically with copying the data, which requires me to have the tables and columns to create proper SQL statements. Also, the reason I can't use default column ordering is because the production database I'm copying from has different column ordering than what is created with a fresh syncdb (due to many months worth of migrations and schema changes).
A:
Have you taken a look at manage.py ?
You can get boatloads of SQL information, for example to get all the create table syntax for an app within your project you can do:
python manage.py sqlall <appname>
If you type:
python manage.py help
You can see a ton of other features.
A:
I dug in to the source to find this solution. I feel like there's probably a better way, but this does the trick.
This first block gets all of the normal (non-m2m) tables and their columns
from django.db import connection
from django.apps import apps
table_info = []
tables = connection.introspection.table_names()
seen_models = connection.introspection.installed_models(tables)
for model in apps.get_models():
if model._meta.proxy:
continue
table = model._meta.db_table
if table not in tables:
continue
columns = [field.column for field in model._meta.fields]
table_info.append((table, columns))
This next block was the tricky part. It gets all the m2m field tables and their columns.
for model in apps.get_models():
for field in model._meta.local_many_to_many:
if not field.creates_table:
continue
table = field.m2m_db_table()
if table not in tables:
continue
columns = ['id'] # They always have an id column
columns.append(field.m2m_column_name())
columns.append(field.m2m_reverse_name())
table_info.append((table, columns))
A:
Have you looked into "manage.py dumpdata" and "manage.py loaddata"? They dump and load in json format. I use it to dump stuff from one site and overwrite another site's database. It doesn't have an "every database" option on dumpdata, but you can call it in a loop on the results of a "manage.py dbshell" command.
| Django: How do I get every table and all of that table's columns in a project? | I'm creating a set of SQL full database copy scripts using MySQL's INTO OUTFILE and LOAD DATA LOCAL INFILE.
Specifically:
SELECT {columns} FROM {table} INTO OUTFILE '{table}.csv'
LOAD DATA LOCAL INFILE '{table}.csv' REPLACE INTO {table} {columns}
Because of this, I don't need just the tables, I also need the columns for the tables.
I can get all of the tables and columns, but this doesn't include m2m tables:
from django.db.models import get_models()
for model in get_models():
table = model._meta.db_table
columns = [field.column for field in model._meta.fields]
I can also get all of the tables, but this doesn't give me access to the columns:
from django.db import connection
tables = connection.introspection.table_names()
How do you get every table and every corresponding column on that table for a Django project?
More details:
I'm doing this on a reasonably large dataset (>1GB) so using the flat file method seems to be the only reasonable way to make this large of a copy in MySQL. I already have the schema copied over (using ./manage.py syncdb --migrate) and the issue I'm having is specifically with copying the data, which requires me to have the tables and columns to create proper SQL statements. Also, the reason I can't use default column ordering is because the production database I'm copying from has different column ordering than what is created with a fresh syncdb (due to many months worth of migrations and schema changes).
| [
"Have you taken a look at manage.py ?\nYou can get boatloads of SQL information, for example to get all the create table syntax for an app within your project you can do:\npython manage.py sqlall <appname>\n\nIf you type:\npython manage.py help\n\nYou can see a ton of other features.\n",
"I dug in to the source t... | [
5,
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003207859_django_python.txt |
Q:
(How) Can I use string substitution for working w/ Django’s i18n {% trans %} tag?
I'm looking for something like this:
{% trans "There are %{flowers}n flowers in the vase" < flowers:3 %}
Now obviously syntax is fake, but it should be sufficient to demonstrate what I'm looking for.
Should I cook something of my own? It looks like a common usecase, so I was quite surprised that quick web search didn't return anything helpful.
I'm actually starting to loathe working with Django templating system... While I understand that it's designed to enforce separation of application logic from view, it's doing it by being intrusive on my workflow. I should be able to quickly prototype and only when I need to work with designer, and only then, should I have to be more strict about something like this.
A:
I'm not absolutely sure what you're trying to do (what's < flowers:3 supposed to do?), but have you looked at blocktrans?
{% blocktrans count flowers|length as counter %}
There is one flower in the vase.
{% plural %}
There are {{ counter }} flowers in the vase.
{% endblocktrans %}
A:
Use {% blocktrans %} instead of {% trans %}.
A:
You may find the module inflect.py useful, although it would mean departing from the templating system.
import inflect
p = inflect.engine()
p.num(numflowers, show=False)
return 'There %s %s %s in the vase.' % (
p.pl('is'),
p.numwords(numflowers),
p.pl('flower'))
with numflowers = 1
'There is one flower in the vase.'
with numflowers = 2
'There are two flowers in the vase.'
| (How) Can I use string substitution for working w/ Django’s i18n {% trans %} tag? | I'm looking for something like this:
{% trans "There are %{flowers}n flowers in the vase" < flowers:3 %}
Now obviously syntax is fake, but it should be sufficient to demonstrate what I'm looking for.
Should I cook something of my own? It looks like a common usecase, so I was quite surprised that quick web search didn't return anything helpful.
I'm actually starting to loathe working with Django templating system... While I understand that it's designed to enforce separation of application logic from view, it's doing it by being intrusive on my workflow. I should be able to quickly prototype and only when I need to work with designer, and only then, should I have to be more strict about something like this.
| [
"I'm not absolutely sure what you're trying to do (what's < flowers:3 supposed to do?), but have you looked at blocktrans?\n{% blocktrans count flowers|length as counter %}\n There is one flower in the vase.\n{% plural %}\n There are {{ counter }} flowers in the vase.\n{% endblocktrans %}\n\n",
"Use {% bloc... | [
3,
1,
0
] | [] | [] | [
"django",
"formatting",
"internationalization",
"python",
"templates"
] | stackoverflow_0002337077_django_formatting_internationalization_python_templates.txt |
Q:
Vim's omnicompletion fails with "from" imports in Python
Omnicompletion for Python seems to fail when there is a "from" import instead of a normal one.
For example, if I have these two files:
Test.py:
class Test:
def method(self):
pass
main.py:
from Test import Test
class Test2:
def __init__(self):
self.x = Test()
If I try to activate omnicompletion for self.x... it says "Pattern not found".
However, if I change the import statement to:
import Test
and the self.x declaration to:
self.x = Test.Test()
then I'm able to use omnicompletion as expected (it suggests "method", for example).
I'm using Vim 7.2.245 and the default plugin for Python code completion (pythoncomplete).
Should I set some variable? Or is this behavior expected?
Update:
Based on Jared's answer, I found out something by accident:
Omnicompletion doesn't work on this:
from StringIO import StringIO
class Test:
def __init__(self):
self.x = StringIO()
self.x.<C-x><C-o>
s = Test()
But works on this:
from StringIO import StringIO
class Test:
def __init__(self):
self.x = StringIO()
self.x.<C-x><C-o>
s = Test()
s.x = StringIO()
The only difference is the redeclaration of x (actually, it also works if I remove the declaration inside __init__).
I tested my example again, and I think the problem is not the "from" import, but the use of the imported class inside another class.
If I change the file main.py to:
from Test import Test
class Test2:
def __init__(self):
self.x = Test()
self.x.<C-x><C-o>
y = Test()
y.<C-x><C-o>
The first attempt to use omnicompletion fails, but the second works fine.
So yep, looks like a bug in the plugin :)
A:
update: ooh, so I checked your example, and I get completion for
x = Test()
x.<C-x><C-o>
but not
o = object()
o.x = Test()
o.x.<C-x><C-o>
...I'm gonna do some digging
update 2: revenge of Dr. Strangelove
and...this is where it get's weird.
from StringIO import StringIO
class M:
pass
s = M()
s.x = StringIO()
s.x.<C-x><C-o>
completes. but this
from StringIO import StringIO
class M: pass
s = M()
s.x = StringIO()
s.x.<C-x><C-o>
Did you catch the difference? nothing syntactically -- just a little whitespace
And yet it breaks completion. So there's definitely a parsing bug in there somewhere (why they don't just use the ast module, I have no idea...)
[end of updates]
On first blush, I can't reproduce your problem; here's my test file:
from os import path
path.<C-x><C-o>
and I get completion. Now, I know it's not exactly your situation, but it shows that pythoncomplete knows about 'from'.
And now the more in-depth example:
from StringIO import StringIO
s = StringIO()
s.<C-x><C-o>
And...completion! Could you try that example to see if it works with builtin modules for you? If that's the case, you should probably check paths...
If it still doesnt work, and you're up for some digging around, check out line #555 of pythoncomplete.vim [at /usr/share/vim/vim72/autoload/pythoncomplete.vim on my ubuntu machine]:
elif token == 'from':
mod, token = self._parsedotname()
if not mod or token != "import":
print "from: syntax error..."
continue
names = self._parseimportlist()
for name, alias in names:
loc = "from %s import %s" % (mod,name)
if len(alias) > 0: loc += " as %s" % alias
self.scope.local(loc)
freshscope = False
as you can see, this is where it handles from statements.
Cheers
| Vim's omnicompletion fails with "from" imports in Python | Omnicompletion for Python seems to fail when there is a "from" import instead of a normal one.
For example, if I have these two files:
Test.py:
class Test:
def method(self):
pass
main.py:
from Test import Test
class Test2:
def __init__(self):
self.x = Test()
If I try to activate omnicompletion for self.x... it says "Pattern not found".
However, if I change the import statement to:
import Test
and the self.x declaration to:
self.x = Test.Test()
then I'm able to use omnicompletion as expected (it suggests "method", for example).
I'm using Vim 7.2.245 and the default plugin for Python code completion (pythoncomplete).
Should I set some variable? Or is this behavior expected?
Update:
Based on Jared's answer, I found out something by accident:
Omnicompletion doesn't work on this:
from StringIO import StringIO
class Test:
def __init__(self):
self.x = StringIO()
self.x.<C-x><C-o>
s = Test()
But works on this:
from StringIO import StringIO
class Test:
def __init__(self):
self.x = StringIO()
self.x.<C-x><C-o>
s = Test()
s.x = StringIO()
The only difference is the redeclaration of x (actually, it also works if I remove the declaration inside __init__).
I tested my example again, and I think the problem is not the "from" import, but the use of the imported class inside another class.
If I change the file main.py to:
from Test import Test
class Test2:
def __init__(self):
self.x = Test()
self.x.<C-x><C-o>
y = Test()
y.<C-x><C-o>
The first attempt to use omnicompletion fails, but the second works fine.
So yep, looks like a bug in the plugin :)
| [
"update: ooh, so I checked your example, and I get completion for\nx = Test()\nx.<C-x><C-o>\n\nbut not\no = object()\no.x = Test()\no.x.<C-x><C-o>\n\n...I'm gonna do some digging\nupdate 2: revenge of Dr. Strangelove\nand...this is where it get's weird.\nfrom StringIO import StringIO\nclass M:\n pass\ns = M()\ns... | [
2
] | [] | [] | [
"import",
"omnicomplete",
"python",
"vim"
] | stackoverflow_0003213129_import_omnicomplete_python_vim.txt |
Q:
Python: No csv.close()?
I'm using the CSV module to read a tab delimited file. Code below:
z = csv.reader(open('/home/rv/ncbi-blast-2.2.23+/db/output.blast'), delimiter='\t')
But when I add Z.close() to end of my script i get and error stating "csv.reader' object has no attribute 'close'"
z.close()
So how do i close "Z"?
A:
The reader is really just a parser. When you ask it for a line of data, it delegates the reading action to the underlying file object and just converts the result into a set of fields. The reader itself doesn't manage any resources that would need to be cleaned up when you're done using it, so there's no need to close it; it'd be a meaningless operation.
You should make sure to close the underlying file object, though, because that does manage a resource (an open file descriptor) that needs to be cleaned up. Here's the way to do that:
with open('/home/rv/ncbi-blast-2.2.23+/db/output.blast') as f:
z = csv.reader(f, delimiter='\t')
# do whatever you need to with z
If you're not familiar with the with statement, it's roughly equivalent to enclosing its contents in a try...finally block that closes the file in the finally part.
Hopefully this doesn't matter (and if it does, you really need to update to a newer version of Python), but the with statement was introduced in Python 2.5, and in that version you would have needed a __future__ import to enable it. If you were working with an even older version of Python, you would have had to do the closing yourself using try...finally.
Thanks to Jared for pointing out compatibility issues with the with statement.
A:
You do not close CSV readers directly; instead you should close whatever file-like object is being used. For example, in your case, you'd say:
f = open('/home/rv/ncbi-blast-2.2.23+/db/output.blast')
z = csv.reader(f, delimiter='\t')
...
f.close()
If you are using a recent version of Python, you can use the with statement, e.g.
with open('/home/rv/ncbi-blast-2.2.23+/db/output.blast') as f:
z = csv.reader(f, delimiter='\t')
...
This has the advantage that f will be closed even if you throw an exception or otherwise return inside the with-block, whereas such a case would lead to the file remaining open in the previous example. In other words, it's basically equivalent to a try/finally block, e.g.
f = open('/home/rv/ncbi-blast-2.2.23+/db/output.blast')
try:
z = csv.reader(f, delimiter='\t')
...
finally:
f.close()
A:
You don't close the result of the reader() method, you close the result of the open() method. So, use two statements: foo=open(...); bar=csv.reader(foo). Then you can call foo.close().
There are no bonus points awarded for doing in one line that which can be more readable and functional in two.
| Python: No csv.close()? | I'm using the CSV module to read a tab delimited file. Code below:
z = csv.reader(open('/home/rv/ncbi-blast-2.2.23+/db/output.blast'), delimiter='\t')
But when I add Z.close() to end of my script i get and error stating "csv.reader' object has no attribute 'close'"
z.close()
So how do i close "Z"?
| [
"The reader is really just a parser. When you ask it for a line of data, it delegates the reading action to the underlying file object and just converts the result into a set of fields. The reader itself doesn't manage any resources that would need to be cleaned up when you're done using it, so there's no need to c... | [
65,
39,
8
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0003216954_csv_python.txt |
Q:
Why am I getting this error when I try writing a client for soaplib?
Traceback (most recent call last):
File "", line 1, in
NameError: name 'HelloWorldService' is not defined
I am following the example at http://github.com/jkp/soaplib by writing the following code:
from soaplib.client import make_service_client
client = make_service_client('http://localhost:7789/',HelloWorldService())
A:
You're neglecting the paragraph after that code snippet:
As in this case, the stub can be the instance of the remote functionality, however the requirements are that it just have the same method signatures and definitions as the server implementation.
You need to add a stub to your project that simulates the structure of the HelloWorldService class on the server:
class HelloWorldService(SimpleWSGISoapApp):
def say_hello(self, name, times):
pass
Add that snippet right after your import statement and give it a whirl.
| Why am I getting this error when I try writing a client for soaplib? | Traceback (most recent call last):
File "", line 1, in
NameError: name 'HelloWorldService' is not defined
I am following the example at http://github.com/jkp/soaplib by writing the following code:
from soaplib.client import make_service_client
client = make_service_client('http://localhost:7789/',HelloWorldService())
| [
"You're neglecting the paragraph after that code snippet:\n\nAs in this case, the stub can be the instance of the remote functionality, however the requirements are that it just have the same method signatures and definitions as the server implementation.\n\nYou need to add a stub to your project that simulates the... | [
1
] | [] | [] | [
"python",
"web_services"
] | stackoverflow_0003217098_python_web_services.txt |
Q:
How can I improve this number2words script
import sys
words = {
1 : 'one',
2 : 'two',
3 : 'three',
4 : 'four',
5 : 'five',
6 : 'six',
7 : 'seven',
8 : 'eight',
9 : 'nine',
10 : 'ten',
11 : 'eleven',
12 : 'twelve',
13 : 'thirteen',
14 : 'fourteen',
15 : 'fifteen',
16 : 'sixteen',
17 : 'seventeen',
18 : 'eighteen',
19 : 'nineteen'
}
tens = [
'',
'twenty',
'thirty',
'forty',
'fifty',
'sixty',
'seventy',
'eighty',
'ninety',
]
placeholders = [
'',
'thousand',
'million',
'billion',
'trillion',
'quadrillion'
]
# segMag = segment magnitude (starting at 1)
def convertTrio(number):
return ' '.join([words[int(number[0])], 'hundred', convertDuo(number[1:3])]) # convertDuo(number[1:3])
def convertDuo(number):
#if teens or less
if int(number[0]) == 1:
return words[int(number)]
#twenty-five
else:
return tens[int(number[0]) - 1] + '-' + words[int(number[1])]
if __name__ == "__main__":
string = []
numeralSegments = []
numeral = sys.argv[1]
if int(numeral) < 100:
print convertDuo(numeral)
else:
# split number into lists, grouped in threes
for i in range (0, len(numeral), 3):
numeralSegments.append(numeral[i:i+3])
numeralSegments.reverse()
# for every segment, convert to trio word and append thousand, million, etc depending on magnitude
for i in range (len(numeralSegments)):
string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i])
# reverse the list of strings before concatenating to commas
string.reverse()
print ', '.join(string)
Warning: I'm a total python novice. I'm aware there are probably many times more efficient ways of doing things. I'd appreciate any pointers to them.
Edit: The code currently only works for numbers whose digit counts are multiples of three. I'd appreciate a suggestion for an elegant way to fix that as well. Thanks.
A:
Two improvements come to mind:
40 is spelled "forty", not "fourty"
your program needs unit tests
Have a look at the Python doctest and unittest modules.
A:
You can't group digits into "segments" going from left-to-right. The range(0,len(),3) is not going to work out well. You'll have to write the same algorithm for inserting digit separators. You start from the right, picking off segments of digits.
What's left over (on the left, get it?) will be 1, 2 or 3 digits. You've got convertTrio and convertDuo, which handle 3 and 2 digits, respectively. Somewhere in there is a convert one digit function (can't see it).
If it's not homework, then, here's a proper digit clustering algorithm
def segment( n ):
segList= []
while len(n) > 3:
segList.insert( 0, n[-3:] )
n= n[:-3]
segList.insert( 0, n )
return segList
Edit
To be more Pythonic, package this as a tidy, reusable module. The stuff inside the if __name__ == "__main__" does two things, which should be separated.
Your command-line parsing (anything having to do with sys.argv is one thing. The actual "convert a number" function is something else entirely. You want to look more like this.
if __name__ == "__main__":
import sys
for number in sys.argv[1:]:
print number2string( number )
Then, your number2string function becomes an easily reused piece of this module.
A:
Instead of slicing digits, use modular arithmetic to separate the units. This function will convert a number less than 100 using the given data structures.
def convert(n):
q, r = divmod(n, 10)
if q < 2:
return words[n]
result = tens[q-1] # offset because tens is missing first null value
if r:
result += '-' + words[r]
return result
Then use convert recursively to support larger numbers, e.g., start with divmod(n, 100) and so on.
A:
Maybe Numbers and plural words as spoken English will help a little. A little dated though - 4 May 2005.
A:
Check out source for Number::Spell Perl module. It is short and can be easily ported to Python (if it has not already been done).
A:
In case anyone reading this is looking for a numbers to words script, have a look at inflect.py
import inflect
p = inflect.engine()
p.numwords(123456789)
gives
'one hundred and twenty-three million, four hundred and fifty-six thousand, seven hundred and eighty-nine'
| How can I improve this number2words script | import sys
words = {
1 : 'one',
2 : 'two',
3 : 'three',
4 : 'four',
5 : 'five',
6 : 'six',
7 : 'seven',
8 : 'eight',
9 : 'nine',
10 : 'ten',
11 : 'eleven',
12 : 'twelve',
13 : 'thirteen',
14 : 'fourteen',
15 : 'fifteen',
16 : 'sixteen',
17 : 'seventeen',
18 : 'eighteen',
19 : 'nineteen'
}
tens = [
'',
'twenty',
'thirty',
'forty',
'fifty',
'sixty',
'seventy',
'eighty',
'ninety',
]
placeholders = [
'',
'thousand',
'million',
'billion',
'trillion',
'quadrillion'
]
# segMag = segment magnitude (starting at 1)
def convertTrio(number):
return ' '.join([words[int(number[0])], 'hundred', convertDuo(number[1:3])]) # convertDuo(number[1:3])
def convertDuo(number):
#if teens or less
if int(number[0]) == 1:
return words[int(number)]
#twenty-five
else:
return tens[int(number[0]) - 1] + '-' + words[int(number[1])]
if __name__ == "__main__":
string = []
numeralSegments = []
numeral = sys.argv[1]
if int(numeral) < 100:
print convertDuo(numeral)
else:
# split number into lists, grouped in threes
for i in range (0, len(numeral), 3):
numeralSegments.append(numeral[i:i+3])
numeralSegments.reverse()
# for every segment, convert to trio word and append thousand, million, etc depending on magnitude
for i in range (len(numeralSegments)):
string.append(convertTrio(numeralSegments[i]) + ' ' + placeholders[i])
# reverse the list of strings before concatenating to commas
string.reverse()
print ', '.join(string)
Warning: I'm a total python novice. I'm aware there are probably many times more efficient ways of doing things. I'd appreciate any pointers to them.
Edit: The code currently only works for numbers whose digit counts are multiples of three. I'd appreciate a suggestion for an elegant way to fix that as well. Thanks.
| [
"Two improvements come to mind:\n\n40 is spelled \"forty\", not \"fourty\"\nyour program needs unit tests\n\nHave a look at the Python doctest and unittest modules.\n",
"You can't group digits into \"segments\" going from left-to-right. The range(0,len(),3) is not going to work out well. You'll have to write t... | [
3,
2,
2,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000289735_python.txt |
Q:
Python "draw() must be called with Label instance as first argument (got _WindowMetaclass instance instead)"
This is a class I made using Python with pyglet to display a window.
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__()
pyglet.text.Label("Prototype")
windowText = text.Label.draw(Window, "Hello World",
font_name = "Times New Roman",
font_size = 36,
color = (193, 205, 193, 255))
def on_draw(self):
self.clear()
self.label.draw()
Every time I try to run it I get the error "TypeError: unbound method draw() must be called with Label instance as first argument (got _WindowMetaclass instance instead)". I'm pretty sure I know what I have to do (find how to get Label's instance) just not how to do it. Could someone help me understand how to make this work?
A:
If I had to guess, I'd say that you should bind the instance you create 2 lines above and use that instead.
mylabel = pyglet.text.Label("Prototype")
windowText = mylabel.draw(...
A:
you give a class "Window" instead of an instance as argument, try "self"
| Python "draw() must be called with Label instance as first argument (got _WindowMetaclass instance instead)" | This is a class I made using Python with pyglet to display a window.
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__()
pyglet.text.Label("Prototype")
windowText = text.Label.draw(Window, "Hello World",
font_name = "Times New Roman",
font_size = 36,
color = (193, 205, 193, 255))
def on_draw(self):
self.clear()
self.label.draw()
Every time I try to run it I get the error "TypeError: unbound method draw() must be called with Label instance as first argument (got _WindowMetaclass instance instead)". I'm pretty sure I know what I have to do (find how to get Label's instance) just not how to do it. Could someone help me understand how to make this work?
| [
"If I had to guess, I'd say that you should bind the instance you create 2 lines above and use that instead.\n mylabel = pyglet.text.Label(\"Prototype\")\n\n windowText = mylabel.draw(...\n\n",
"you give a class \"Window\" instead of an instance as argument, try \"self\"\n"
] | [
2,
0
] | [] | [] | [
"pyglet",
"python"
] | stackoverflow_0003030348_pyglet_python.txt |
Q:
How to get root premissions for my app?
My app needs to do some privileged work. I've been looking everywhere, but I can't find anything useful. I know I want to use Policykit1 and dbus because all the other alternatives I've found aren't used anymore.
This is the code I got so far:
import dbus
import os
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
authority = dbus.Interface(proxy, dbus_interface='org.freedesktop.PolicyKit1.Authority')
system_bus_name = bus.get_unique_name()
subject = ('system-bus-name', {'name' : system_bus_name})
action_id = 'org.freedesktop.policykit.exec'
details = {}
flags = 1 # AllowUserInteraction flag
cancellation_id = '' # No cancellation i
result = authority.CheckAuthorization(subject, action_id, details, flags, cancellation_id)
os.makedirs('/usr/local/share/somefolder')
I can't make the directory, what am I doing wrong?
A:
Filesystem security is stopping you because your user doesn't have write permissions to /usr/local/share/somefolder. You could use sudo to temporarily escalate permissions for that directory creation. But it doesn't stop there if you need to perform more operations as superuser.
If you need to write to something that isn't in user space, the entire program might be better of run as root (under sudo of course), such as sudo ./myscript.py.
| How to get root premissions for my app? | My app needs to do some privileged work. I've been looking everywhere, but I can't find anything useful. I know I want to use Policykit1 and dbus because all the other alternatives I've found aren't used anymore.
This is the code I got so far:
import dbus
import os
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
authority = dbus.Interface(proxy, dbus_interface='org.freedesktop.PolicyKit1.Authority')
system_bus_name = bus.get_unique_name()
subject = ('system-bus-name', {'name' : system_bus_name})
action_id = 'org.freedesktop.policykit.exec'
details = {}
flags = 1 # AllowUserInteraction flag
cancellation_id = '' # No cancellation i
result = authority.CheckAuthorization(subject, action_id, details, flags, cancellation_id)
os.makedirs('/usr/local/share/somefolder')
I can't make the directory, what am I doing wrong?
| [
"Filesystem security is stopping you because your user doesn't have write permissions to /usr/local/share/somefolder. You could use sudo to temporarily escalate permissions for that directory creation. But it doesn't stop there if you need to perform more operations as superuser. \nIf you need to write to somethin... | [
1
] | [] | [] | [
"dbus",
"linux",
"python"
] | stackoverflow_0003217420_dbus_linux_python.txt |
Q:
Is it possible to use soaplib server with Apache?
Almost every documentation I am seeing shows Soaplib servers to be deployed using Cherry Py or some other server. Instead of that can be be deployed using apache?
Thanks
A:
soaplib makes its servers be WSGI applications, so they can be deployed in any WSGI environment. Best way to use WSGI on Apache is mod_wsgi.
| Is it possible to use soaplib server with Apache? | Almost every documentation I am seeing shows Soaplib servers to be deployed using Cherry Py or some other server. Instead of that can be be deployed using apache?
Thanks
| [
"soaplib makes its servers be WSGI applications, so they can be deployed in any WSGI environment. Best way to use WSGI on Apache is mod_wsgi.\n"
] | [
3
] | [] | [] | [
"python",
"soaplib",
"web_services"
] | stackoverflow_0003216924_python_soaplib_web_services.txt |
Q:
Using Suds for SOAP in python, are suds.client.Client objects thread safe?
I'm using Suds to access a SOAP web service from python. If I have multiple threading.Thread threads of execution, can each of them safely access the same suds.client.Client instance concurrently, or must I create separate Client objects for each thread?
A:
As far as I know they are NOT thread safe. You could safely use the same client object so long as you are using a queue or thread pool. That way when one thread is done with the client, the next one can use it.
For network-based events however, you should probably ask yourself which is better. Threading or asynchronous network programming? There was recently a patch proposed to SUDS to enable support for asynch sockets for use with event-based packages such as Twisted, greenlets, etc.
| Using Suds for SOAP in python, are suds.client.Client objects thread safe? | I'm using Suds to access a SOAP web service from python. If I have multiple threading.Thread threads of execution, can each of them safely access the same suds.client.Client instance concurrently, or must I create separate Client objects for each thread?
| [
"As far as I know they are NOT thread safe. You could safely use the same client object so long as you are using a queue or thread pool. That way when one thread is done with the client, the next one can use it.\nFor network-based events however, you should probably ask yourself which is better. Threading or asyn... | [
2
] | [] | [] | [
"multithreading",
"python",
"soap",
"suds"
] | stackoverflow_0002991864_multithreading_python_soap_suds.txt |
Q:
Writing a 'print' function in Python
I want to create a function that works like the build-in print function in Python:
print 'test', i, 'started'
So a call like this should work:
log('test', i, 'started)
The log function should call the logging.info() function (from the Python logging module). How can I create such a function?
This is my first try:
import logging
def log(*args):
logging.info(args)
log('test', i, 'started)
But the output is not what I want:
('test', 2, 'started')
While it should be:
test 2 started
A:
This works:
def log(*args):
logging.info(' '.join(map(str, args)))
A:
You can do this kind of thing:
def log(*args):
logging.info(' '.join(args))
A:
Define a function that takes a variable number of arguments, you can operate on the parameter list args to print it how you'd like:
>>> def log(*args):
... print args
>>> log("a", 1, "b")
("a", 1, "b")
Or:
>>> def log(*args):
... for a in args: # <- loop over the arguments
... print a, # <- notice the comma that says "no newline".
... print # <- force a newline after the log statement.
>>> log("a", 1, "b")
a 1 b
If you want to use logging.info:
logging.info(msg[, *args[, **kwargs]])
Logs a message with level INFO on the root logger. The arguments are interpreted
as for debug().
>>> def log(*args):
... logging.info(" ".join("%s" %a for a in args))
A:
How about:
def log(*args):
logging.info(' '.join([str(arg) for arg in args]))
HTH!
A:
I do this, to make it accept a format string. Coming from a C world, I like my format strings. I use code exactly like this in several production systems.
def logf(fmt, *args):
try: m = fmt % args
except:
# Catch mismatch between fmt/args; prevents logging.info from
# failing below, as well.
m = fmt
fmt = "%s"
if DEBUG:
stderr.write("[%s] %s\n" % (time.asctime(), m))
logging.info(fmt, *args)
Usage:
logf("There are %u entries in the list, and my mood is %s.", len(L), "sad")
logf("It works without arguments, as well")
logf("Test %d started", i)
Call me old-school, I guess. This is all Python 2, by the way - 3 is far different.
A:
The logging methods require a format-string as the first argument (or, as some others have suggested, a literal string to log). You can easily generate a format string for a given-number of arguments with code something like this:
def log(*args):
fmt_string = ' '.join(['%s'] * len(args))
logging.info(fmt_string, *args)
This works because the multiplication operator on lists is defined to extend the list with copies of the list's contents.
Note that I'm passing *args as the second "argument" to logging.info -- this is Python's syntax for expanding a sequence (args will be a tuple, I believe) into a series of positional arguments in the function call.
A:
One day I was reading the python docs and I came across the functools.partial() method (or I read about it somewhere -- I can't remember). A little playing around led to the following code I now put at the beginning of every python script I write:
import sys, functools
nl = "\n"
def StreamOut(stream, *s, **kw):
k = kw.setdefault
# Process keyword arguments
sep = k("sep", "")
auto_nl = k("auto_nl", True)
prefix = k("prefix", "")
convert = k("convert", str)
# Convert position arguments to strings
strings = map(convert, s)
# Dump them to the stream
stream.write(prefix + sep.join(strings))
# Add a newline if desired
if auto_nl:
stream.write(nl)
out = functools.partial(StreamOut, sys.stdout)
outs = functools.partial(StreamOut, sys.stdout, sep=" ")
dbg = functools.partial(StreamOut, sys.stdout, sep=" ", prefix="+ ")
err = functools.partial(StreamOut, sys.stderr)
out("Hi there", "how are you?")
outs("Hi there", "how are you?")
Put it into a file and try them out. This makes for some easily-extendible functions.
| Writing a 'print' function in Python | I want to create a function that works like the build-in print function in Python:
print 'test', i, 'started'
So a call like this should work:
log('test', i, 'started)
The log function should call the logging.info() function (from the Python logging module). How can I create such a function?
This is my first try:
import logging
def log(*args):
logging.info(args)
log('test', i, 'started)
But the output is not what I want:
('test', 2, 'started')
While it should be:
test 2 started
| [
"This works:\ndef log(*args):\n logging.info(' '.join(map(str, args)))\n\n",
"You can do this kind of thing:\ndef log(*args):\n logging.info(' '.join(args))\n\n",
"Define a function that takes a variable number of arguments, you can operate on the parameter list args to print it how you'd like:\n>>> def log... | [
7,
3,
1,
1,
1,
0,
0
] | [] | [] | [
"arguments",
"python"
] | stackoverflow_0003212938_arguments_python.txt |
Q:
Python signals hosted on WSGI
I'm using the python signals library to kill a function if it runs longer than a set period of time.
It works well in my tests but when hosted on the server I get the following error
"signal only works in main thread"
I have set the WSGI signals restriction to be off in my httpd.conf
WSGIRestrictSignal Off
as described
http://code.google.com/p/modwsgi/wiki/ApplicationIssues#Registration_Of_Signal_Handlers
I'm using the functions from the recipe described here
http://code.activestate.com/recipes/307871/
Not sure what I'm doing wrong. Is there a way to ensure that the signals are called in the main thread?
A:
The only time any code under Apache/mod_wsgi runs as main thread is when a WSGI script file is being imported via WSGIImportScript or equivalent methods. Although one could use that method to register the signal handler from the main thread, it will be of no use as all subsequent requests are serviced via secondary threads and never the main thread. As a consequence, I don't think your signal handler will ever run as recollect that it can only run if the main thread is actually doing something, and that will not be the case as the main thread, will be blocked in Apache/mod_wsgi simply waiting for the process to be shutdown.
What is the operation doing that you are trying to kill? Doing it within context of web application, especially if web application is multi threaded probably isn't a good idea.
| Python signals hosted on WSGI | I'm using the python signals library to kill a function if it runs longer than a set period of time.
It works well in my tests but when hosted on the server I get the following error
"signal only works in main thread"
I have set the WSGI signals restriction to be off in my httpd.conf
WSGIRestrictSignal Off
as described
http://code.google.com/p/modwsgi/wiki/ApplicationIssues#Registration_Of_Signal_Handlers
I'm using the functions from the recipe described here
http://code.activestate.com/recipes/307871/
Not sure what I'm doing wrong. Is there a way to ensure that the signals are called in the main thread?
| [
"The only time any code under Apache/mod_wsgi runs as main thread is when a WSGI script file is being imported via WSGIImportScript or equivalent methods. Although one could use that method to register the signal handler from the main thread, it will be of no use as all subsequent requests are serviced via secondar... | [
1
] | [] | [] | [
"mod_wsgi",
"python",
"signals"
] | stackoverflow_0003208577_mod_wsgi_python_signals.txt |
Q:
Matplotlib: move graph to the right
I have two graphs with in one image, each with 5 points. Their value on the X axis is not important, all that I require is that they're all equally distributed on it.
import matplotlib.pyplot as plt
data = [43,51,44,73,60]
data2 = [34,25,42,53,61]
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(data, '-o', color='#000000', lw=1, ms=6)
ax.plot(data2, '-o', color='#000000', lw=1, ms=6)
plt.show()
This creates a graph like the one below.
I need the second graph (the one using the data2 points) to start from 5 on the X axis, not from 0, meaning it'll have the points at (5,34),(6,25),(7,42),(8,53),(9,61). How can I do this?
A:
Make a list of the X values,
x = [5,6,7,8,9]
and use
ax.plot(x, data2, ...)
Note that you could also use range(5,10) or numpy's arange(5,10) or linspace(5,9,5) to generate the X values.
| Matplotlib: move graph to the right | I have two graphs with in one image, each with 5 points. Their value on the X axis is not important, all that I require is that they're all equally distributed on it.
import matplotlib.pyplot as plt
data = [43,51,44,73,60]
data2 = [34,25,42,53,61]
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(data, '-o', color='#000000', lw=1, ms=6)
ax.plot(data2, '-o', color='#000000', lw=1, ms=6)
plt.show()
This creates a graph like the one below.
I need the second graph (the one using the data2 points) to start from 5 on the X axis, not from 0, meaning it'll have the points at (5,34),(6,25),(7,42),(8,53),(9,61). How can I do this?
| [
"Make a list of the X values,\nx = [5,6,7,8,9]\n\nand use\nax.plot(x, data2, ...)\n\nNote that you could also use range(5,10) or numpy's arange(5,10) or linspace(5,9,5) to generate the X values.\n"
] | [
1
] | [] | [] | [
"graph",
"matplotlib",
"python"
] | stackoverflow_0003217715_graph_matplotlib_python.txt |
Q:
sql server function native parameter bind error
I'm using the following software stack on Ubuntu 10.04 Lucid LTS to
connect to a database:
python 2.6.5 (ubuntu package)
pyodbc git trunk commit eb545758079a743b2e809e2e219c8848bc6256b2
unixodbc 2.2.11 (ubuntu package)
freetds 0.82 (ubuntu package)
Windows with Microsoft SQL Server 2000 (8.0)
I get this error when trying to do native parameter binds in arguments
to a SQL SERVER function:
Traceback (most recent call last):
File "/home/nosklo/devel/testes/sqlfunc.py", line 32, in <module>
cur.execute("SELECT * FROM fn_FuncTest(?)", ('test',))
pyodbc.ProgrammingError: ('42000', '[42000] [FreeTDS][SQL
Server]SqlDumpExceptionHandler: Process 54 generated fatal exception
c0000005 EXCEPTION_ACCESS_VIOLATION. SQL Server is terminating this
process.\r\n (0) (SQLPrepare)')
Here's the reproduction code:
import pyodbc
constring = 'server=myserver;uid=uid;pwd=pwd;database=db;TDS_Version=8.0;driver={FreeTDS}'
con = pyodbc.connect(constring)
print 'VERSION: ', con.getinfo(pyodbc.SQL_DBMS_VER)
cur = con.cursor()
try:
cur.execute('DROP FUNCTION fn_FuncTest')
con.commit()
print "Function dropped"
except pyodbc.Error:
pass
cur.execute('''
CREATE FUNCTION fn_FuncTest (@testparam varchar(4))
RETURNS @retTest TABLE (param varchar(4))
AS
BEGIN
INSERT @retTest
SELECT @testparam
RETURN
END''')
con.commit()
Now the function is created. If I try to call it using a value direct in the query (no native binds of values) it works fine:
cur.execute("SELECT * FROM fn_FuncTest('test')")
assert cur.fetchone()[0] == 'test'
However I get the error above when I try to do a native bind (by using a parameter placeholder and passing the value separately):
cur.execute("SELECT * FROM fn_FuncTest(?)", ('test',))
Further investigation reveals some weird stuff I'd like to relate:
Everything works fine if I change TDS Version to 4.2 (however,
version report from sql server is wrong -- using TDS version 4.2 I get
'95.08.0255' instead of the real version '08.00.0760').
Everything works fine for the other two types of functions ->
functions that return a value and functions that are just a SELECT
query (like a view) both work fine. You can even define a new function
that returns the result of a query on the other (broken) function, and
this way everything will work, even when doing native binds on the
parameters. For example: CREATE FUNCTION fn_tempFunc(@testparam
varchar(4)) RETURNS TABLE AS RETURN (SELECT * FROM
fn_FuncTest(@testparam))
Connection gets very unstable after this error, you can't recover.
The error happens when trying to bind any type of data.
How can I pursue this further? I'd like to do native binds to function parameters.
A:
Ultimately, this probably isn't the answer you're looking for, but when I had to connect to MSSQL from Perl two or three years ago, ODBC + FreeTDS was initially involved, and I didn't get anywhere with it (though I don't recall the specific errors, I was trying to do binding, though, and it seemed the source of some of the trouble).
On the Perl project, I eventually wound up using a driver intended for Sybase (which MSSQL forked off from), so you might want to look into that.
The Python wiki has a page on Sybase and another on SQL Server that you'll probably want to peruse for alternatives:
http://wiki.python.org/moin/Sybase
http://wiki.python.org/moin/SQL%20Server
| sql server function native parameter bind error | I'm using the following software stack on Ubuntu 10.04 Lucid LTS to
connect to a database:
python 2.6.5 (ubuntu package)
pyodbc git trunk commit eb545758079a743b2e809e2e219c8848bc6256b2
unixodbc 2.2.11 (ubuntu package)
freetds 0.82 (ubuntu package)
Windows with Microsoft SQL Server 2000 (8.0)
I get this error when trying to do native parameter binds in arguments
to a SQL SERVER function:
Traceback (most recent call last):
File "/home/nosklo/devel/testes/sqlfunc.py", line 32, in <module>
cur.execute("SELECT * FROM fn_FuncTest(?)", ('test',))
pyodbc.ProgrammingError: ('42000', '[42000] [FreeTDS][SQL
Server]SqlDumpExceptionHandler: Process 54 generated fatal exception
c0000005 EXCEPTION_ACCESS_VIOLATION. SQL Server is terminating this
process.\r\n (0) (SQLPrepare)')
Here's the reproduction code:
import pyodbc
constring = 'server=myserver;uid=uid;pwd=pwd;database=db;TDS_Version=8.0;driver={FreeTDS}'
con = pyodbc.connect(constring)
print 'VERSION: ', con.getinfo(pyodbc.SQL_DBMS_VER)
cur = con.cursor()
try:
cur.execute('DROP FUNCTION fn_FuncTest')
con.commit()
print "Function dropped"
except pyodbc.Error:
pass
cur.execute('''
CREATE FUNCTION fn_FuncTest (@testparam varchar(4))
RETURNS @retTest TABLE (param varchar(4))
AS
BEGIN
INSERT @retTest
SELECT @testparam
RETURN
END''')
con.commit()
Now the function is created. If I try to call it using a value direct in the query (no native binds of values) it works fine:
cur.execute("SELECT * FROM fn_FuncTest('test')")
assert cur.fetchone()[0] == 'test'
However I get the error above when I try to do a native bind (by using a parameter placeholder and passing the value separately):
cur.execute("SELECT * FROM fn_FuncTest(?)", ('test',))
Further investigation reveals some weird stuff I'd like to relate:
Everything works fine if I change TDS Version to 4.2 (however,
version report from sql server is wrong -- using TDS version 4.2 I get
'95.08.0255' instead of the real version '08.00.0760').
Everything works fine for the other two types of functions ->
functions that return a value and functions that are just a SELECT
query (like a view) both work fine. You can even define a new function
that returns the result of a query on the other (broken) function, and
this way everything will work, even when doing native binds on the
parameters. For example: CREATE FUNCTION fn_tempFunc(@testparam
varchar(4)) RETURNS TABLE AS RETURN (SELECT * FROM
fn_FuncTest(@testparam))
Connection gets very unstable after this error, you can't recover.
The error happens when trying to bind any type of data.
How can I pursue this further? I'd like to do native binds to function parameters.
| [
"Ultimately, this probably isn't the answer you're looking for, but when I had to connect to MSSQL from Perl two or three years ago, ODBC + FreeTDS was initially involved, and I didn't get anywhere with it (though I don't recall the specific errors, I was trying to do binding, though, and it seemed the source of so... | [
0
] | [] | [] | [
"freetds",
"pyodbc",
"python",
"sql_server",
"unixodbc"
] | stackoverflow_0003143704_freetds_pyodbc_python_sql_server_unixodbc.txt |
Q:
Scapy SYN send on our own IP address
I tried to send SYN packets on my local network and monitoring them with Wireshark and everything works just fine, except when i try to send a packet to my own ip address it "seems" to work because it says Sent 1 packet, but it is not really sent, i can't see the packet in Wireshark nor any answers to the packet. My setup is a computer A ( 192.168.0.1 ) with a TCP Socket Server listening on port 40508, and a computer B ( 192.168.0.2 ).
On Computer B i test:
ip=IP(src="192.168.0.2",dst="192.168.0.1")
SYN=TCP(sport=40508,dport=40508,flags="S",seq=12345)
send(ip/SYN)
It works fine, i see the SYN packet on Wireshark and the SYN/ACK response from 192.168.0.1
On Computer A i test:
ip=IP(src="192.168.0.1",dst="192.168.0.2")
SYN=TCP(sport=40508,dport=40508,flags="S",seq=12345)
send(ip/SYN)
It works fine too, i see the SYN packet and the RST/ACK ( there is no server listening on port 40508 on 192.168.0.2 so it sends a RST/ACK ) response from 192.168.0.2
But when i try on Computer A :
ip=IP(src="192.168.0.2",dst="192.168.0.1")
SYN=TCP(sport=40508,dport=40508,flags="S",seq=12345)
send(ip/SYN)
Nothing appears in Wireshark, as if the packet was never sent but it said like the other tests : Sent 1 packets. and returned no error whatsoever. If i run the same test on computer B and try to send a packet to its own IP address i got the same problem.
For my program i really need to send a SYN packet to my own IP address, is there a way to do that or is it impossible ?
Thanks in advance,
Nolhian
A:
What network device(s) is your Wireshark installation listening on? I suspect it's listening on the actual network card (ethernet, wifi, or otherwise, as per the Wireshark FAQ) -- and when sending from a computer to itself the OS can of course bypass the device (why bother with it?) and just do the "sending" by copying bits around within the TCP/IP stack in kernel memory.
In other words I suspect your packet is being sent OK, just Wireshark may not see it. To verify this hypothesis, you could try (e.g.) using your browser to visit existent and nonexistent ports on your local machine, and see if Wireshark sees those packets or not.
| Scapy SYN send on our own IP address | I tried to send SYN packets on my local network and monitoring them with Wireshark and everything works just fine, except when i try to send a packet to my own ip address it "seems" to work because it says Sent 1 packet, but it is not really sent, i can't see the packet in Wireshark nor any answers to the packet. My setup is a computer A ( 192.168.0.1 ) with a TCP Socket Server listening on port 40508, and a computer B ( 192.168.0.2 ).
On Computer B i test:
ip=IP(src="192.168.0.2",dst="192.168.0.1")
SYN=TCP(sport=40508,dport=40508,flags="S",seq=12345)
send(ip/SYN)
It works fine, i see the SYN packet on Wireshark and the SYN/ACK response from 192.168.0.1
On Computer A i test:
ip=IP(src="192.168.0.1",dst="192.168.0.2")
SYN=TCP(sport=40508,dport=40508,flags="S",seq=12345)
send(ip/SYN)
It works fine too, i see the SYN packet and the RST/ACK ( there is no server listening on port 40508 on 192.168.0.2 so it sends a RST/ACK ) response from 192.168.0.2
But when i try on Computer A :
ip=IP(src="192.168.0.2",dst="192.168.0.1")
SYN=TCP(sport=40508,dport=40508,flags="S",seq=12345)
send(ip/SYN)
Nothing appears in Wireshark, as if the packet was never sent but it said like the other tests : Sent 1 packets. and returned no error whatsoever. If i run the same test on computer B and try to send a packet to its own IP address i got the same problem.
For my program i really need to send a SYN packet to my own IP address, is there a way to do that or is it impossible ?
Thanks in advance,
Nolhian
| [
"What network device(s) is your Wireshark installation listening on? I suspect it's listening on the actual network card (ethernet, wifi, or otherwise, as per the Wireshark FAQ) -- and when sending from a computer to itself the OS can of course bypass the device (why bother with it?) and just do the \"sending\" by... | [
2
] | [] | [] | [
"generator",
"packet",
"python",
"scapy",
"send"
] | stackoverflow_0003217486_generator_packet_python_scapy_send.txt |
Q:
How to add __iter__ to dynamic type?
Source
def flags(*opts):
keys = [t[0] for t in opts]
words = [t[1] for t in opts]
nums = [2**i for i in range(len(opts))]
attrs = dict(zip(keys,nums))
choices = iter(zip(nums,words))
return type('Flags', (), dict(attrs))
Abilities = flags(
('FLY', 'Can fly'),
('FIREBALL', 'Can shoot fireballs'),
('INVISIBLE', 'Can turn invisible'),
)
Question
How can I add an __iter__ method to Abilities so that I can iterate over choices?
Why?
This way I can use things like
hero.abilities = Abilities.FLY | Abilities.FIREBALL
if hero.abilities & Abilities.FIREBALL:
for k, v in Abilities:
print k, v
in my code without having to use any magic numbers or strings, and I can also save the set of flags to the DB as a single int, or display the list in a readable format.
Other improvements are welcome.
A:
There's no need to use a dynamic type here; I'd restructure this as a simple class, for example:
class flags(object):
def __init__(self, *opts):
keys = [t[0] for t in opts]
words = [t[1] for t in opts]
nums = [2**i for i in range(len(opts))]
self.attrs = dict(zip(keys,nums))
self.choices = zip(nums,words)
def __getattr__(self, a):
return self.attrs[a]
def __iter__(self):
return iter(self.choices)
Abilities = flags(
('FLY', 'Can fly'),
('FIREBALL', 'Can shoot fireballs'),
('INVISIBLE', 'Can turn invisible'),
)
print Abilities.FLY
for k, v in Abilities:
print k, v
A:
Why are you doing it the hard way? If you want a dict with __getattr__ overriding why not start with one:
class Flags(dict):
def __init__(self, *args):
dict.__init__(self, args)
def __getattr__(self, name):
return self[name]
...
This also has the Advantage of Least Surprise, since dict.__iter__() generates keys and dict.iteritems() yields tuples.
A:
It would be a more Pythonic solution if you implement your own __getattr__ method for accessing dynamic fields instead of dealing with metaclasses through type.
Edit: It's not clear to me what do you mean by choices, but here is an example:
class Abilities(object):
def __init__(self, abilities):
self.abilities = abilities
def __getattr__(self, name):
a = [x for x in self.abilities if x[0] == name]
if len(a) != 1:
raise AttributeError('attribute {0} not found'.format(name))
title, id, help = a[0]
return id
def __iter__(self):
return (id, help for title, id, help in self.abilities)
SPEC = [
('FLY', 10, 'Can fly'),
('FIREBALL', 13, 'Can shoot fireballs'),
('INVISIBLE', 14, 'Can turn invisible'),
]
abitilies = Abilities(SPEC)
hero.abilities = abilities.FLY | abilities.FIREBALL
for k, v in abilities:
print k, v
A:
You need two key changes -- the last lines of flags should be:
choices = iter(zip(nums,words))
attrs['__iter__'] = lambda self: choices
return type('Flags', (), dict(attrs))()
Note that I've added a line setting __iter__, and a trailing () in the return to instantiate the type (to loop on a type you'd have to use a custom metaclass -- way overkill, no need).
The last line of flags should actually be:
return type('Flags', (), attrs)()
as there's no reason to make a copy of attrs, which is already a dict (but that's an innocuous redundancy, not a killer mistake;-).
A:
Based on your guys' suggestions, I came up with this:
Source
class enumerable(object):
def __init__(self, func, *opts):
keys = func(len(opts))
self.attrs = dict(zip([t[0] for t in opts], keys))
self.opts = zip(keys, [t[1] for t in opts])
def __getattr__(self, a):
return self.attrs[a]
def __len__(self):
return len(self.opts)
def __iter__(self):
return iter(self.opts)
def __deepcopy__(self, memo):
return self
class enum(enumerable):
def __init__(self, *opts):
return super(enum, self).__init__(range, *opts)
class flags(enumerable):
def __init__(self, *opts):
return super(flags, self).__init__(lambda l: [1<<i for i in range(l)], *opts)
### tests:
Abilities = enum(
('FLY', 'Can fly'),
('FIREBALL', 'Can shoot fireballs'),
('INVISIBLE', 'Can turn invisible'),
('FROST_NOVA', 'Can call down an ice storm'),
('BLINK', 'Can teleport short distances'),
)
print 'Fireball = %d' % Abilities.FIREBALL
print 'Number of options = %d' % len(Abilities)
for k, v in Abilities:
print '%d: %s' % (k, v)
Output
Fireball = 1
Number of options = 5
0: Can fly
1: Can shoot fireballs
2: Can turn invisible
3: Can call down an ice storm
4: Can teleport short distances
For whatever reason, my particular application needs __deepcopy__ to be implemented. Since these classes are for building "constants", none of their attributes should ever be changed after creation; thus I hope it's safe just to return self.
| How to add __iter__ to dynamic type? | Source
def flags(*opts):
keys = [t[0] for t in opts]
words = [t[1] for t in opts]
nums = [2**i for i in range(len(opts))]
attrs = dict(zip(keys,nums))
choices = iter(zip(nums,words))
return type('Flags', (), dict(attrs))
Abilities = flags(
('FLY', 'Can fly'),
('FIREBALL', 'Can shoot fireballs'),
('INVISIBLE', 'Can turn invisible'),
)
Question
How can I add an __iter__ method to Abilities so that I can iterate over choices?
Why?
This way I can use things like
hero.abilities = Abilities.FLY | Abilities.FIREBALL
if hero.abilities & Abilities.FIREBALL:
for k, v in Abilities:
print k, v
in my code without having to use any magic numbers or strings, and I can also save the set of flags to the DB as a single int, or display the list in a readable format.
Other improvements are welcome.
| [
"There's no need to use a dynamic type here; I'd restructure this as a simple class, for example:\nclass flags(object):\n def __init__(self, *opts):\n keys = [t[0] for t in opts]\n words = [t[1] for t in opts]\n nums = [2**i for i in range(len(opts))]\n self.attrs = dict(zip(keys,nums... | [
4,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003217768_python.txt |
Q:
Still wondering about directed graphs drawn from AppEngine
With reference to another case of pretty much the same question I have, Brightside asked:
Library to render Directed Graphs (similar to graphviz) on Google App Engine
The accepted answer was "canvis", which looks very cool from a rendering perspective, but canvis just does the drawing. It still needs to call graphvis binaries for doing the layout, not so? Or what am I missing, in order to make sense of the author's "Awesome! I just got it working on GAE. Thanks!" - possibly I will have to resort to manual layout via my own pure python code, when generating my graph specification in the dot language? (Else I'll resort to other options mentioned.)
A:
Canvis doesn't call graphviz itself - it renders xdot directly in the browser. Of course you still have to have some way to generate xdot files, but canvis doesn't care where they come from.
| Still wondering about directed graphs drawn from AppEngine | With reference to another case of pretty much the same question I have, Brightside asked:
Library to render Directed Graphs (similar to graphviz) on Google App Engine
The accepted answer was "canvis", which looks very cool from a rendering perspective, but canvis just does the drawing. It still needs to call graphvis binaries for doing the layout, not so? Or what am I missing, in order to make sense of the author's "Awesome! I just got it working on GAE. Thanks!" - possibly I will have to resort to manual layout via my own pure python code, when generating my graph specification in the dot language? (Else I'll resort to other options mentioned.)
| [
"Canvis doesn't call graphviz itself - it renders xdot directly in the browser. Of course you still have to have some way to generate xdot files, but canvis doesn't care where they come from.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"graphviz",
"python"
] | stackoverflow_0003217536_google_app_engine_graphviz_python.txt |
Q:
Socket in python will only send data it receives
I must be missing something in the code. I've rewritten an 'echo server' example to do a bit more when it receives something.
This is how it currently looks:
#!/usr/bin/env python
import select
import socket
import sys
import threading
import time
import Queue
globuser = {}
queue = Queue.Queue()
class Server:
def __init__(self):
self.host = ''
self.port = 2000
self.backlog = 5
self.size = 1024
self.server = None
self.threads = []
def open_socket(self):
try:
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host,self.port))
self.server.listen(5)
except socket.error, (value,message):
if self.server:
self.server.close()
print "Could not open socket: " + message
sys.exit(1)
def run(self):
self.open_socket()
input = [self.server,sys.stdin]
running = 1
while running:
inputready,outputready,exceptready = select.select(input,[],[])
for s in inputready:
if s == self.server:
# handle the server socket
c = Client(self.server.accept(), queue)
c.start()
self.threads.append(c)
elif s == sys.stdin:
# handle standard input
junk = sys.stdin.readline()
running = 0
# close all threads
self.server.close()
for c in self.threads:
c.join()
class Client(threading.Thread):
initialized=0
def __init__(self,(client,address), queue):
threading.Thread.__init__(self)
self.client = client
self.address = address
self.size = 1024
self.queue = queue
self.threads = []
global globuser
print 'Client thread created!'
def run(self):
running = 1
while running:
print 'While running client'
data = self.client.recv(self.size)
print 'Dit we receive data?'
if data:
print 'Data received!'
print 'Fetching data from socket: ',
if data[0] == 'I':
print 'Initializing user: ' + data
user = {'uid': data[1:6] ,'x': data[6:9], 'y': data[9:12]}
globuser[user['uid']] = user
print globuser
initialized=1
m=updateClient(user['uid'], queue)
m.start()
self.threads.append(m)
self.client.send('Beginning - Initialized'+';')
elif data[0] == 'A':
print 'Client has received previous data: ' + data
#On deactivation, nothing works.
self.client.send(data+';')
#print 'Client Data sent: ' + data
else:
print 'Closing'
self.client.close()
running = 0
if self.queue.empty():
print 'Queue is empty'
else:
print 'Queue has information: ',
data2 = self.queue.get(1, 1)
isdata2 = 1
if data2 == 'Exit':
running = 0
print 'Client is being closed'
self.client.close()
if isdata2 == 1:
print 'Sending data to client: ' + data2,
self.client.send(data2)
self.queue.task_done()
isdata2 = 0
time.sleep(1)
class updateClient(threading.Thread):
def __init__(self,uid, queue):
threading.Thread.__init__(self)
self.uid = uid
self.queue = queue
global globuser
print 'updateClient thread started!'
def run(self):
running = 20
test=0
while running > 0:
test = test + 1
self.queue.put('Test Queue Data #' + str(test))
running = running - 1
time.sleep(1)
print 'Updateclient has stopped'
if __name__ == "__main__":
s = Server()
s.run()
This runs fine, although it's kind of silly to keep sending the same data back again along with other data.
In the middle of the code you'll see
#On deactivation, nothing works.
self.client.send(data+';')
#print 'Client Data sent: ' + data
When I DO deactive the self.client.send(data+';') or change it into self.client.send('something else;') it does not work! And the client receives nothing.
Is there something special about the "data" variable? Do I need to format the string in some way?
A:
Here's a cleaned-up, functional version of your code! I tested it myself, though I didn't write unit tests.
There were some syntax errors and other miscellaneous problems with the
original code, so I took some liberties. I'm assuming that the protocol is
framed by using ; as a delimiter, since a ; is sent at the end of every
message to the client, though no framing was being done in the original code.
from twisted.internet import reactor, protocol, task
from twisted.protocols import basic
from twisted.python import log
import sys
class ServerProtocol(basic.LineOnlyReceiver):
delimiter = ';'
def lineReceived(self, line):
if line.startswith('I'):
user = dict(uid=line[1:6], x=line[6:9], y=line[9:12])
self.factory.users[user['uid']] = user
log.msg(repr(self.factory.users))
self.startUpdateClient()
self.sendLine('Beginning - Initialized')
elif line.startswith('A'):
self.sendLine(line)
else:
self.transport.loseConnection()
def _updateClient(self):
if self._running == 0:
self._looper.stop()
return
self._running -= 1
self._test += 1
self.sendLine('Test Queue Data #%d' % (self._test,))
def startUpdateClient(self):
self._running, self._test = 20, 0
self._looper = task.LoopingCall(self._updateClient)
self._looper.start(1, now=False)
class Server(protocol.ServerFactory):
protocol = ServerProtocol
def __init__(self):
self.users = {}
if __name__ == '__main__':
log.startLogging(sys.stderr)
reactor.listenTCP(2000, Server())
reactor.run()
| Socket in python will only send data it receives | I must be missing something in the code. I've rewritten an 'echo server' example to do a bit more when it receives something.
This is how it currently looks:
#!/usr/bin/env python
import select
import socket
import sys
import threading
import time
import Queue
globuser = {}
queue = Queue.Queue()
class Server:
def __init__(self):
self.host = ''
self.port = 2000
self.backlog = 5
self.size = 1024
self.server = None
self.threads = []
def open_socket(self):
try:
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host,self.port))
self.server.listen(5)
except socket.error, (value,message):
if self.server:
self.server.close()
print "Could not open socket: " + message
sys.exit(1)
def run(self):
self.open_socket()
input = [self.server,sys.stdin]
running = 1
while running:
inputready,outputready,exceptready = select.select(input,[],[])
for s in inputready:
if s == self.server:
# handle the server socket
c = Client(self.server.accept(), queue)
c.start()
self.threads.append(c)
elif s == sys.stdin:
# handle standard input
junk = sys.stdin.readline()
running = 0
# close all threads
self.server.close()
for c in self.threads:
c.join()
class Client(threading.Thread):
initialized=0
def __init__(self,(client,address), queue):
threading.Thread.__init__(self)
self.client = client
self.address = address
self.size = 1024
self.queue = queue
self.threads = []
global globuser
print 'Client thread created!'
def run(self):
running = 1
while running:
print 'While running client'
data = self.client.recv(self.size)
print 'Dit we receive data?'
if data:
print 'Data received!'
print 'Fetching data from socket: ',
if data[0] == 'I':
print 'Initializing user: ' + data
user = {'uid': data[1:6] ,'x': data[6:9], 'y': data[9:12]}
globuser[user['uid']] = user
print globuser
initialized=1
m=updateClient(user['uid'], queue)
m.start()
self.threads.append(m)
self.client.send('Beginning - Initialized'+';')
elif data[0] == 'A':
print 'Client has received previous data: ' + data
#On deactivation, nothing works.
self.client.send(data+';')
#print 'Client Data sent: ' + data
else:
print 'Closing'
self.client.close()
running = 0
if self.queue.empty():
print 'Queue is empty'
else:
print 'Queue has information: ',
data2 = self.queue.get(1, 1)
isdata2 = 1
if data2 == 'Exit':
running = 0
print 'Client is being closed'
self.client.close()
if isdata2 == 1:
print 'Sending data to client: ' + data2,
self.client.send(data2)
self.queue.task_done()
isdata2 = 0
time.sleep(1)
class updateClient(threading.Thread):
def __init__(self,uid, queue):
threading.Thread.__init__(self)
self.uid = uid
self.queue = queue
global globuser
print 'updateClient thread started!'
def run(self):
running = 20
test=0
while running > 0:
test = test + 1
self.queue.put('Test Queue Data #' + str(test))
running = running - 1
time.sleep(1)
print 'Updateclient has stopped'
if __name__ == "__main__":
s = Server()
s.run()
This runs fine, although it's kind of silly to keep sending the same data back again along with other data.
In the middle of the code you'll see
#On deactivation, nothing works.
self.client.send(data+';')
#print 'Client Data sent: ' + data
When I DO deactive the self.client.send(data+';') or change it into self.client.send('something else;') it does not work! And the client receives nothing.
Is there something special about the "data" variable? Do I need to format the string in some way?
| [
"Here's a cleaned-up, functional version of your code! I tested it myself, though I didn't write unit tests.\nThere were some syntax errors and other miscellaneous problems with the \noriginal code, so I took some liberties. I'm assuming that the protocol is \nframed by using ; as a delimiter, since a ; is sent at ... | [
2
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003216577_python_sockets.txt |
Q:
Python list initialization (by ref problem)
I have some simple code that represents a graph using a square boolean matrix where rows/columns are nodes and true represents an undirected link between two nodes. I am initializing this matrix with False values and then setting the value to True where a link exists.
I believe the way I am initializing the list is causing a single bool instance to be referenced by each cell in a given row. The result is that if I set any cell to True all the other cells in that row also become True.
How should I be initializing my square matrix so that all values are false but none are shared by reference with other cells?
import sys
class Graph(object):
def __init__(self, nodeCount, links):
self.matrix = [[False] * nodeCount] * nodeCount
for l in links:
self.matrix[l[0]][l[1]] = True
def __str__(self):
s = " "
for i in range(len(self.matrix)):
s += str(i) + " "
s += "\n"
for r in range(len(self.matrix)):
s += str(r) + " "
for c in range(len(self.matrix)):
s += str(self.matrix[c][r])[0] + " "
s += "\n"
return s
g = Graph(5, [(2,3)])
print g
Also, on GIST
A:
Actually, you've slightly misunderstood the problem. You believe that the boolean references are shared (this is true, but not important-- booleans are immutable, so sharing references to the same object doesn't mean much). What's happened is that the list references are shared, and that's caused your troubles. Let me show you:
Your code is this
[[False] * nodeCount] * nodeCount
What happens is that you get nodeCount references to a single list with nodeCount references to False. Multiplying a sequene by an integer gives you a sequence with duplicated references-- they're not copies, they're aliases.
>>> x = [False] * 3
>>> y = [x] * 3
>>> y[0] is y[1]
True
>> # your problem
>>> y[0][0] = True
>>> y[1]
[True, False, False]
So in this case, it means you can't change individual rows, because all the rows are the same list, and changing one row changes all.
to fix this, make new lists for each row:
[[False]*nodeCount for _ in xrange(nodeCount)]
example:
>>> y = [[False]*3 for _ in xrange(3)]
>>> y[0] is y[1]
False
>>> y[0][0] = True
>>> y[1]
[False, False, False]
A:
self.matrix = [[False] * nodeCount] * nodeCount
should be something like
self.matrix = [[False] * nodeCount for _ in range(nodeCount)]
| Python list initialization (by ref problem) | I have some simple code that represents a graph using a square boolean matrix where rows/columns are nodes and true represents an undirected link between two nodes. I am initializing this matrix with False values and then setting the value to True where a link exists.
I believe the way I am initializing the list is causing a single bool instance to be referenced by each cell in a given row. The result is that if I set any cell to True all the other cells in that row also become True.
How should I be initializing my square matrix so that all values are false but none are shared by reference with other cells?
import sys
class Graph(object):
def __init__(self, nodeCount, links):
self.matrix = [[False] * nodeCount] * nodeCount
for l in links:
self.matrix[l[0]][l[1]] = True
def __str__(self):
s = " "
for i in range(len(self.matrix)):
s += str(i) + " "
s += "\n"
for r in range(len(self.matrix)):
s += str(r) + " "
for c in range(len(self.matrix)):
s += str(self.matrix[c][r])[0] + " "
s += "\n"
return s
g = Graph(5, [(2,3)])
print g
Also, on GIST
| [
"Actually, you've slightly misunderstood the problem. You believe that the boolean references are shared (this is true, but not important-- booleans are immutable, so sharing references to the same object doesn't mean much). What's happened is that the list references are shared, and that's caused your troubles. Le... | [
5,
1
] | [] | [] | [
"arrays",
"list",
"python"
] | stackoverflow_0003218136_arrays_list_python.txt |
Q:
Import large chunk of data into Google App Engine Data Store at one go
I have a large CSV file, approx 10 MB in size, which contains all the data which need to be imported in the Google App Engine DataStore.
I tried following approaches to perform import but all the times it failed in half way.
Import using mapping a command to url and then executing url, failed because of request time out...
Import using creating cron job, but got DeadlineExceededError...
Import using remort_api_shell, but got Operation timed out.
Can you please suggest me and approch (using dummy data you can imagine) how to do it... Suggestion with code will be more helpful..
** I am using Python and google's web app framework to develop the said app.
A:
you can post row by row. using built in bulk loader.
http://code.google.com/appengine/docs/python/tools/uploadingdata.html
this is good article.
and here is my contactloader.py that i used 2 years ago for reference. it is more sophisticated since last i used but still.....
import datetime
from google.appengine.ext import db
from google.appengine.tools import bulkloader
class Contact(db.Model):
date = db.DateTimeProperty(auto_now_add=True)
owner = db.StringProperty()
companyname = db.StringProperty()
companyemail = db.EmailProperty()
def myfunc(x):
temp = x.split(":mailto:")
if len(temp) > 0:
temp = temp[-1].split(":")
else:
return "defaultvalue"
if len(temp) > 0:
temp = temp[0]
else:
return "defaultvalue"
temp = temp.split("<1>")[0]
if temp is None or len(temp) < 5:
return "defaultvalue"
return temp
def mysecfunc(x):
return x.split("<0>")[0]
class ContactLoader(bulkloader.Loader):
def __init__(self):
bulkloader.Loader.__init__(self, 'Contact',
[
('companyname',mysecfunc),
('owner', lambda x:"somevalue"),
('companyemail',myfunc),
("date",lambda x:datetime.datetime.now()),
])
loaders = [ContactLoader]
| Import large chunk of data into Google App Engine Data Store at one go | I have a large CSV file, approx 10 MB in size, which contains all the data which need to be imported in the Google App Engine DataStore.
I tried following approaches to perform import but all the times it failed in half way.
Import using mapping a command to url and then executing url, failed because of request time out...
Import using creating cron job, but got DeadlineExceededError...
Import using remort_api_shell, but got Operation timed out.
Can you please suggest me and approch (using dummy data you can imagine) how to do it... Suggestion with code will be more helpful..
** I am using Python and google's web app framework to develop the said app.
| [
"you can post row by row. using built in bulk loader.\nhttp://code.google.com/appengine/docs/python/tools/uploadingdata.html\nthis is good article. \nand here is my contactloader.py that i used 2 years ago for reference. it is more sophisticated since last i used but still.....\nimport datetime\nfrom google.appengi... | [
4
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0003218220_google_app_engine_google_cloud_datastore_python.txt |
Q:
Using other languages with ruby
Is it possible to use multiple languages along side with ruby. For example, I have my application code in Ruby on Rails. I would like to calculate the recommendations and I would like to use python for that. So essentially, python code would get the data and calculate all the stuff and probably get the data from DB, calculate and update the tables.Is it possible and what do you guys think about its adv/disadv
Thanks
A:
If you are offloading work to an exterior process, you may want to make this a webservice (ajax, perhaps) of some sort so that you have some sort of consistent interface.
Otherwise, you could always execute the python script in a subshell through ruby, using stdin/stdout/argv, but this can get ugly quick.
A:
Depending on your exact needs, you can either call out to an external process (using popen, system, etc) or you can setup another mini-web-server or something along those lines and have the rails server communicate with it over HTTP with a REST-style API (or whatever best suits your needs).
In your example, you have a ruby frontend website and then a number-crunching python backend service that builds up recommendation data for the ruby site. A fairly nice solution is to have the ruby site send a HTTP request to the python service when it needs data updating (with a payload of information to identify what it needs doing to what or some such) and then the python backend service can crunch away and update the table which presumably your ruby frontend will automatically pick up the changes of during the next request and display.
A:
I would use the system command
as such
system("python myscript.py")
A:
An easy, quick 'n' dirty solution in case you have python scripts and you want to execute them from inside rails, is this:
%x[shell commands or python path/of/pythonscript.py #{ruby variables to pass on the script}]
or
``shell commands or python path/of/pythonscript.py #{ruby variables to pass on the script}\ (with ` symbol in the beginning and the end).
Put the above inside a controller and it will execute.
For some reason, inside ruby on rails, system and exec commands didn't work for me (exec crashed my application and system doesn't do anything).
| Using other languages with ruby | Is it possible to use multiple languages along side with ruby. For example, I have my application code in Ruby on Rails. I would like to calculate the recommendations and I would like to use python for that. So essentially, python code would get the data and calculate all the stuff and probably get the data from DB, calculate and update the tables.Is it possible and what do you guys think about its adv/disadv
Thanks
| [
"If you are offloading work to an exterior process, you may want to make this a webservice (ajax, perhaps) of some sort so that you have some sort of consistent interface.\nOtherwise, you could always execute the python script in a subshell through ruby, using stdin/stdout/argv, but this can get ugly quick.\n",
"... | [
4,
2,
1,
1
] | [] | [] | [
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0003215455_python_ruby_ruby_on_rails.txt |
Q:
How do I execute Python/bash code in the current directory as part of a code?
Lets say I am designing a tool foobuzzle (foobuzzle's exact job is to set up SRPM files for cross-compiling a variety of codes into their own compartmentalized prefix directories, but this is not important). I would like foobuzzle to take in an input file (buzzle_input) specified by an (intelligent, code-savvy) client, who will tell foobuzzle how they would like it to perform these operations.
I am writing foobuzzle in Python, and it seems to make sense for the user to provide buzzle_input configuration information in either Python or bash. Which would you choose? How would you implement it? I am expecting that Python will need some global environment variables that may need to be set up by executing some other scripts, probably from within the buzzle_input script.
This is not production code, just an internal tool a small team of developers will be using to help manage a fairly large cross-compiled environment of C/C++/FORTRAN codes.
My best guess is to use something to wrap the foobuzzle script so that the $PYTHONPATH variable picks up the current working directory, and to have the foobuzzle_input script imported and executed as set up. Is there a cleaner way to do this without wrapping foobuzzle? Any special considerations for executing the bash scripts (assume safety is not really a concern and that these scripts will not be run with system administrator privileges).
A:
My interpretation of your context, is that you have a Python script that performs various make- or autoconf-like operations, and you want to allow clients to write their own Makefiles for Foobuzzle.
The problem with directories I don't understand. import will always search the local directory? And you can os.chdir() when you hop around to change current working directory, like make does.
Having it as a bash script has the pro that nobody needs to learn Python or, specifically, the Python-like Foobuzzle DSL. But it is a lot less powerful: you're basically limited to sending and receiving text only. You can't write support functions that the bash code can call (unless you generate that into bash as well), proper error handling might be tough, etc.
Depending on how powerful the configuration needs to be, I would use Python. I'd probably load the file itself and use eval() on it, giving me full control over its namespace. I could pass various utility and helper functions, for example, or provide objects they can manipulate directly.
If it's really simple though, specifying flags and names, that sort of thing, then you could just have it as .ini files and use ConfigParser() in the standard library.
| How do I execute Python/bash code in the current directory as part of a code? | Lets say I am designing a tool foobuzzle (foobuzzle's exact job is to set up SRPM files for cross-compiling a variety of codes into their own compartmentalized prefix directories, but this is not important). I would like foobuzzle to take in an input file (buzzle_input) specified by an (intelligent, code-savvy) client, who will tell foobuzzle how they would like it to perform these operations.
I am writing foobuzzle in Python, and it seems to make sense for the user to provide buzzle_input configuration information in either Python or bash. Which would you choose? How would you implement it? I am expecting that Python will need some global environment variables that may need to be set up by executing some other scripts, probably from within the buzzle_input script.
This is not production code, just an internal tool a small team of developers will be using to help manage a fairly large cross-compiled environment of C/C++/FORTRAN codes.
My best guess is to use something to wrap the foobuzzle script so that the $PYTHONPATH variable picks up the current working directory, and to have the foobuzzle_input script imported and executed as set up. Is there a cleaner way to do this without wrapping foobuzzle? Any special considerations for executing the bash scripts (assume safety is not really a concern and that these scripts will not be run with system administrator privileges).
| [
"My interpretation of your context, is that you have a Python script that performs various make- or autoconf-like operations, and you want to allow clients to write their own Makefiles for Foobuzzle.\nThe problem with directories I don't understand. import will always search the local directory? And you can os.chdi... | [
1
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0003218599_bash_python.txt |
Q:
How to use SQLAlchemy to dump an SQL file from query expressions to bulk-insert into a DBMS?
Please bear with me as I explain the problem, how I tried to solve it,
and my question on how to improve it is at the end.
I have a 100,000 line csv file from an offline batch job and I needed to
insert it into the database as its proper models. Ordinarily, if this is a fairly straight-forward load, this can be trivially loaded by just munging the CSV file to fit a schema; but, I had to do some external processing that requires querying and it's just much more convenient to use SQLAlchemy to generate the data I want.
The data I want here is 3 models that represent 3 pre-exiting tables
in the database and each subsequent model depends on the previous model.
For example:
Model C --> Foreign Key --> Model B --> Foreign Key --> Model A
So, the models must be inserted in the order A, B, and C. I came up
with a producer/consumer approach:
- instantiate a multiprocessing.Process which contains a
threadpool of 50 persister threads that have a threadlocal
connection to a database
- read a line from the file using the csv DictReader
- enqueue the dictionary to the process, where each thread creates
the appropriate models by querying the right values and each
thread persists the models in the appropriate order
This was faster than a non-threaded read/persist but it is way slower than
bulk-loading a file into the database. The job finished persisting
after about 45 minutes. For fun, I decided to write it in SQL
statements, it took 5 minutes.
Writing the SQL statements took me a couple of hours, though. So my
question is, could I have used a faster method to insert rows using
SQLAlchemy? As I understand it, SQLAlchemy is not designed for bulk
insert operations, so this is less than ideal.
This follows to my question, is there a way to generate the SQL statements using SQLAlchemy, throw
them in a file, and then just use a bulk-load into the database? I
know about str(model_object) but it does not show the interpolated
values.
I would appreciate any guidance for how to do this faster.
Thanks!
A:
Ordinarily, no, there's no way to get the query with the values included.
What database are you using though? Cause a lot of databases do have some bulk load feature for CSV available.
Postgres: http://www.postgresql.org/docs/8.4/static/sql-copy.html
MySQL: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Oracle: http://www.orafaq.com/wiki/SQL*Loader_FAQ
If you're willing to accept that certain values might not be escaped correctly than you can use this hack I wrote for debugging purposes:
'''Replace the parameter placeholders with values'''
params = compiler.params.items()
params.sort(key=lambda (k, v): len(str(k)), reverse=True)
for k, v in params:
'''Some types don't need escaping'''
if isinstance(v, (int, long, float, bool)):
v = unicode(v)
else:
v = "'%s'" % v
'''Replace the placeholders with values
Works both with :1 and %(foo)s type placeholders'''
query = query.replace(':%s' % k, v)
query = query.replace('%%(%s)s' % k, v)
A:
First, unless you actually have a machine with 50 CPU cores, using 50 threads/processes won't help performance -- it will actually make things slower.
Second, I've a feeling that if you used SQLAlchemy's way of inserting multiple values at once, it would be much faster than creating ORM objects and persisting them one-by-one.
A:
I would venture to say the time spent in the python script is in the per-record upload portion. To determine this you could write to CSV or discard the results instead of uploading new records. This will determine where the bottleneck is; at least from a lookup-vs-insert standpoint. If, as I suspect, that is indeed where it is you can take advantage of the bulk import feature most DBS have. There is no reason, and indeed some arguments against, inserting record-by-record in this kind of circumstance.
Bulk imports tend to do some interestng optimization such as doing it as one transaction w/o commits for each record (even just doing this could see an appreciable drop in run time); whenever feasible I recommend the bulk insert for large record counts. You could still use the producer/consumer approach, but have the consumer instead store the values in memory or in a file and then call the bulk import statement specific to the DB you are using. This might be the route to go if you need to do processing for each record in the CSV file. If so I would also consider how much of that can be cached and shared between records.
it is also possible that the bottleneck is using SQLAlchemy. Not that I know of any inherent issues, but given what you are doing it might be requiring a lot more processing than is necessary - as evidenced by the 8x difference in run times.
For fun, since you already know the SQL, try using a direct DBAPI module in Python to do it and compare run times.
| How to use SQLAlchemy to dump an SQL file from query expressions to bulk-insert into a DBMS? | Please bear with me as I explain the problem, how I tried to solve it,
and my question on how to improve it is at the end.
I have a 100,000 line csv file from an offline batch job and I needed to
insert it into the database as its proper models. Ordinarily, if this is a fairly straight-forward load, this can be trivially loaded by just munging the CSV file to fit a schema; but, I had to do some external processing that requires querying and it's just much more convenient to use SQLAlchemy to generate the data I want.
The data I want here is 3 models that represent 3 pre-exiting tables
in the database and each subsequent model depends on the previous model.
For example:
Model C --> Foreign Key --> Model B --> Foreign Key --> Model A
So, the models must be inserted in the order A, B, and C. I came up
with a producer/consumer approach:
- instantiate a multiprocessing.Process which contains a
threadpool of 50 persister threads that have a threadlocal
connection to a database
- read a line from the file using the csv DictReader
- enqueue the dictionary to the process, where each thread creates
the appropriate models by querying the right values and each
thread persists the models in the appropriate order
This was faster than a non-threaded read/persist but it is way slower than
bulk-loading a file into the database. The job finished persisting
after about 45 minutes. For fun, I decided to write it in SQL
statements, it took 5 minutes.
Writing the SQL statements took me a couple of hours, though. So my
question is, could I have used a faster method to insert rows using
SQLAlchemy? As I understand it, SQLAlchemy is not designed for bulk
insert operations, so this is less than ideal.
This follows to my question, is there a way to generate the SQL statements using SQLAlchemy, throw
them in a file, and then just use a bulk-load into the database? I
know about str(model_object) but it does not show the interpolated
values.
I would appreciate any guidance for how to do this faster.
Thanks!
| [
"Ordinarily, no, there's no way to get the query with the values included.\nWhat database are you using though? Cause a lot of databases do have some bulk load feature for CSV available.\n\nPostgres: http://www.postgresql.org/docs/8.4/static/sql-copy.html\nMySQL: http://dev.mysql.com/doc/refman/5.1/en/load-data.htm... | [
3,
2,
0
] | [] | [] | [
"bulkinsert",
"orm",
"performance",
"python",
"sqlalchemy"
] | stackoverflow_0002880517_bulkinsert_orm_performance_python_sqlalchemy.txt |
Q:
Python function implementations
I've seen various answers to the ball collision detection question explaining why sqrt operations are slow, why absolute value operations are fast on floating ponts etc. How can I find out which operations are expensive and which are not?
Basically, I'm looking for a resource where I can learn about the implementation of all the python library functions. When people are saying those things they aren't actually thinking about how that stuff is implemented in C are they?
Thanks, looking to learn more about implementation details on this slick language.
A:
Python is, like any language, translated to machine code and then run. So yes, they could be talking about low-level implementation details.
Anyway, the best way to learn about speed implementation of the various Python functions is taking a look in the source code.
Have fun!
EDIT: This tip actually applies to any open source project I worked with: Got a problem? Take a look at the source code and you should be fine.
A:
If you're looking for tips on Python speed in general, these performance tips are a good resource.
A:
You find out which operations are slow and which ones are fast by using the timeit module.
For example, let's compare the various methods of checking if a point falls within a circle, from the command line:
python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'math.sqrt(x**2 + y**2) <= r'
python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'math.hypot(x, y) <= r'
python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'x**2 + y**2 <= r**2'
On my machine the results are:
$ python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'math.sqrt(x**2 + y**2) <= r'
1000000 loops, best of 3: 0.744 usec per loop
$ python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'math.hypot(x, y) <= r'
1000000 loops, best of 3: 0.374 usec per loop
$ python -m timeit -s 'import math; x = 42.5; y = 17.2; r = 50.0' 'x**2 + y**2 <= r**2'
1000000 loops, best of 3: 0.724 usec per loop
so math.hypot wins! Incidentally, if you remove the dotted name lookup from the inner loop, you get slightly better results:
$ python -m timeit -s 'from math import hypot; x = 42.5; y = 17.2; r = 50.0' 'hypot(x, y) <= r'
1000000 loops, best of 3: 0.334 usec per loop
A:
The Python standard library includes a disassembler:
>>> def foo(): print
...
>>> import dis
>>> dis.dis(foo)
1 0 PRINT_NEWLINE
1 LOAD_CONST 0 (None)
4 RETURN_VALUE
It doesn't work on everything, though:
>>> from math import sqrt
>>> import dis
>>> dis.dis(sqrt)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/dis.py", line 48, in dis
type(x).__name__
TypeError: don't know how to disassemble builtin_function_or_method objects
| Python function implementations | I've seen various answers to the ball collision detection question explaining why sqrt operations are slow, why absolute value operations are fast on floating ponts etc. How can I find out which operations are expensive and which are not?
Basically, I'm looking for a resource where I can learn about the implementation of all the python library functions. When people are saying those things they aren't actually thinking about how that stuff is implemented in C are they?
Thanks, looking to learn more about implementation details on this slick language.
| [
"Python is, like any language, translated to machine code and then run. So yes, they could be talking about low-level implementation details.\nAnyway, the best way to learn about speed implementation of the various Python functions is taking a look in the source code.\nHave fun! \nEDIT: This tip actually applies to... | [
2,
1,
1,
0
] | [] | [] | [
"implementation",
"performance",
"python"
] | stackoverflow_0003216504_implementation_performance_python.txt |
Q:
Binding a list of strings to an IN clause
Possible Duplicate:
python list in sql query as parameter
Consider this (using apsw here):
s = ["A", "B", "C"]
c.execute("SELECT foo.y FROM foo WHERE foo.x in (?)", (s, ))
This doesn't work, because a binding parameter cannot be a list. I want to bind a list of strings to ?. I know how to build the appropriate query-string manually, but I wonder if there is a way to do this with bindings.
A:
Going with the multiple question marks idea by Fabian, how about
c.execute("SELECT foo.y FROM foo WHERE foo.x in (%s)" % ', '.join('?' * len(s)), s)
A:
I had this problem around 4 years ago, and then I found out it was impossible to bind lists to sql (i was using mssql server and ODBC provider, but also considered direct sql calls)
In my case i was just building the queries manually and it was efficient. In case you have a very long list of values you will have to create another table, populate it in runtime and join with it in your sql.
| Binding a list of strings to an IN clause |
Possible Duplicate:
python list in sql query as parameter
Consider this (using apsw here):
s = ["A", "B", "C"]
c.execute("SELECT foo.y FROM foo WHERE foo.x in (?)", (s, ))
This doesn't work, because a binding parameter cannot be a list. I want to bind a list of strings to ?. I know how to build the appropriate query-string manually, but I wonder if there is a way to do this with bindings.
| [
"Going with the multiple question marks idea by Fabian, how about\nc.execute(\"SELECT foo.y FROM foo WHERE foo.x in (%s)\" % ', '.join('?' * len(s)), s)\n\n",
"I had this problem around 4 years ago, and then I found out it was impossible to bind lists to sql (i was using mssql server and ODBC provider, but also c... | [
1,
0
] | [] | [] | [
"binding",
"list",
"python",
"sqlite"
] | stackoverflow_0003212559_binding_list_python_sqlite.txt |
Q:
why does my pygtk application crash when copying text on a clipboard?
I'm writing a python application using pygtk. I have a main thread who occasionally calls another thread that is supposed to build a string and then copy it on the clipboard before dying. My "slave" thread looks pretty much like this:
class Slave(threading.Thread):
def run(self):
s = build_string()
c = gtk.Clipboard()
c.set_text(s)
Unfortunately my app crashes one-third of the time, showing a message like this:
python: xcb_io.c:221: poll_for_event: Assertion `(((long) (event_sequence) - (long) (dpy->request)) <= 0)' failed.
cloudapp.py: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.0.
Any idea? Could it be a threading problem? I tried initializing the clipboard inside of the Slave.init, putting the string on a TextBuffer and then calling tb.copy_clipboard(c), I tried everything, none of them worked.
A:
You can't interact with Gtk from threads without taking some necessary precautions. Check this PyGTK FAQ entry.
| why does my pygtk application crash when copying text on a clipboard? | I'm writing a python application using pygtk. I have a main thread who occasionally calls another thread that is supposed to build a string and then copy it on the clipboard before dying. My "slave" thread looks pretty much like this:
class Slave(threading.Thread):
def run(self):
s = build_string()
c = gtk.Clipboard()
c.set_text(s)
Unfortunately my app crashes one-third of the time, showing a message like this:
python: xcb_io.c:221: poll_for_event: Assertion `(((long) (event_sequence) - (long) (dpy->request)) <= 0)' failed.
cloudapp.py: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.0.
Any idea? Could it be a threading problem? I tried initializing the clipboard inside of the Slave.init, putting the string on a TextBuffer and then calling tb.copy_clipboard(c), I tried everything, none of them worked.
| [
"You can't interact with Gtk from threads without taking some necessary precautions. Check this PyGTK FAQ entry.\n"
] | [
0
] | [] | [] | [
"clipboard",
"gtk",
"multithreading",
"pygtk",
"python"
] | stackoverflow_0003212010_clipboard_gtk_multithreading_pygtk_python.txt |
Q:
Python file.read() grabs more data than necessary, under the hood
cat file_ro.py
import sys
def file_open(filename):
fo=open(filename,'r')
fo.seek(7)
read_data=fo.read(3)
fo.close()
print read_data
file_open("file.py")
But strace says
readlink("file_ro.py", 0x7fff31fc7ea0, 4096) = -1 EINVAL (Invalid argument)
getcwd("/home/laks/python", 4096) = 18
lstat("/home/laks/python/file_ro.py", {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
stat("file_ro.py", {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
open("file_ro.py", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fa671a6c000
fstat(3, {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
lseek(3, 0, SEEK_SET) = 0
read(3, "import sys\ndef file_open(filenam"..., 128) = 128
read(3, "ile_open(\"file.py\")\n\t\n", 4096) = 22
close(3) = 0
munmap(0x7fa671a6c000, 4096) = 0
stat("file_ro.py", {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
open("file_ro.py", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
ioctl(3, SNDCTL_TMR_TIMEBASE or TCGETS, 0x7fff31fc9e30) = -1 ENOTTY (Inappropriate ioctl for device)
fstat(3, {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fa671a6c000
lseek(3, 0, SEEK_CUR) = 0
read(3, "import sys\ndef file_open(filenam"..., 4096) = 150
lseek(3, 150, SEEK_SET) = 150
read(3, "", 4096) = 0
close(3) = 0
munmap(0x7fa671a6c000, 4096) = 0
open("file.py", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0755, st_size=305, ...}) = 0
fstat(3, {st_mode=S_IFREG|0755, st_size=305, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fa671a6c000
lseek(3, 0, SEEK_SET) = 0
read(3, "import ", 7) = 7
read(3, "sys\ndef file_open(filename):\n\t\"\""..., 4096) = 298
close(3) = 0
munmap(0x7fa671a6c000, 4096) = 0
fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fa671a6c000
write(1, "sys\n", 4sys
) = 4
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x306140efa0}, {0x306d10b2b0, [], SA_RESTORER, 0x306140efa0}, 8) = 0
close(5) = 0
munmap(0x7fa671952000, 4096) = 0
exit_group(0)
As you can see above -
read(3, "import sys\ndef file_open(filenam"..., 4096) = 150
Why read() returns 150 bytes when the program says to read only 3 bytes ?
A:
Since you're reading in another py file things become confused, but it seems the built-in function ignores the value you pass to read(), and buffers the rest of the value. Maybe trying using os.read() instead?
file_ro.py:
import sys
def file_open(filename):
fo=open(filename,'r')
fo.seek(7)
read_data=fo.read(3)
fo.close()
print read_data
file_open("zzz")
zzz:
12345678901234567890123456789012345678901234567890
strace:
...
open("zzz", O_RDONLY|O_LARGEFILE) = 3
fstat64(3, {st_mode=S_IFREG|0644, st_size=51, ...}) = 0
fstat64(3, {st_mode=S_IFREG|0644, st_size=51, ...}) = 0
mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb73fb000
_llseek(3, 0, [0], SEEK_SET) = 0
read(3, "1234567", 7) = 7
read(3, "89012345678901234567890123456789"..., 4096) = 44
close(3) = 0
...
You can specify the size of the buffer to open('zzz', buffering=0), or I used the os module and could more closely control the file reading as you wanted:
file_ro2.py:
import sys, os
def file_open(filename):
fo=os.open(filename, os.O_RDONLY)
os.lseek(fo, 7, 0)
read_data=os.read(fo, 3)
os.close(fo)
print read_data
file_open("zzz")
strace2:
...
open("zzz", O_RDONLY|O_LARGEFILE) = 3
_llseek(3, 7, [7], SEEK_SET) = 0
read(3, "890", 3) = 3
close(3) = 0
...
A:
Buffering. To avoid that use open(filename, 'rb', bufsize=0).
| Python file.read() grabs more data than necessary, under the hood | cat file_ro.py
import sys
def file_open(filename):
fo=open(filename,'r')
fo.seek(7)
read_data=fo.read(3)
fo.close()
print read_data
file_open("file.py")
But strace says
readlink("file_ro.py", 0x7fff31fc7ea0, 4096) = -1 EINVAL (Invalid argument)
getcwd("/home/laks/python", 4096) = 18
lstat("/home/laks/python/file_ro.py", {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
stat("file_ro.py", {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
open("file_ro.py", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fa671a6c000
fstat(3, {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
lseek(3, 0, SEEK_SET) = 0
read(3, "import sys\ndef file_open(filenam"..., 128) = 128
read(3, "ile_open(\"file.py\")\n\t\n", 4096) = 22
close(3) = 0
munmap(0x7fa671a6c000, 4096) = 0
stat("file_ro.py", {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
open("file_ro.py", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
ioctl(3, SNDCTL_TMR_TIMEBASE or TCGETS, 0x7fff31fc9e30) = -1 ENOTTY (Inappropriate ioctl for device)
fstat(3, {st_mode=S_IFREG|0755, st_size=150, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fa671a6c000
lseek(3, 0, SEEK_CUR) = 0
read(3, "import sys\ndef file_open(filenam"..., 4096) = 150
lseek(3, 150, SEEK_SET) = 150
read(3, "", 4096) = 0
close(3) = 0
munmap(0x7fa671a6c000, 4096) = 0
open("file.py", O_RDONLY) = 3
fstat(3, {st_mode=S_IFREG|0755, st_size=305, ...}) = 0
fstat(3, {st_mode=S_IFREG|0755, st_size=305, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fa671a6c000
lseek(3, 0, SEEK_SET) = 0
read(3, "import ", 7) = 7
read(3, "sys\ndef file_open(filename):\n\t\"\""..., 4096) = 298
close(3) = 0
munmap(0x7fa671a6c000, 4096) = 0
fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 0), ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fa671a6c000
write(1, "sys\n", 4sys
) = 4
rt_sigaction(SIGINT, {SIG_DFL, [], SA_RESTORER, 0x306140efa0}, {0x306d10b2b0, [], SA_RESTORER, 0x306140efa0}, 8) = 0
close(5) = 0
munmap(0x7fa671952000, 4096) = 0
exit_group(0)
As you can see above -
read(3, "import sys\ndef file_open(filenam"..., 4096) = 150
Why read() returns 150 bytes when the program says to read only 3 bytes ?
| [
"Since you're reading in another py file things become confused, but it seems the built-in function ignores the value you pass to read(), and buffers the rest of the value. Maybe trying using os.read() instead?\nfile_ro.py:\nimport sys\ndef file_open(filename):\n fo=open(filename,'r')\n fo.seek(7)\n ... | [
6,
6
] | [] | [] | [
"file",
"python",
"strace"
] | stackoverflow_0003211569_file_python_strace.txt |
Q:
making more rows in a row of treeview!
I wanna make sth like this in transmission: [link text]here1
(also in pidgin too, Status under IDs)
can anyone show me a sample code here?
A:
You need a TreeView with a custom CellRenderer. Here's some documentation and an example of the latter.
| making more rows in a row of treeview! | I wanna make sth like this in transmission: [link text]here1
(also in pidgin too, Status under IDs)
can anyone show me a sample code here?
| [
"You need a TreeView with a custom CellRenderer. Here's some documentation and an example of the latter.\n"
] | [
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003211049_pygtk_python.txt |
Q:
What's the VT100 escape code for the "esc" keyboard key itself
I'm writing a script to navigate a text-based menu system, using python's telnetlib to access a serial connection.
I can happily press the F-keys, using the escape codes. e.g. F9 = "\033OX", where "\033" is the escape sequence.
How do I encode the "esc" keyboard key? I would have expected just "\033", but that doesn't seem to work.
A:
There is no such thing as an "escape sequence" for the ESC key on a VT-100 (or other terminals that used escape sequences).
The escape character, ASCII 27, was used to indicate that the following sequences of characters had special meaning. This usually put the terminal into a simple state machine. In general the rule was to swallow the incoming characters until an alphabetic or symbolic character was seen, inclusively, although some special cases such as symbols which might grab one additional character, e.g. ESC # 6 to double-width characters.
For instance on a H-19 / VT-52 terminal, ESC H meant home, ESC E meant clear screen and home, ESC J meant clear to end of screen, etc. The VT-100 series used ESC [ H for home, and ESC [ 2 J for clear to end of screen.
What was really going on was that the open square bracket (there was no close bracket) said that a list of arguments, usually numeric, was coming. The '2' in the ESC [ 2 J meant both from the cursor to the top (zero), and from the cursor to the end (one). Switch the J to a K, and now it would clear the line, rather than the screen, the same way. They weren't arbitrary. Even ESC [ row ; col H would take a numerical row/col, e.g. ESC [ 12; 34 H would go to row 12, column 34. Not providing them took default values.
In theory the server should never throw you a meaningless orphaned ESC character as the terminal would sit there and wait for a sequence.
When you pressed a function key, the terminal would send an ESC character followed by some pre-canned sequence for a function key, arrow, or action. For instance ESC [ 21 ~ was F10.
This then left the very real problem of how to send a literal orphaned ESC. There were two ways.
One, send the ESC and then delay for some amount. The host would have the responsibility of watching not just what came in, but when. And, working under the assumption that a terminal would send a block of characters in its buffer immediately, it would internally time out and take ESC to mean just ESC. The delay did not have to be long.
Two, require the user to press ESC twice for every literal ESC desired. As no escape sequence ever consisted of a double escape character, it signaled a special condition. It exactly the same thing we do when quoting backslash characters in strings, a "\" really means a "\" because we have to satisfy the compiler's lexical phase. In this case, it's the host server. Remember, in the days of serial ports, which was when these terminals were in use, when a character was pressed, it was sent immediately. Only years later did we start emulating terminals and thus rose the need to emulate their escape sequences rather than taking the behaviors out of the content stream.
Of course, an 'invalid' ESC sequence meant the ESC was literal, but this required seeing what the following bytes were before you could act on them (hence the timeout solution). The problem is sometimes those characters caused side effects to an application, nasty ones, and interesting cases could arrive where trying to naively fake out the system could get you into trouble. e.g., use ESC Space to force the escape through, the ESC cancels one prompt, but the space unintendedly acknowledges the next.
The third solution to the problem was to simply have the host ignore special function keys altogether and take the incoming byte stream as literal. For instance, the TECO editor would display a dollar sign to the user each time the ESC was pressed, as it used this for a command separator the same way one might use a semicolon in coding today.
A:
Put a small delay, say 1.5s, after sending the escape so that the other side realizes that it's an isolated escape and not part of a longer sequence.
| What's the VT100 escape code for the "esc" keyboard key itself | I'm writing a script to navigate a text-based menu system, using python's telnetlib to access a serial connection.
I can happily press the F-keys, using the escape codes. e.g. F9 = "\033OX", where "\033" is the escape sequence.
How do I encode the "esc" keyboard key? I would have expected just "\033", but that doesn't seem to work.
| [
"There is no such thing as an \"escape sequence\" for the ESC key on a VT-100 (or other terminals that used escape sequences).\nThe escape character, ASCII 27, was used to indicate that the following sequences of characters had special meaning. This usually put the terminal into a simple state machine. In general... | [
8,
6
] | [] | [] | [
"escaping",
"python",
"serial_port"
] | stackoverflow_0002420671_escaping_python_serial_port.txt |
Q:
Writing a Python mail server with authentication
I'm trying to write a simple mail server using Python.
I found smtpd that can be used as a simple smtp server, but I don't think it supports any form of authentication.
For pop or imap, I haven't found anything at all yet.
I do know Twisted has some support for both smtp and pop or imap, but I can't find any examples or tutorials about it.
An alternative would be to use Clojure, but I still have the same question:
Which libraries should I use and is there any documentation about them?
A:
Here is an example from Twisted.
And the main page. Follow the link for documentation to find the example and a tutorial.
Edit:
Check the attachment for this ticket for an example IMAP server. Definitely read the thread as it talks about the shortcomings of the example.
A:
A bit late probably but for experimentation you might also want to check pymta which is a pure-python SMTP implementation I'm using for some experiments/testing. It supports SMTP basic auth. Documentation should be at a 'decent' level, check the examples directory and the unit tests-
For anything production-related I'd go for twisted if you don't mind the asynchronous nature.
| Writing a Python mail server with authentication | I'm trying to write a simple mail server using Python.
I found smtpd that can be used as a simple smtp server, but I don't think it supports any form of authentication.
For pop or imap, I haven't found anything at all yet.
I do know Twisted has some support for both smtp and pop or imap, but I can't find any examples or tutorials about it.
An alternative would be to use Clojure, but I still have the same question:
Which libraries should I use and is there any documentation about them?
| [
"Here is an example from Twisted. \nAnd the main page. Follow the link for documentation to find the example and a tutorial.\nEdit:\nCheck the attachment for this ticket for an example IMAP server. Definitely read the thread as it talks about the shortcomings of the example.\n",
"A bit late probably but for ex... | [
2,
1
] | [] | [] | [
"clojure",
"imap",
"pop3",
"python",
"smtp"
] | stackoverflow_0003085248_clojure_imap_pop3_python_smtp.txt |
Q:
keep alive thread in PyQt4
I have a PyQt4 application, which at some point packs a big file using the tarfile module. Since the tarfile module does not implement any callback strategy, it blocks and the Qt GUI gets unresponsive.
I want the GUI to keep updating during that time. The only possibility is a separate thread.
So, I start a QThread. What do I have to do in the QThread to make the GUI update itself?
As soon, as the tar process is finished, I want the thread to finish.
Thanks!
Nathan
A:
QThread's are pretty much identical to normal Python threads so you can just use normal communication methods. However, QThreads also have a few signals available, so if you simply connect to those, than you're done.
In your GUI code do something like this and you're pretty much done:
thread = Thread()
thread.finished.connect(gui.do_update_thingy)
There is also a terminated and started signal available which you can use :)
| keep alive thread in PyQt4 | I have a PyQt4 application, which at some point packs a big file using the tarfile module. Since the tarfile module does not implement any callback strategy, it blocks and the Qt GUI gets unresponsive.
I want the GUI to keep updating during that time. The only possibility is a separate thread.
So, I start a QThread. What do I have to do in the QThread to make the GUI update itself?
As soon, as the tar process is finished, I want the thread to finish.
Thanks!
Nathan
| [
"QThread's are pretty much identical to normal Python threads so you can just use normal communication methods. However, QThreads also have a few signals available, so if you simply connect to those, than you're done.\nIn your GUI code do something like this and you're pretty much done:\nthread = Thread()\nthread.f... | [
1
] | [] | [] | [
"multithreading",
"pyqt4",
"python",
"qthread"
] | stackoverflow_0003213891_multithreading_pyqt4_python_qthread.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.