content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 35
137
|
|---|---|---|---|---|---|---|---|---|
Q:
How to handle 'self' argument with Python decorators
I am trying to setup some decorators so that I can do something like:
class Ball(object):
def __init__(self, owner):
self.owner = owner
class Example(CommandSource):
@command
@when(lambda self, ball: ball.owner == self)
def throwBall(self, ball):
# code to throw the ball
pass
e = Example()
ball = Ball(e)
commands = e.listCommands(ball) # commands = [ 'throwBall' ]
This currently doesn't work, as when the validation lambda is called, there is no self argument passed.
Now something like this works fine:
class Example(CommandSource):
@command
@when(lambda ball: ball.is_round)
def throwBall(self, ball):
pass
But this also doesn't work:
class Example(CommandSource):
def verify_owner(self, ball):
return ball.owner == self
@command
@when(verify_owner)
def throwBall(self, ball):
pass
The intent is to be able to mark methods in a class as a 'command', and the get a list of commands that are valid to run. Actually running the method is unchanged. I would like to use decorators here as it seems the least klunky way to do this. In effect I am trying to setup a little DSL using Python.
But I'm having difficulty, especially with the self argument. Here is my current implementation of command, when and CommandSource:
def command(cmd):
if getattr(cmd, 'command', False): return cmd
def wrapper(*args, **kwargs):
return cmd(*args, **kwargs)
wrapper.validators = []
wrapper.command = True
return wrapper
def when(predicate):
def createCommand(cmd):
newcmd = command(cmd)
newcmd.validators.append(predicate)
return newcmd
return createCommand
class CommandSource(object):
def listCommands(self, *args, **kwargs):
commands = []
for command in dir(self.__class__):
func = getattr(self, command, None)
if func == None or getattr(func, 'command', False) == False:
continue
valid = True
for validator in func.validators:
if not validator(*args, **kwargs):
valid = False
break
if valid:
commands.append(command)
return commands
A:
Change your CommandSource as follow:
class CommandSource(object):
def listCommands(self, *args, **kwargs):
commands = []
for command in dir(self.__class__):
func = getattr(self, command, None)
if func == None or getattr(func, 'command', False) == False:
continue
for validator in func.validators:
if not validator(self, *args, **kwargs):
break
else:
commands.append(command)
return commands
and use your very first code.
A:
You need to pass an instance reference to your validator function:
for validator in func.validators:
if not validator(self, *args, **kwargs):
valid = False
break
|
How to handle 'self' argument with Python decorators
|
I am trying to setup some decorators so that I can do something like:
class Ball(object):
def __init__(self, owner):
self.owner = owner
class Example(CommandSource):
@command
@when(lambda self, ball: ball.owner == self)
def throwBall(self, ball):
# code to throw the ball
pass
e = Example()
ball = Ball(e)
commands = e.listCommands(ball) # commands = [ 'throwBall' ]
This currently doesn't work, as when the validation lambda is called, there is no self argument passed.
Now something like this works fine:
class Example(CommandSource):
@command
@when(lambda ball: ball.is_round)
def throwBall(self, ball):
pass
But this also doesn't work:
class Example(CommandSource):
def verify_owner(self, ball):
return ball.owner == self
@command
@when(verify_owner)
def throwBall(self, ball):
pass
The intent is to be able to mark methods in a class as a 'command', and the get a list of commands that are valid to run. Actually running the method is unchanged. I would like to use decorators here as it seems the least klunky way to do this. In effect I am trying to setup a little DSL using Python.
But I'm having difficulty, especially with the self argument. Here is my current implementation of command, when and CommandSource:
def command(cmd):
if getattr(cmd, 'command', False): return cmd
def wrapper(*args, **kwargs):
return cmd(*args, **kwargs)
wrapper.validators = []
wrapper.command = True
return wrapper
def when(predicate):
def createCommand(cmd):
newcmd = command(cmd)
newcmd.validators.append(predicate)
return newcmd
return createCommand
class CommandSource(object):
def listCommands(self, *args, **kwargs):
commands = []
for command in dir(self.__class__):
func = getattr(self, command, None)
if func == None or getattr(func, 'command', False) == False:
continue
valid = True
for validator in func.validators:
if not validator(*args, **kwargs):
valid = False
break
if valid:
commands.append(command)
return commands
|
[
"Change your CommandSource as follow:\nclass CommandSource(object):\n\n def listCommands(self, *args, **kwargs):\n commands = []\n for command in dir(self.__class__):\n func = getattr(self, command, None)\n if func == None or getattr(func, 'command', False) == False:\n continue\n for validator in func.validators:\n if not validator(self, *args, **kwargs):\n break\n else:\n commands.append(command)\n return commands\n\nand use your very first code.\n",
"You need to pass an instance reference to your validator function:\nfor validator in func.validators:\n if not validator(self, *args, **kwargs):\n valid = False\n break\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"decorator",
"dsl",
"python"
] |
stackoverflow_0002546801_decorator_dsl_python.txt
|
Q:
Optimization Techniques in Python
Recently i have developed a billing application for my company with Python/Django. For few months everything was fine but now i am observing that the performance is dropping because of more and more users using that applications. Now the problem is that the application is now very critical for the finance team. Now the finance team are after my life for sorting out the performance issue. I have no other option but to find a way to increase the performance of the billing application.
So do you guys know any performance optimization techniques in python that will really help me with the scalability issue
Guys we are using mysql database and its hosted on apache web server on Linux box. Secondly what i have noticed more is the over all application is slow and not the database transactional part. For example once the application is loaded then it works fine but if they navigate to other link on that application then it takes a whole lot of time.
And yes we are using HTML, CSS and Javascript
A:
As I said in comment, you must start by finding what part of your code is slow.
Nobody can help you without this information.
You can profile your code with the Python profilers then go back to us with the result.
If it's a Web app, the first suspect is generally the database. If it's a calculus intensive GUI app, then look first at the calculations algo first.
But remember that perf issues car be highly unintuitive and therefor, an objective assessment is the only way to go.
A:
ok, not entirely to the point, but before you go and start fixing it, make sure everyone understands the situation. it seems to me that they're putting some pressure on you to fix the "problem".
well first of all, when you wrote the application, have they specified the performance requirements? did they tell you that they need operation X to take less than Y secs to complete? Did they specify how many concurrent users must be supported without penalty to the performance? If not, then tell them to back off and that it is iteration (phase, stage, whatever) one of the deployment, and the main goal was the functionality and testing. phase two is performance improvements. let them (with your help obviously) come up with some non functional requirements for the performance of your system.
by doing all this, a) you'll remove the pressure applied by the finance team (and i know they can be a real pain in the bum) b) both you and your clients will have a clear idea of what you mean by "performance" c) you'll have a base that you can measure your progress and most importantly d) you'll have some agreed time to implement/fix the performance issues.
PS. that aside, look at the indexing... :)
A:
A surprising feature of Python is that the pythonic code is quite efficient... So a few general hints:
Use built-ins and standard functions whenever possible, they're already quite well optimized.
Try to use lazy generators instead one-off temporary lists.
Use numpy for vector arithmetic.
Use psyco if running on x86 32bit.
Write performance critical loops in a lower level language (C, Pyrex, Cython, etc.).
When calling the same method of a collection of objects, get a reference to the class function and use it, it will save lookups in the objects dictionaries (this one is a micro-optimization, not sure it's worth)
And of course, if scalability is what matters:
Use O(n) (or better) algorithms! Otherwise your system cannot be linearly scalable.
Write multiprocessor aware code. At some point you'll need to throw more computing power at it, and your software must be ready to use it!
A:
before you can "fix" something you need to know what is "broken". In software development that means profiling, profiling, profiling. Did I mention profiling. Without profiling you don't know where CPU cycles and wall clock time is going. Like others have said to get any more useful information you need to post the details of your entire stack. Python version, what you are using to store the data in (mysql, postgres, flat files, etc), what web server interface cgi, fcgi, wsgi, passenger, etc. how you are generating the HTML, CSS and assuming Javascript. Then you can get more specific answers to those tiers.
A:
You may be interested in this document I've found some time ago.
As personal advice, be as more pythonic as you can: lazy evaluation is the keyword, so learn to use iterators and generators.
A:
For the type of application you are describing (a web application probably backed by a database) your performance problems are unlikely to be language specific. They are far more likely to stem from design or architecture issues, though they could be simple coding problems too.
To sort this out you need to figure out where the bottlenecks are in your application and for that you need some sort of profiler.
Once you have found your bottlenecks you will be in a much better position. You can evaluate then problem areas for common issues including:
Design and Architecture issues
SQL anti-patterns
Incorrect usage of your framework (perhaps relying on inappropriate defaults)
Badly structured algorithms
The specifics of any solution are going to depend on the specifics of the bottlenecks your find.
A:
http://wiki.python.org/moin/PythonSpeed/PerformanceTips
I optimized some python code a while back, the most surprising thing to me was how much each function call costs. If you minimize function calls or replace loops with builtins you'll be running much faster.
A:
There are some great suggestions here… So let me suggest an implementation detail. I have found the runprofileserver command found in django-command-extensions very convenient for profiling my Django code.
A:
I am not sure if this would solve the problem but you should have a look at psyco
|
Optimization Techniques in Python
|
Recently i have developed a billing application for my company with Python/Django. For few months everything was fine but now i am observing that the performance is dropping because of more and more users using that applications. Now the problem is that the application is now very critical for the finance team. Now the finance team are after my life for sorting out the performance issue. I have no other option but to find a way to increase the performance of the billing application.
So do you guys know any performance optimization techniques in python that will really help me with the scalability issue
Guys we are using mysql database and its hosted on apache web server on Linux box. Secondly what i have noticed more is the over all application is slow and not the database transactional part. For example once the application is loaded then it works fine but if they navigate to other link on that application then it takes a whole lot of time.
And yes we are using HTML, CSS and Javascript
|
[
"As I said in comment, you must start by finding what part of your code is slow.\nNobody can help you without this information.\nYou can profile your code with the Python profilers then go back to us with the result.\nIf it's a Web app, the first suspect is generally the database. If it's a calculus intensive GUI app, then look first at the calculations algo first.\nBut remember that perf issues car be highly unintuitive and therefor, an objective assessment is the only way to go.\n",
"ok, not entirely to the point, but before you go and start fixing it, make sure everyone understands the situation. it seems to me that they're putting some pressure on you to fix the \"problem\".\nwell first of all, when you wrote the application, have they specified the performance requirements? did they tell you that they need operation X to take less than Y secs to complete? Did they specify how many concurrent users must be supported without penalty to the performance? If not, then tell them to back off and that it is iteration (phase, stage, whatever) one of the deployment, and the main goal was the functionality and testing. phase two is performance improvements. let them (with your help obviously) come up with some non functional requirements for the performance of your system.\nby doing all this, a) you'll remove the pressure applied by the finance team (and i know they can be a real pain in the bum) b) both you and your clients will have a clear idea of what you mean by \"performance\" c) you'll have a base that you can measure your progress and most importantly d) you'll have some agreed time to implement/fix the performance issues.\nPS. that aside, look at the indexing... :)\n",
"A surprising feature of Python is that the pythonic code is quite efficient... So a few general hints:\n\nUse built-ins and standard functions whenever possible, they're already quite well optimized.\nTry to use lazy generators instead one-off temporary lists.\nUse numpy for vector arithmetic.\nUse psyco if running on x86 32bit.\nWrite performance critical loops in a lower level language (C, Pyrex, Cython, etc.).\nWhen calling the same method of a collection of objects, get a reference to the class function and use it, it will save lookups in the objects dictionaries (this one is a micro-optimization, not sure it's worth)\n\nAnd of course, if scalability is what matters:\n\nUse O(n) (or better) algorithms! Otherwise your system cannot be linearly scalable.\nWrite multiprocessor aware code. At some point you'll need to throw more computing power at it, and your software must be ready to use it!\n\n",
"before you can \"fix\" something you need to know what is \"broken\". In software development that means profiling, profiling, profiling. Did I mention profiling. Without profiling you don't know where CPU cycles and wall clock time is going. Like others have said to get any more useful information you need to post the details of your entire stack. Python version, what you are using to store the data in (mysql, postgres, flat files, etc), what web server interface cgi, fcgi, wsgi, passenger, etc. how you are generating the HTML, CSS and assuming Javascript. Then you can get more specific answers to those tiers.\n",
"You may be interested in this document I've found some time ago.\nAs personal advice, be as more pythonic as you can: lazy evaluation is the keyword, so learn to use iterators and generators.\n",
"For the type of application you are describing (a web application probably backed by a database) your performance problems are unlikely to be language specific. They are far more likely to stem from design or architecture issues, though they could be simple coding problems too.\nTo sort this out you need to figure out where the bottlenecks are in your application and for that you need some sort of profiler.\nOnce you have found your bottlenecks you will be in a much better position. You can evaluate then problem areas for common issues including:\n\nDesign and Architecture issues\nSQL anti-patterns\nIncorrect usage of your framework (perhaps relying on inappropriate defaults)\nBadly structured algorithms\n\nThe specifics of any solution are going to depend on the specifics of the bottlenecks your find.\n",
"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\nI optimized some python code a while back, the most surprising thing to me was how much each function call costs. If you minimize function calls or replace loops with builtins you'll be running much faster.\n",
"There are some great suggestions here… So let me suggest an implementation detail. I have found the runprofileserver command found in django-command-extensions very convenient for profiling my Django code.\n",
"I am not sure if this would solve the problem but you should have a look at psyco\n"
] |
[
11,
6,
4,
2,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002545820_python.txt
|
Q:
How to update the filename of a Django's FileField instance?
Here a simple django model:
class SomeModel(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='video')
I would like to save any instance so that the video's file name would be a valid file name of the title.
For example, in the admin interface, I load a new instance with title "Lorem ipsum" and a video called "video.avi". The copy of the file on the server should be "Lorem Ipsum.avi" (or "Lorem_Ipsum.avi").
Thank you :)
A:
If it just happens during save, as per the docs, you can pass a function to upload_to that will get called with the instance and the original filename and needs to return a string to be used as the filename. Maybe something like:
from django.template.defaultfilters import slugify
class SomeModel(models.Model):
title = models.CharField(max_length=100)
def video_filename(instance, filename):
fname, dot, extension = filename.rpartition('.')
slug = slugify(instance.title)
return '%s.%s' % (slug, extension)
video = models.FileField(upload_to=video_filename)
|
How to update the filename of a Django's FileField instance?
|
Here a simple django model:
class SomeModel(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='video')
I would like to save any instance so that the video's file name would be a valid file name of the title.
For example, in the admin interface, I load a new instance with title "Lorem ipsum" and a video called "video.avi". The copy of the file on the server should be "Lorem Ipsum.avi" (or "Lorem_Ipsum.avi").
Thank you :)
|
[
"If it just happens during save, as per the docs, you can pass a function to upload_to that will get called with the instance and the original filename and needs to return a string to be used as the filename. Maybe something like:\nfrom django.template.defaultfilters import slugify\nclass SomeModel(models.Model):\n title = models.CharField(max_length=100)\n def video_filename(instance, filename):\n fname, dot, extension = filename.rpartition('.')\n slug = slugify(instance.title)\n return '%s.%s' % (slug, extension) \n video = models.FileField(upload_to=video_filename)\n\n"
] |
[
11
] |
[] |
[] |
[
"django",
"field",
"file",
"model",
"python"
] |
stackoverflow_0002546575_django_field_file_model_python.txt
|
Q:
What is the equivalent for pycassa ColumnFamily.get_range() with Lazyboy?
I think everything is in the question.
I'm looking for the Lazyboy equivalent for Pycassa ColumnFamily.get_range() -- with features like column_start, column_finish et column_count --.
Thanks.
A:
check out this file in lazyboy:
http://github.com/digg/lazyboy/blob/master/lazyboy/iterators.py
it has a few different range methods.
E.g., line 121: def key_range(key, start="", finish="", count=100):
or you could use this when you need to apply slice predicates:
def slice_iterator(key, consistency, **predicate_args):
HTH
|
What is the equivalent for pycassa ColumnFamily.get_range() with Lazyboy?
|
I think everything is in the question.
I'm looking for the Lazyboy equivalent for Pycassa ColumnFamily.get_range() -- with features like column_start, column_finish et column_count --.
Thanks.
|
[
"check out this file in lazyboy:\nhttp://github.com/digg/lazyboy/blob/master/lazyboy/iterators.py\nit has a few different range methods. \nE.g., line 121: def key_range(key, start=\"\", finish=\"\", count=100):\nor you could use this when you need to apply slice predicates:\ndef slice_iterator(key, consistency, **predicate_args):\nHTH\n"
] |
[
1
] |
[] |
[] |
[
"cassandra",
"database",
"nosql",
"python"
] |
stackoverflow_0002540040_cassandra_database_nosql_python.txt
|
Q:
Python: fetching SVG file using urllib is returning binary when I need ASCII
I'm using urllib (in Python) to fetch an SVG file:
import urllib
urllib.urlopen('http://alpha.vectors.cloudmade.com/BC9A493B41014CAABB98F0471D759707/-122.2487,37.87588,-122.265823,37.868054?styleid=1&viewport=400x231').read()
which produces output of the sort:
xb6\xf6\x00\xb3\xfb2\xff\xda\xc5\xf2\xc2\x14\xef\xcd\x82\x0b\xdbU\xb0\x81\xcaF\xd8\x1a\xf6\xdf[i)\xba\xcf\x80\xab\xd6\x8c\xe3l_\xe7\n\xed2,\xbdm\xa0_|\xbb\x12\xff\xb6\xf8\xda\xd9\xc3\xd9\t\xde\x9a\xf8\xae\xb3T\xa3\r`\x8a\x08!T\xfb8\x92\x95\x0c\xdd\x8b!\x02P\xea@\x98\x1c^\xc7\xda\\\xec\xe3\xe1\xbe,0\xcd\xbeZ~\x92\xb3\xfa\xdd\xfcbyu\xb8\x83\xbb\xbdS\x0f\x82\x0b\xfe\xf5_\xdawn\xff\xef_\xff\xe5\xfa\x1f?\xbf\xffoZ\x0f\x8b\xbfV\xf4\x04\x00'
when I was expecting more like this:
<?xml version='1.0' encoding='UTF-8'?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:cm="http://cloudmade.com/" width="400" height="231"> <rect width="100%" height="100%" fill="#eae8dd" opacity="1"/> <g transform="scale(0.209849975856)">
<g transform="translate(13610569, 4561906)" flood-opacity="0.1" flood-color="grey">
<path d="M -13610027.720000000670552 -4562403.660000000149012
I guess this is an issue of binary vs. ASCII. Can anyone help me (a Python newbie) with the appropriate conversion so that I can get on with parsing and manipulating the SVG code?
A:
It's gzip-compressed (check the Content-Encoding HTTP header). You can use the gzip module to decompress it.
|
Python: fetching SVG file using urllib is returning binary when I need ASCII
|
I'm using urllib (in Python) to fetch an SVG file:
import urllib
urllib.urlopen('http://alpha.vectors.cloudmade.com/BC9A493B41014CAABB98F0471D759707/-122.2487,37.87588,-122.265823,37.868054?styleid=1&viewport=400x231').read()
which produces output of the sort:
xb6\xf6\x00\xb3\xfb2\xff\xda\xc5\xf2\xc2\x14\xef\xcd\x82\x0b\xdbU\xb0\x81\xcaF\xd8\x1a\xf6\xdf[i)\xba\xcf\x80\xab\xd6\x8c\xe3l_\xe7\n\xed2,\xbdm\xa0_|\xbb\x12\xff\xb6\xf8\xda\xd9\xc3\xd9\t\xde\x9a\xf8\xae\xb3T\xa3\r`\x8a\x08!T\xfb8\x92\x95\x0c\xdd\x8b!\x02P\xea@\x98\x1c^\xc7\xda\\\xec\xe3\xe1\xbe,0\xcd\xbeZ~\x92\xb3\xfa\xdd\xfcbyu\xb8\x83\xbb\xbdS\x0f\x82\x0b\xfe\xf5_\xdawn\xff\xef_\xff\xe5\xfa\x1f?\xbf\xffoZ\x0f\x8b\xbfV\xf4\x04\x00'
when I was expecting more like this:
<?xml version='1.0' encoding='UTF-8'?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:cm="http://cloudmade.com/" width="400" height="231"> <rect width="100%" height="100%" fill="#eae8dd" opacity="1"/> <g transform="scale(0.209849975856)">
<g transform="translate(13610569, 4561906)" flood-opacity="0.1" flood-color="grey">
<path d="M -13610027.720000000670552 -4562403.660000000149012
I guess this is an issue of binary vs. ASCII. Can anyone help me (a Python newbie) with the appropriate conversion so that I can get on with parsing and manipulating the SVG code?
|
[
"It's gzip-compressed (check the Content-Encoding HTTP header). You can use the gzip module to decompress it.\n"
] |
[
2
] |
[] |
[] |
[
"ascii",
"binary_data",
"python",
"urllib"
] |
stackoverflow_0002547937_ascii_binary_data_python_urllib.txt
|
Q:
Problem with building OpenCV for Python 2.6
I've just downloaded OpenCV's trunk and now I'm trying to build it with MinGW. I read the manual and get .dll's compiled, but that's all - "interfaces/python" contains only some .i and .cmake files. How can I really get new python interface? Where I can find new cv.pyd/libcv.dll.a (because a compiled version from official site crashes sometimes and I saw this bug as "fixed" in Trac)?
A:
Since you downloaded the source from trunk, you will also have to build all of OpenCV before you can use it or the Python wrappers. Have you compiled it?
If not, check the directions on http://opencv.willowgarage.com/wiki/InstallGuide under the "Building OpenCV from source using CMake" heading. There is also a section at the bottom specifc to MinGW.
|
Problem with building OpenCV for Python 2.6
|
I've just downloaded OpenCV's trunk and now I'm trying to build it with MinGW. I read the manual and get .dll's compiled, but that's all - "interfaces/python" contains only some .i and .cmake files. How can I really get new python interface? Where I can find new cv.pyd/libcv.dll.a (because a compiled version from official site crashes sometimes and I saw this bug as "fixed" in Trac)?
|
[
"Since you downloaded the source from trunk, you will also have to build all of OpenCV before you can use it or the Python wrappers. Have you compiled it?\nIf not, check the directions on http://opencv.willowgarage.com/wiki/InstallGuide under the \"Building OpenCV from source using CMake\" heading. There is also a section at the bottom specifc to MinGW.\n"
] |
[
0
] |
[] |
[] |
[
"opencv",
"python"
] |
stackoverflow_0002546151_opencv_python.txt
|
Q:
Why is python decode replacing more than the invalid bytes from an encoded string?
Trying to decode an invalid encoded utf-8 html page gives different results in
python, firefox and chrome.
The invalid encoded fragment from test page looks like 'PREFIX\xe3\xabSUFFIX'
>>> fragment = 'PREFIX\xe3\xabSUFFIX'
>>> fragment.decode('utf-8', 'strict')
...
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 6-8: invalid data
UPDATE: This question concluded in a bug report to Python unicode component. The Issue is reported to be fixed in Python 2.7.11 and 3.5.2.
What follows is the replacement policies used to handle decoding errors in
Python, Firefox and Chrome. Note how they differs, and specially how
python builtin removes the valid S (plus the invalid sequence of bytes).
Python
The builtin replace error handler replaces the invalid \xe3\xab plus the
S from SUFFIX by U+FFFD
>>> fragment.decode('utf-8', 'replace')
u'PREFIX\ufffdUFFIX'
>>> print _
PREFIX�UFFIX
Browsers
To tests how browsers decode the invalid sequence of bytes will use a cgi script:
#!/usr/bin/env python
print """\
Content-Type: text/plain; charset=utf-8
PREFIX\xe3\xabSUFFIX"""
Firefox and Chrome browsers rendered:
PREFIX�SUFFIX
Why builtin replace error handler for str.decode is removing the S from SUFFIX
(Was UPDATE 1)
According to wikipedia UTF-8 (thanks mjv),
the following ranges of bytes are used to indicate the start of a sequence of
bytes
0xC2-0xDF : Start of 2-byte sequence
0xE0-0xEF : Start of 3-byte sequence
0xF0-0xF4 : Start of 4-byte sequence
'PREFIX\xe3\abSUFFIX' test fragment has 0xE3, it instructs python decoder
that a 3-byte sequence follows, the sequence is found invalid and python
decoder ignores the whole sequence including '\xabS', and continues after it
ignoring any possible correct sequence starting in the middle.
This means that for an invalid encoded sequence like '\xF0SUFFIX', it will
decode u'\ufffdFIX' instead of u'\ufffdSUFFIX'.
Example 1: Introducing DOM parsing bugs
>>> '<div>\xf0<div>Price: $20</div>...</div>'.decode('utf-8', 'replace')
u'<div>\ufffdv>Price: $20</div>...</div>'
>>> print _
<div>�v>Price: $20</div>...</div>
Example 2: Security issues (Also see Unicode security considerations):
>>> '\xf0<!-- <script>alert("hi!");</script> -->'.decode('utf-8', 'replace')
u'\ufffd- <script>alert("hi!");</script> -->'
>>> print _
�- <script>alert("hi!");</script> -->
Example 3: Remove valid information for a scraping application
>>> '\xf0' + u'it\u2019s'.encode('utf-8') # "it’s"
'\xf0it\xe2\x80\x99s'
>>> _.decode('utf-8', 'replace')
u'\ufffd\ufffd\ufffds'
>>> print _
���s
Using a cgi script to render this in browsers:
#!/usr/bin/env python
print """\
Content-Type: text/plain; charset=utf-8
\xf0it\xe2\x80\x99s"""
Rendered:
�it’s
Is there any official recommended way for handling decoding replacements?
(Was UPDATE 2)
In a public review, the Unicode Technical Committee has opted for option 2
of the following candidates:
Replace the entire ill-formed subsequence by a single U+FFFD.
Replace each maximal subpart of the ill-formed subsequence by a single U+FFFD.
Replace each code unit of the ill-formed subsequence by a single U+FFFD.
UTC Resolution was at 2008-08-29, source: http://www.unicode.org/review/resolved-pri-100.html
UTC Public Review 121 also includes an invalid bytestream as example
'\x61\xF1\x80\x80\xE1\x80\xC2\x62', it shows decoding results for each
option.
61 F1 80 80 E1 80 C2 62
1 U+0061 U+FFFD U+0062
2 U+0061 U+FFFD U+FFFD U+FFFD U+0062
3 U+0061 U+FFFD U+FFFD U+FFFD U+FFFD U+FFFD U+FFFD U+0062
In plain Python the three results are:
u'a\ufffdb' shows as a�b
u'a\ufffd\ufffd\ufffdb' shows as a���b
u'a\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdb' shows as a������b
And here is what python does for the invalid example bytestream:
>>> '\x61\xF1\x80\x80\xE1\x80\xC2\x62'.decode('utf-8', 'replace')
u'a\ufffd\ufffd\ufffd'
>>> print _
a���
Again, using a cgi script to test how browsers render the buggy encoded bytes:
#!/usr/bin/env python
print """\
Content-Type: text/plain; charset=utf-8
\x61\xF1\x80\x80\xE1\x80\xC2\x62"""
Both, Chrome and Firefox rendered:
a���b
Note that browsers rendered result matches option 2 of PR121 recomendation
While option 3 looks easily implementable in python, option 2 and 1 are a challenge.
>>> replace_option3 = lambda exc: (u'\ufffd', exc.start+1)
>>> codecs.register_error('replace_option3', replace_option3)
>>> '\x61\xF1\x80\x80\xE1\x80\xC2\x62'.decode('utf-8', 'replace_option3')
u'a\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdb'
>>> print _
a������b
A:
the 0xE3 byte is one (of the possible) first bytes indicative of a 3-bytes character.
Apparently Python's decode logic takes these three bytes and tries to decode them. They turn out to not match an actual code point ("character") and that is why Python produces a UnicodeDecodeError and emits a substitution character
It appears, however that in doing so, Python's decode logic doesn't adhere to the recommendation of the Unicode Consortium with regards to substitution characters for "ill-formed" UTF-8 sequences.
See UTF-8 article on Wikipedia for background info about UTF-8 encoding.
New (final?) Edit: re the UniCode Consortium's recommended practice for replacement characters (PR121)
(BTW, congrats to dangra to keep digging and digging and hence making the question better)
Both dangra and I were partially incorrect, in our own way, regarding the interpretation of this recommendation; my latest insight is that indeed the recommendation also speaks to trying and "re-synchronize".
The key concept is that of the maximal subpart [of an ill-formed sequence].
In view of the (lone) example supplied in the PR121 document, the "maximal subpart" implies not reading-in the bytes which could not possibly be part of a sequence. For example, the 5th byte in the sequence, 0xE1 could NOT possibly be a "second, third or fourth byte of a sequence" since it isn't in the x80-xBF range, and hence this terminates the ill-formed sequence which started with xF1. Then one must try and start a new sequence with the xE1 etc. Similarly, upon hitting the x62 which too cannot be interpreted as a second/third/fourth byte, the bad sequence is ended, and the "b" (x62) is "saved"...
In this light (and until corrected ;-) ) the Python decoding logic appears to be faulty.
Also see John Machin's answer in this post for more specific quotes of the underlying Unicode standard/recommendations.
A:
You know that your S is valid, with the benefit of both look-ahead and hindsight :-) Suppose there was originally a legal 3-byte UTF-8 sequence there, and the 3rd byte was corrupted in transmission ... with the change that you mention, you'd be complaining that a spurious S had not been replaced. There is no "right" way of doing it, without the benefit of error-correcting codes, or a crystal ball, or a tamborine.
Update
As @mjv remarked, the UTC issue is all about how many U+FFFD should be included.
In fact, Python is not using ANY of the UTC's 3 options.
Here is the UTC's sole example:
61 F1 80 80 E1 80 C2 62
1 U+0061 U+FFFD U+0062
2 U+0061 U+FFFD U+FFFD U+FFFD U+0062
3 U+0061 U+FFFD U+FFFD U+FFFD U+FFFD U+FFFD U+FFFD U+0062
Here is what Python does:
>>> bad = '\x61\xf1\x80\x80\xe1\x80\xc2\x62cdef'
>>> bad.decode('utf8', 'replace')
u'a\ufffd\ufffd\ufffdcdef'
>>>
Why?
F1 should start a 4-byte sequence, but the E1 is not valid. One bad sequence, one replacement.
Start again at the next byte, the 3rd 80. Bang, another FFFD.
Start again at the C2, which introduces a 2-byte sequence, but C2 62 is invalid, so bang again.
It's interesting that the UTC didn't mention what Python is doing (restarting after the number of bytes indicated by the lead character). Perhaps this is actually forbidden or deprecated somewhere in the Unicode standard. More reading required. Watch this space.
Update 2 Houston, we have a problem.
=== Quoted from Chapter 3 of Unicode 5.2 ===
Constraints on Conversion Processes
The requirement not to interpret any ill-formed code unit subsequences in a string as characters (see conformance clause C10) has important consequences for conversion processes.
Such processes may, for example, interpret UTF-8 code unit sequences as Unicode character
sequences. If the converter encounters an ill-formed UTF-8 code unit sequence which
starts with a valid first byte, but which does not continue with valid successor bytes (see
Table 3-7), it must not consume the successor bytes as part of the ill-formed subsequence
whenever those successor bytes themselves constitute part of a well-formed UTF-8 code
unit subsequence.
If an implementation of a UTF-8 conversion process stops at the first error encountered,
without reporting the end of any ill-formed UTF-8 code unit subsequence, then the
requirement makes little practical difference. However, the requirement does introduce a
significant constraint if the UTF-8 converter continues past the point of a detected error,
perhaps by substituting one or more U+FFFD replacement characters for the uninterpretable,
ill-formed UTF-8 code unit subsequence. For example, with the input UTF-8 code
unit sequence <C2 41 42>, such a UTF-8 conversion process must not return <U+FFFD>
or <U+FFFD, U+0042>, because either of those outputs would be the result of misinterpreting a well-formed subsequence as being part of the ill-formed subsequence. The
expected return value for such a process would instead be <U+FFFD, U+0041, U+0042>.
For a UTF-8 conversion process to consume valid successor bytes is not only non-conformant,
but also leaves the converter open to security exploits. See Unicode Technical Report
#36, “Unicode Security Considerations.”
=== End of quote ===
It then goes on to discuss at length, with examples, the "how many FFFD to emit" issue.
Using their example in the 2nd last quoted paragraph:
>>> bad2 = "\xc2\x41\x42"
>>> bad2.decode('utf8', 'replace')
u'\ufffdB'
# FAIL
Note that this is a problem with both the 'replace' and 'ignore' options of str.decode('utf_8') -- it's all about omitting data, not about how many U+FFFD are emitted; get the data-emitting part right and the U+FFFD issue falls out naturally, as explained in the part that I didn't quote.
Update 3 Current versions of Python (including 2.7) have unicodedata.unidata_version as '5.1.0' which may or may not indicate that the Unicode-related code is intended to conform to Unicode 5.1.0. In any case, the wordy prohibition of what Python is doing didn't appear in the Unicode standard until 5.2.0. I'll raise an issue on the Python tracker without mentioning the word 'oht'.encode('rot13').
Reported here
A:
In 'PREFIX\xe3\xabSUFFIX', the \xe3 indicates that it and the next two bites form one unicode code point. (\xEy does for all y.) However, \xe3\xabS obviously does not refer to a valid code point. Since Python knows it's supposed to take three bytes, it sucks up all three anyhow since it doesn't know your S is an S and not just some byte representing 0x53 for some other reason.
A:
Also, is there any unicode's official recommended way for handling decoding replacements?
No. Unicode considers them an error condition and doesn't consider any fallback options. So none of the behaviours above are ‘right’.
|
Why is python decode replacing more than the invalid bytes from an encoded string?
|
Trying to decode an invalid encoded utf-8 html page gives different results in
python, firefox and chrome.
The invalid encoded fragment from test page looks like 'PREFIX\xe3\xabSUFFIX'
>>> fragment = 'PREFIX\xe3\xabSUFFIX'
>>> fragment.decode('utf-8', 'strict')
...
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 6-8: invalid data
UPDATE: This question concluded in a bug report to Python unicode component. The Issue is reported to be fixed in Python 2.7.11 and 3.5.2.
What follows is the replacement policies used to handle decoding errors in
Python, Firefox and Chrome. Note how they differs, and specially how
python builtin removes the valid S (plus the invalid sequence of bytes).
Python
The builtin replace error handler replaces the invalid \xe3\xab plus the
S from SUFFIX by U+FFFD
>>> fragment.decode('utf-8', 'replace')
u'PREFIX\ufffdUFFIX'
>>> print _
PREFIX�UFFIX
Browsers
To tests how browsers decode the invalid sequence of bytes will use a cgi script:
#!/usr/bin/env python
print """\
Content-Type: text/plain; charset=utf-8
PREFIX\xe3\xabSUFFIX"""
Firefox and Chrome browsers rendered:
PREFIX�SUFFIX
Why builtin replace error handler for str.decode is removing the S from SUFFIX
(Was UPDATE 1)
According to wikipedia UTF-8 (thanks mjv),
the following ranges of bytes are used to indicate the start of a sequence of
bytes
0xC2-0xDF : Start of 2-byte sequence
0xE0-0xEF : Start of 3-byte sequence
0xF0-0xF4 : Start of 4-byte sequence
'PREFIX\xe3\abSUFFIX' test fragment has 0xE3, it instructs python decoder
that a 3-byte sequence follows, the sequence is found invalid and python
decoder ignores the whole sequence including '\xabS', and continues after it
ignoring any possible correct sequence starting in the middle.
This means that for an invalid encoded sequence like '\xF0SUFFIX', it will
decode u'\ufffdFIX' instead of u'\ufffdSUFFIX'.
Example 1: Introducing DOM parsing bugs
>>> '<div>\xf0<div>Price: $20</div>...</div>'.decode('utf-8', 'replace')
u'<div>\ufffdv>Price: $20</div>...</div>'
>>> print _
<div>�v>Price: $20</div>...</div>
Example 2: Security issues (Also see Unicode security considerations):
>>> '\xf0<!-- <script>alert("hi!");</script> -->'.decode('utf-8', 'replace')
u'\ufffd- <script>alert("hi!");</script> -->'
>>> print _
�- <script>alert("hi!");</script> -->
Example 3: Remove valid information for a scraping application
>>> '\xf0' + u'it\u2019s'.encode('utf-8') # "it’s"
'\xf0it\xe2\x80\x99s'
>>> _.decode('utf-8', 'replace')
u'\ufffd\ufffd\ufffds'
>>> print _
���s
Using a cgi script to render this in browsers:
#!/usr/bin/env python
print """\
Content-Type: text/plain; charset=utf-8
\xf0it\xe2\x80\x99s"""
Rendered:
�it’s
Is there any official recommended way for handling decoding replacements?
(Was UPDATE 2)
In a public review, the Unicode Technical Committee has opted for option 2
of the following candidates:
Replace the entire ill-formed subsequence by a single U+FFFD.
Replace each maximal subpart of the ill-formed subsequence by a single U+FFFD.
Replace each code unit of the ill-formed subsequence by a single U+FFFD.
UTC Resolution was at 2008-08-29, source: http://www.unicode.org/review/resolved-pri-100.html
UTC Public Review 121 also includes an invalid bytestream as example
'\x61\xF1\x80\x80\xE1\x80\xC2\x62', it shows decoding results for each
option.
61 F1 80 80 E1 80 C2 62
1 U+0061 U+FFFD U+0062
2 U+0061 U+FFFD U+FFFD U+FFFD U+0062
3 U+0061 U+FFFD U+FFFD U+FFFD U+FFFD U+FFFD U+FFFD U+0062
In plain Python the three results are:
u'a\ufffdb' shows as a�b
u'a\ufffd\ufffd\ufffdb' shows as a���b
u'a\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdb' shows as a������b
And here is what python does for the invalid example bytestream:
>>> '\x61\xF1\x80\x80\xE1\x80\xC2\x62'.decode('utf-8', 'replace')
u'a\ufffd\ufffd\ufffd'
>>> print _
a���
Again, using a cgi script to test how browsers render the buggy encoded bytes:
#!/usr/bin/env python
print """\
Content-Type: text/plain; charset=utf-8
\x61\xF1\x80\x80\xE1\x80\xC2\x62"""
Both, Chrome and Firefox rendered:
a���b
Note that browsers rendered result matches option 2 of PR121 recomendation
While option 3 looks easily implementable in python, option 2 and 1 are a challenge.
>>> replace_option3 = lambda exc: (u'\ufffd', exc.start+1)
>>> codecs.register_error('replace_option3', replace_option3)
>>> '\x61\xF1\x80\x80\xE1\x80\xC2\x62'.decode('utf-8', 'replace_option3')
u'a\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdb'
>>> print _
a������b
|
[
"the 0xE3 byte is one (of the possible) first bytes indicative of a 3-bytes character.\nApparently Python's decode logic takes these three bytes and tries to decode them. They turn out to not match an actual code point (\"character\") and that is why Python produces a UnicodeDecodeError and emits a substitution character\nIt appears, however that in doing so, Python's decode logic doesn't adhere to the recommendation of the Unicode Consortium with regards to substitution characters for \"ill-formed\" UTF-8 sequences.\nSee UTF-8 article on Wikipedia for background info about UTF-8 encoding.\nNew (final?) Edit: re the UniCode Consortium's recommended practice for replacement characters (PR121)\n(BTW, congrats to dangra to keep digging and digging and hence making the question better)\nBoth dangra and I were partially incorrect, in our own way, regarding the interpretation of this recommendation; my latest insight is that indeed the recommendation also speaks to trying and \"re-synchronize\".\nThe key concept is that of the maximal subpart [of an ill-formed sequence].\nIn view of the (lone) example supplied in the PR121 document, the \"maximal subpart\" implies not reading-in the bytes which could not possibly be part of a sequence. For example, the 5th byte in the sequence, 0xE1 could NOT possibly be a \"second, third or fourth byte of a sequence\" since it isn't in the x80-xBF range, and hence this terminates the ill-formed sequence which started with xF1. Then one must try and start a new sequence with the xE1 etc. Similarly, upon hitting the x62 which too cannot be interpreted as a second/third/fourth byte, the bad sequence is ended, and the \"b\" (x62) is \"saved\"...\nIn this light (and until corrected ;-) ) the Python decoding logic appears to be faulty.\nAlso see John Machin's answer in this post for more specific quotes of the underlying Unicode standard/recommendations.\n",
"You know that your S is valid, with the benefit of both look-ahead and hindsight :-) Suppose there was originally a legal 3-byte UTF-8 sequence there, and the 3rd byte was corrupted in transmission ... with the change that you mention, you'd be complaining that a spurious S had not been replaced. There is no \"right\" way of doing it, without the benefit of error-correcting codes, or a crystal ball, or a tamborine.\nUpdate\nAs @mjv remarked, the UTC issue is all about how many U+FFFD should be included.\nIn fact, Python is not using ANY of the UTC's 3 options.\nHere is the UTC's sole example:\n 61 F1 80 80 E1 80 C2 62\n1 U+0061 U+FFFD U+0062\n2 U+0061 U+FFFD U+FFFD U+FFFD U+0062\n3 U+0061 U+FFFD U+FFFD U+FFFD U+FFFD U+FFFD U+FFFD U+0062\n\nHere is what Python does:\n>>> bad = '\\x61\\xf1\\x80\\x80\\xe1\\x80\\xc2\\x62cdef'\n>>> bad.decode('utf8', 'replace')\nu'a\\ufffd\\ufffd\\ufffdcdef'\n>>>\n\nWhy?\nF1 should start a 4-byte sequence, but the E1 is not valid. One bad sequence, one replacement.\nStart again at the next byte, the 3rd 80. Bang, another FFFD.\nStart again at the C2, which introduces a 2-byte sequence, but C2 62 is invalid, so bang again. \nIt's interesting that the UTC didn't mention what Python is doing (restarting after the number of bytes indicated by the lead character). Perhaps this is actually forbidden or deprecated somewhere in the Unicode standard. More reading required. Watch this space.\nUpdate 2 Houston, we have a problem.\n=== Quoted from Chapter 3 of Unicode 5.2 ===\nConstraints on Conversion Processes\nThe requirement not to interpret any ill-formed code unit subsequences in a string as characters (see conformance clause C10) has important consequences for conversion processes.\nSuch processes may, for example, interpret UTF-8 code unit sequences as Unicode character\nsequences. If the converter encounters an ill-formed UTF-8 code unit sequence which\nstarts with a valid first byte, but which does not continue with valid successor bytes (see\nTable 3-7), it must not consume the successor bytes as part of the ill-formed subsequence\nwhenever those successor bytes themselves constitute part of a well-formed UTF-8 code\nunit subsequence.\nIf an implementation of a UTF-8 conversion process stops at the first error encountered,\nwithout reporting the end of any ill-formed UTF-8 code unit subsequence, then the\nrequirement makes little practical difference. However, the requirement does introduce a\nsignificant constraint if the UTF-8 converter continues past the point of a detected error,\nperhaps by substituting one or more U+FFFD replacement characters for the uninterpretable,\nill-formed UTF-8 code unit subsequence. For example, with the input UTF-8 code\nunit sequence <C2 41 42>, such a UTF-8 conversion process must not return <U+FFFD>\nor <U+FFFD, U+0042>, because either of those outputs would be the result of misinterpreting a well-formed subsequence as being part of the ill-formed subsequence. The\nexpected return value for such a process would instead be <U+FFFD, U+0041, U+0042>.\nFor a UTF-8 conversion process to consume valid successor bytes is not only non-conformant,\nbut also leaves the converter open to security exploits. See Unicode Technical Report\n#36, “Unicode Security Considerations.”\n=== End of quote ===\nIt then goes on to discuss at length, with examples, the \"how many FFFD to emit\" issue.\nUsing their example in the 2nd last quoted paragraph:\n>>> bad2 = \"\\xc2\\x41\\x42\"\n>>> bad2.decode('utf8', 'replace')\nu'\\ufffdB'\n# FAIL\n\nNote that this is a problem with both the 'replace' and 'ignore' options of str.decode('utf_8') -- it's all about omitting data, not about how many U+FFFD are emitted; get the data-emitting part right and the U+FFFD issue falls out naturally, as explained in the part that I didn't quote.\nUpdate 3 Current versions of Python (including 2.7) have unicodedata.unidata_version as '5.1.0' which may or may not indicate that the Unicode-related code is intended to conform to Unicode 5.1.0. In any case, the wordy prohibition of what Python is doing didn't appear in the Unicode standard until 5.2.0. I'll raise an issue on the Python tracker without mentioning the word 'oht'.encode('rot13').\nReported here\n",
"In 'PREFIX\\xe3\\xabSUFFIX', the \\xe3 indicates that it and the next two bites form one unicode code point. (\\xEy does for all y.) However, \\xe3\\xabS obviously does not refer to a valid code point. Since Python knows it's supposed to take three bytes, it sucks up all three anyhow since it doesn't know your S is an S and not just some byte representing 0x53 for some other reason.\n",
"\nAlso, is there any unicode's official recommended way for handling decoding replacements?\n\nNo. Unicode considers them an error condition and doesn't consider any fallback options. So none of the behaviours above are ‘right’.\n"
] |
[
9,
9,
4,
0
] |
[] |
[] |
[
"python",
"screen_scraping",
"security",
"unicode"
] |
stackoverflow_0002547262_python_screen_scraping_security_unicode.txt
|
Q:
How to connect to local MQseries queue using Python?
I am new to mqseries and I started with IBM WebSphere MQ curses. There are examples with MQ_APPLE and MQ_ORANGE queue managers. I have no problem with sending messages to local or remote queue with MQ Explorer, but I wanted to send such message from code: Python or Java. I tried Python pymqi library with code like this:
import pymqi
qmgr = pymqi.QueueManager(None)
qmgr.connect('QM_APPLE')
putq = pymqi.Queue(qmgr, 'Q1')
putq.put('Hello from Python!')
but I receive error:
Traceback (most recent call last):
File "mq_put.py", line 4, in <module>
qmgr.connect('QM_APPLE')
File "c:\Python26\lib\site-packages\pymqi.py", line 758, in connect
raise MQMIError(rv[1], rv[2])
pymqi.MQMIError: MQI Error. Comp: 2, Reason 2540: FAILED: MQRC_UNKNOWN_CHANNEL_NAME
There is QM_APPLE queue manager with Q1 local queue.
What is wrong with my code?
A:
Based on the error it appears that you are attempting to connect to a remote queue manager, but you are using the local queue manager bindings method to connect. I say this because the error is stating that the mqi client doesn't know which channel to connect to. Can you please clarify if you are using a local queue manager or a remote queue manager? I have pasted the code below to connect to a remote queue manager using a channel.
import pymqi
queue_manager = "QUEUE_MANAGER_NAME"
channel = "SVRCONN.1"
host = "host.domain.com"
port = "1434"
conn_info = "%s(%s)" % (host, port)
qmgr = pymqi.QueueManager(None)
qmgr.connectTCPClient(queue_manager, pymqi.cd(), channel, conn_info)
A:
Your post mentions you'd like this to run in Python or Java. Python I can't help with but the previous responder did, so cool. As far as Java, maybe I can point you in the right direction. IBM supports both Java and JMS and provides a number of sample programs of each. By default, these are installed at:
C:\Program Files\IBM\WebSphere MQ\tools\wmqjava
C:\Program Files\IBM\WebSphere MQ\tools\jms
I also offer up my own sample code here:
http://www.ibm.com/developerworks/websphere/techjournal/0610_woolf/0610_woolf.html
The documentation for the IBM's implementation of the Java and JMS WMQ API is here:
http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/topic/com.ibm.mq.csqzaw.doc/uj10120_.htm
The docs I found on the Python module appear to indicate that it must be linked to the Client or Server WMQ libraries and your error seems to indicate that you have the client bindings linked. If that's the case, you must provide the connection info as the previous posted pointed out. The Java and JMS code support either connection type so there's no linking to be done but you still must supply the proper connection details. In particular, please read the chapter on Connection Differences:
http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/topic/com.ibm.mq.csqzaw.doc/ja11010_.htm
-- T.Rob
|
How to connect to local MQseries queue using Python?
|
I am new to mqseries and I started with IBM WebSphere MQ curses. There are examples with MQ_APPLE and MQ_ORANGE queue managers. I have no problem with sending messages to local or remote queue with MQ Explorer, but I wanted to send such message from code: Python or Java. I tried Python pymqi library with code like this:
import pymqi
qmgr = pymqi.QueueManager(None)
qmgr.connect('QM_APPLE')
putq = pymqi.Queue(qmgr, 'Q1')
putq.put('Hello from Python!')
but I receive error:
Traceback (most recent call last):
File "mq_put.py", line 4, in <module>
qmgr.connect('QM_APPLE')
File "c:\Python26\lib\site-packages\pymqi.py", line 758, in connect
raise MQMIError(rv[1], rv[2])
pymqi.MQMIError: MQI Error. Comp: 2, Reason 2540: FAILED: MQRC_UNKNOWN_CHANNEL_NAME
There is QM_APPLE queue manager with Q1 local queue.
What is wrong with my code?
|
[
"Based on the error it appears that you are attempting to connect to a remote queue manager, but you are using the local queue manager bindings method to connect. I say this because the error is stating that the mqi client doesn't know which channel to connect to. Can you please clarify if you are using a local queue manager or a remote queue manager? I have pasted the code below to connect to a remote queue manager using a channel.\nimport pymqi\n\nqueue_manager = \"QUEUE_MANAGER_NAME\"\nchannel = \"SVRCONN.1\"\nhost = \"host.domain.com\"\nport = \"1434\"\nconn_info = \"%s(%s)\" % (host, port)\n\nqmgr = pymqi.QueueManager(None)\nqmgr.connectTCPClient(queue_manager, pymqi.cd(), channel, conn_info)\n\n",
"Your post mentions you'd like this to run in Python or Java. Python I can't help with but the previous responder did, so cool. As far as Java, maybe I can point you in the right direction. IBM supports both Java and JMS and provides a number of sample programs of each. By default, these are installed at: \nC:\\Program Files\\IBM\\WebSphere MQ\\tools\\wmqjava\nC:\\Program Files\\IBM\\WebSphere MQ\\tools\\jms\nI also offer up my own sample code here:\nhttp://www.ibm.com/developerworks/websphere/techjournal/0610_woolf/0610_woolf.html\nThe documentation for the IBM's implementation of the Java and JMS WMQ API is here:\nhttp://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/topic/com.ibm.mq.csqzaw.doc/uj10120_.htm\nThe docs I found on the Python module appear to indicate that it must be linked to the Client or Server WMQ libraries and your error seems to indicate that you have the client bindings linked. If that's the case, you must provide the connection info as the previous posted pointed out. The Java and JMS code support either connection type so there's no linking to be done but you still must supply the proper connection details. In particular, please read the chapter on Connection Differences:\nhttp://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/topic/com.ibm.mq.csqzaw.doc/ja11010_.htm\n-- T.Rob\n"
] |
[
3,
2
] |
[] |
[] |
[
"ibm_mq",
"pymqi",
"python"
] |
stackoverflow_0002536733_ibm_mq_pymqi_python.txt
|
Q:
Design pattern for parsing data that will be grouped to two different ways and flipped
I'm looking for an easily maintainable and extendable design model for a script to parse an excel workbook into two separate workbooks after pulling data from other locations like the command line, and a database. The high level details are as follows.
I need to parse an excel workbook containing a sheet that lists unique question names, the only reliable information that can be parsed from the question name is the book code that identifies the title and edition of the textbook the question is associated with, the rest of the question name is not standardized well enough to be reliably parsed by computer. The general form of the question name is best described by the following regular expression.
'^(\w+)\s(\w{1,2})\.(\w{1,2})\.(\w{1,3})\.(\w{1,3}\.)*$'
The first sub-pattern is the book code, the second sub-pattern is 90% of the time the chapter, and the rest of the sub-patterns could be section, problem type, problem number, or question type information. There is no simple logic, at least not one I can find.
There will be a minimum of three other columns in this spreadsheet; one column will be the chapter the question is associated with, the second will be the section within the chapter the question is associated with, and the third will be some kind of asset indicated by a uniform resource locator.
1 | 1 | qname1 | url | description | url | description ...
1 | 1 | qname2 | url | description
1 | 1 | qname3 | url | description | url | description | url |
The asset can be indicated by a full or partial uniform resource locator, the partial url will need to be completed before it can be fed into the application. There theoretically could be no limit to the number of asset columns, the assets will be grouped in columns by type. Some times additional data will have to be retrieved from a database or combined with the book code before the asset url is complete and can be understood by the application that will be using the asset.
The type is an abstraction, there are eight types right now, each with their own logic in how the uniform resource locator is handled and or completed, and I have to add a new type and its logic every three or four months.
For each asset url there is the possibility of a description column, a character string for display in the application, but not always. (I've already worked out validating the description text, and squashing MSs obscure code page down to something 7-bit ascii can handle.)
Now that all the details are filled-in I can get to the actual problem of parsing the file. I need to split the information in this excel workbook into two separate workbooks. The first workbook will group all the questions by section in rows. With the first cell being the section doublet and the rest of the cells in the row are the question names.
1.1 | qname1 | qname2 | qname3 | qname4 |
1.2 | qname1 | qname2 | qname3 |
1.3 | qname1 | qname2 | qname3 | qname4 | qname5
There is no set number of questions for each section as you can see from the above example.
The second workbook is more complicated, there is one row per asset, and question names that have more than one asset will be duplicated. There will be four or five columns on this sheet. The first is the question name for the asset, the second is a media type used to select the correct icon for the asset in the application, the third is string representing the asset type, the four is the full and complete uniform resource locator for the asset, and the fifth columns is the optional text description for the asset.
q1 | mtype1 | atype1 | url | description
q1 | mtype2 | atype2 | url | description
q1 | mtype2 | atype3 | url | description
q2 | mtype1 | atype1 | url | description
q2 | mtype2 | atype3 | url | description
For the original six types I did have a script that parsed the source excel workbook into the other two excel workbooks, and I was able to add two more types until I ran aground on the implementation of the ninth type and tenth types.
What broke my script was the fact that the ninth type is actually a sub-type of one of the original six, but with entirely different logic, and my mostly procedural script could not accommodate without duplicating a lot of code. I also had a lot of bugs in the script and will be writing the test first on this time around.
I'm stuck with the format for the resulting two workbooks, this script is glue code, development went ahead with the project without bothering to get a complete spec from the sponsor. I work for the same company as the developers but in the editorial department, editorial is co-sponsor of the project, and am expected to fix pesky details like this (I'm foaming at the mouth as I type this).
I've tried factories, I've tried different object models, but each resulting workbook is so different when I find a design that works for generating one workbook the code is not really usable for generating the other. What I would really like are ideas about a maintainable and extensible design for parsing the source workbook into both workbooks with maximum code reuse, and or sympathy.
A:
Not sure if I can help, but at the least, sympathy for you I do have :-)
Have you tried using Strategies? If haven't check out the link, there is even a simple Python example. If your types differ only in the way they handle the URLs, you could encapsulate the different logics into strategy subclasses. In the worst case, there may be duplicated logic between some subclasses, but at least the rest of your app can be happily oblivious about it, and adding new types should be simple. But you might even be able to reuse part of the duplicated logic by e.g. parameterizing strategies differently... I am entirely speculating here, without knowing the concrete details of your problem.
Hope this helps...
|
Design pattern for parsing data that will be grouped to two different ways and flipped
|
I'm looking for an easily maintainable and extendable design model for a script to parse an excel workbook into two separate workbooks after pulling data from other locations like the command line, and a database. The high level details are as follows.
I need to parse an excel workbook containing a sheet that lists unique question names, the only reliable information that can be parsed from the question name is the book code that identifies the title and edition of the textbook the question is associated with, the rest of the question name is not standardized well enough to be reliably parsed by computer. The general form of the question name is best described by the following regular expression.
'^(\w+)\s(\w{1,2})\.(\w{1,2})\.(\w{1,3})\.(\w{1,3}\.)*$'
The first sub-pattern is the book code, the second sub-pattern is 90% of the time the chapter, and the rest of the sub-patterns could be section, problem type, problem number, or question type information. There is no simple logic, at least not one I can find.
There will be a minimum of three other columns in this spreadsheet; one column will be the chapter the question is associated with, the second will be the section within the chapter the question is associated with, and the third will be some kind of asset indicated by a uniform resource locator.
1 | 1 | qname1 | url | description | url | description ...
1 | 1 | qname2 | url | description
1 | 1 | qname3 | url | description | url | description | url |
The asset can be indicated by a full or partial uniform resource locator, the partial url will need to be completed before it can be fed into the application. There theoretically could be no limit to the number of asset columns, the assets will be grouped in columns by type. Some times additional data will have to be retrieved from a database or combined with the book code before the asset url is complete and can be understood by the application that will be using the asset.
The type is an abstraction, there are eight types right now, each with their own logic in how the uniform resource locator is handled and or completed, and I have to add a new type and its logic every three or four months.
For each asset url there is the possibility of a description column, a character string for display in the application, but not always. (I've already worked out validating the description text, and squashing MSs obscure code page down to something 7-bit ascii can handle.)
Now that all the details are filled-in I can get to the actual problem of parsing the file. I need to split the information in this excel workbook into two separate workbooks. The first workbook will group all the questions by section in rows. With the first cell being the section doublet and the rest of the cells in the row are the question names.
1.1 | qname1 | qname2 | qname3 | qname4 |
1.2 | qname1 | qname2 | qname3 |
1.3 | qname1 | qname2 | qname3 | qname4 | qname5
There is no set number of questions for each section as you can see from the above example.
The second workbook is more complicated, there is one row per asset, and question names that have more than one asset will be duplicated. There will be four or five columns on this sheet. The first is the question name for the asset, the second is a media type used to select the correct icon for the asset in the application, the third is string representing the asset type, the four is the full and complete uniform resource locator for the asset, and the fifth columns is the optional text description for the asset.
q1 | mtype1 | atype1 | url | description
q1 | mtype2 | atype2 | url | description
q1 | mtype2 | atype3 | url | description
q2 | mtype1 | atype1 | url | description
q2 | mtype2 | atype3 | url | description
For the original six types I did have a script that parsed the source excel workbook into the other two excel workbooks, and I was able to add two more types until I ran aground on the implementation of the ninth type and tenth types.
What broke my script was the fact that the ninth type is actually a sub-type of one of the original six, but with entirely different logic, and my mostly procedural script could not accommodate without duplicating a lot of code. I also had a lot of bugs in the script and will be writing the test first on this time around.
I'm stuck with the format for the resulting two workbooks, this script is glue code, development went ahead with the project without bothering to get a complete spec from the sponsor. I work for the same company as the developers but in the editorial department, editorial is co-sponsor of the project, and am expected to fix pesky details like this (I'm foaming at the mouth as I type this).
I've tried factories, I've tried different object models, but each resulting workbook is so different when I find a design that works for generating one workbook the code is not really usable for generating the other. What I would really like are ideas about a maintainable and extensible design for parsing the source workbook into both workbooks with maximum code reuse, and or sympathy.
|
[
"Not sure if I can help, but at the least, sympathy for you I do have :-)\nHave you tried using Strategies? If haven't check out the link, there is even a simple Python example. If your types differ only in the way they handle the URLs, you could encapsulate the different logics into strategy subclasses. In the worst case, there may be duplicated logic between some subclasses, but at least the rest of your app can be happily oblivious about it, and adding new types should be simple. But you might even be able to reuse part of the duplicated logic by e.g. parameterizing strategies differently... I am entirely speculating here, without knowing the concrete details of your problem.\nHope this helps...\n"
] |
[
1
] |
[] |
[] |
[
"design_patterns",
"oop",
"python"
] |
stackoverflow_0002548790_design_patterns_oop_python.txt
|
Q:
Converting a string into a list in Python
I have a text document that contains a list of numbers and I want to convert it to a list. Right now I can only get the entire list in the 0th entry of the list, but I want each number to be an element of a list. Does anyone know of an easy way to do this in Python?
1000
2000
3000
4000
to
['1000','2000','3000','4000']
A:
To convert a Python string into a list use the str.split method:
>>> '1000 2000 3000 4000'.split()
['1000', '2000', '3000', '4000']
split has some options: look them up for advanced uses.
You can also read the file into a list with the readlines() method of a file object - it returns a list of lines. For example, to get a list of integers from that file, you can do:
lst = map(int, open('filename.txt').readlines())
P.S: See some other methods for doing the same in the comments. Some of those methods are nicer (more Pythonic) than mine
A:
>>> open("myfile.txt").readlines()
>>> lines = open("myfile.txt").readlines()
>>> lines
['1000\n', '2000\n', '3000\n', '4000\n']
>>> clean_lines = [x.strip() for x in lines]
>>> clean_lines
['1000', '2000', '3000', '4000']
Or, if you have a string already, use str.split:
>>> myfile
'1000\n2000\n3000\n4000\n'
>>> myfile.splitlines()
['1000', '2000', '3000', '4000', '']
You can remove the empty element with a list comprehension (or just a regular for loop)
>>> [x for x in myfile.splitlines() if x != ""]
['1000', '2000', '3000', '4000']
A:
$ cat > t.txt
1
2
3
4
^D
$ python
Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [l.strip() for l in open('t.txt')]
>>> l
['1', '2', '3', '4']
>>>
A:
with open('file.txt', 'rb') as f:
data = f.read()
lines = [s.strip() for s in data.split('\n') if s]
A:
You might need to strip newlines.
# list of strings
[number for number in open("file.txt")]
# list of integers
[int(number) for number in open("file.txt")]
|
Converting a string into a list in Python
|
I have a text document that contains a list of numbers and I want to convert it to a list. Right now I can only get the entire list in the 0th entry of the list, but I want each number to be an element of a list. Does anyone know of an easy way to do this in Python?
1000
2000
3000
4000
to
['1000','2000','3000','4000']
|
[
"To convert a Python string into a list use the str.split method:\n>>> '1000 2000 3000 4000'.split()\n['1000', '2000', '3000', '4000']\n\nsplit has some options: look them up for advanced uses.\nYou can also read the file into a list with the readlines() method of a file object - it returns a list of lines. For example, to get a list of integers from that file, you can do:\nlst = map(int, open('filename.txt').readlines())\n\n\nP.S: See some other methods for doing the same in the comments. Some of those methods are nicer (more Pythonic) than mine\n",
">>> open(\"myfile.txt\").readlines()\n>>> lines = open(\"myfile.txt\").readlines()\n>>> lines\n['1000\\n', '2000\\n', '3000\\n', '4000\\n']\n>>> clean_lines = [x.strip() for x in lines]\n>>> clean_lines\n['1000', '2000', '3000', '4000']\n\nOr, if you have a string already, use str.split:\n>>> myfile\n'1000\\n2000\\n3000\\n4000\\n'\n>>> myfile.splitlines()\n['1000', '2000', '3000', '4000', '']\n\nYou can remove the empty element with a list comprehension (or just a regular for loop)\n>>> [x for x in myfile.splitlines() if x != \"\"]\n['1000', '2000', '3000', '4000']\n\n",
" $ cat > t.txt\n 1\n 2\n 3\n 4\n ^D\n $ python\n Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) \n [GCC 4.2.1 (Apple Inc. build 5646)] on darwin\n Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n >>> l = [l.strip() for l in open('t.txt')]\n >>> l\n ['1', '2', '3', '4']\n >>> \n\n",
" with open('file.txt', 'rb') as f:\n data = f.read()\n lines = [s.strip() for s in data.split('\\n') if s]\n\n",
"You might need to strip newlines.\n# list of strings\n[number for number in open(\"file.txt\")]\n\n# list of integers\n[int(number) for number in open(\"file.txt\")]\n\n"
] |
[
24,
1,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002545397_python.txt
|
Q:
How to find the filename of a script being run when it is executed from a symlink on linux
If I have a python script that is executed via a symlink, is there a way that I can find the path to the script rather than the symlink? I've tried using the methods suggested in this question, but they always return the path to the symlink, not the script.
For example, when this is saved as my "/usr/home/philboltt/scripts/test.py" :
#!/usr/bin/python
import sys
print sys.argv[0]
print __file__
and I then create this symlink
ln -s /usr/home/philboltt/scripts/test.py /usr/home/philboltt/test
and execute the script using
/usr/home/philboltt/test
I get the following output:
/usr/home/philboltt/test
/usr/home/philboltt/test
Thanks!
Phil
A:
You want the os.path.realpath() function.
A:
os.readlink() will resolve a symlink, and os.path.islink() will tell you if it's a symlink in the first place.
A:
I believe you will need to check if the file is a symlink, and if so, get where it is linked to. For example...
try:
print os.readlink(__file__)
except:
print "File is not a symlink"
|
How to find the filename of a script being run when it is executed from a symlink on linux
|
If I have a python script that is executed via a symlink, is there a way that I can find the path to the script rather than the symlink? I've tried using the methods suggested in this question, but they always return the path to the symlink, not the script.
For example, when this is saved as my "/usr/home/philboltt/scripts/test.py" :
#!/usr/bin/python
import sys
print sys.argv[0]
print __file__
and I then create this symlink
ln -s /usr/home/philboltt/scripts/test.py /usr/home/philboltt/test
and execute the script using
/usr/home/philboltt/test
I get the following output:
/usr/home/philboltt/test
/usr/home/philboltt/test
Thanks!
Phil
|
[
"You want the os.path.realpath() function.\n",
"os.readlink() will resolve a symlink, and os.path.islink() will tell you if it's a symlink in the first place.\n",
"I believe you will need to check if the file is a symlink, and if so, get where it is linked to. For example...\ntry:\n print os.readlink(__file__)\nexcept:\n print \"File is not a symlink\"\n\n"
] |
[
8,
3,
0
] |
[] |
[] |
[
"filenames",
"linux",
"python",
"symlink"
] |
stackoverflow_0002548936_filenames_linux_python_symlink.txt
|
Q:
: in node causing Keyerror in xmlparsing using ElementTree
Hi I'm using ElementTree to parse out an xml feed from Kuler. I'm only beginning in python but am stuck here.
The parsing works fine until I attempt to retrieve any nodes containing ':'
e.g kuler:swatchHexColor
Below is a cut down version of the full feed but same structure:
<rss xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:kuler="http://kuler.adobe.com/kuler/API/rss/" xmlns:rss="http://blogs.law.harvard.edu/tech/rss" version="2.0">
<channel>
<title>kuler popular themes</title>
<item>
<title>Theme Title: Fresh Money</title>
<description>
<img src="http://kuler-api.adobe.com/kuler/themeImages/theme_808366.png" /><br />
Artist: thesylph005<br />
ThemeID: 808366<br />
Posted: 03/02/2010<br />
Hex:
2F400D, 8CBF26, A8CA65, E8E5B0, 419184
</description>
<kuler:themeItem>
<kuler:themeID>808366</kuler:themeID>
<kuler:themeTitle>Fresh Money</kuler:themeTitle>
<kuler:themeImage>http://kuler-api.adobe.com/kuler/themeImages/theme_808366.png</kuler:themeImage>
<kuler:themeAuthor>
<kuler:authorID>370750</kuler:authorID>
<kuler:authorLabel>thesylph005</kuler:authorLabel>
</kuler:themeAuthor>
<kuler:themeTags/>
<kuler:themeRating>4</kuler:themeRating>
<kuler:themeDownloadCount>708</kuler:themeDownloadCount>
<kuler:themeCreatedAt>20100302</kuler:themeCreatedAt>
<kuler:themeEditedAt>20100302</kuler:themeEditedAt>
<kuler:themeSwatches>
<kuler:swatch>
<kuler:swatchHexColor>2F400D</kuler:swatchHexColor>
<kuler:swatchColorMode>rgb</kuler:swatchColorMode>
<kuler:swatchChannel1>0.183333</kuler:swatchChannel1>
<kuler:swatchChannel2>0.25</kuler:swatchChannel2>
<kuler:swatchChannel3>0.05</kuler:swatchChannel3>
<kuler:swatchChannel4>0.0</kuler:swatchChannel4>
<kuler:swatchIndex>0</kuler:swatchIndex>
</kuler:swatch>
<kuler:swatch>
<kuler:swatchHexColor>8CBF26</kuler:swatchHexColor>
<kuler:swatchColorMode>rgb</kuler:swatchColorMode>
<kuler:swatchChannel1>0.55</kuler:swatchChannel1>
<kuler:swatchChannel2>0.75</kuler:swatchChannel2>
<kuler:swatchChannel3>0.15</kuler:swatchChannel3>
<kuler:swatchChannel4>0.0</kuler:swatchChannel4>
<kuler:swatchIndex>1</kuler:swatchIndex>
</kuler:swatch>
<kuler:swatch>
<kuler:swatchHexColor>A8CA65</kuler:swatchHexColor>
<kuler:swatchColorMode>rgb</kuler:swatchColorMode>
<kuler:swatchChannel1>0.659722</kuler:swatchChannel1>
<kuler:swatchChannel2>0.791667</kuler:swatchChannel2>
<kuler:swatchChannel3>0.395833</kuler:swatchChannel3>
<kuler:swatchChannel4>0.0</kuler:swatchChannel4>
<kuler:swatchIndex>2</kuler:swatchIndex>
</kuler:swatch>
<kuler:swatch>
<kuler:swatchHexColor>E8E5B0</kuler:swatchHexColor>
<kuler:swatchColorMode>rgb</kuler:swatchColorMode>
<kuler:swatchChannel1>0.91</kuler:swatchChannel1>
<kuler:swatchChannel2>0.898047</kuler:swatchChannel2>
<kuler:swatchChannel3>0.688705</kuler:swatchChannel3>
<kuler:swatchChannel4>0.0</kuler:swatchChannel4>
<kuler:swatchIndex>3</kuler:swatchIndex>
</kuler:swatch>
<kuler:swatch>
<kuler:swatchHexColor>419184</kuler:swatchHexColor>
<kuler:swatchColorMode>rgb</kuler:swatchColorMode>
<kuler:swatchChannel1>0.254901</kuler:swatchChannel1>
<kuler:swatchChannel2>0.57</kuler:swatchChannel2>
<kuler:swatchChannel3>0.519034</kuler:swatchChannel3>
<kuler:swatchChannel4>0.0</kuler:swatchChannel4>
<kuler:swatchIndex>4</kuler:swatchIndex>
</kuler:swatch>
</kuler:themeSwatches>
Tue, 30 Mar 2010 11:27:12 PST
So if I do a findall on say each item's description, I get that back fine.
But the minute I try to retrieve anything with a : in the nodename I get
Exception Type: KeyError
Exception Value: ':'
So this works
from elementtree.ElementTree import Element, SubElement, dump, parse
def xml():
kulerurl = 'http://kuler-api.adobe.com/rss/get.cfm?listType=popular&startIndex=0&itemsPerPage=5&timeSpan=30&key=mykey'
rss = parse(urllib.urlopen(kulerurl)).getroot()
for element in rss.findall('channel/item'):
print(element.findtext('description'))
dump (rss)
but this doesn't
def xml():
kulerurl = 'http://kuler-api.adobe.com/rss/get.cfm?listType=popular&startIndex=0&itemsPerPage=5&timeSpan=30&key=mykey'
rss = parse(urllib.urlopen(kulerurl)).getroot()
for element in rss.findall('channel/item/kuler:themeItem'):
print(element.findtext('kuler:themeID'))
dump (rss)
I'm sure it's something simple if anyone could point me to what I'm doing wrong here I'd be most grateful
thanks
Kieran
A:
Based on this article (and comments on this article) I think you have to substitute the namespace name with the actual URI (and remove the colon and put it in {}):
namespace = 'http://kuler.adobe.com/kuler/API/rss/'
def xml():
kulerurl = 'http://kuler-api.adobe.com/rss/get.cfm?listType=popular&startIndex=0&itemsPerPage=5&timeSpan=30&key=mykey'
rss = parse(urllib.urlopen(kulerurl)).getroot()
for element in rss.findall('channel/item/{%s}themeItem' % namespace):
print(element.findtext('{%s}themeID' % namespace))
dump (rss)
[XML namespaces]
The element type represents a qualified name pair, also called universal name, as a string of the form “{uri}local“. This syntax can be used both for tag names and for attribute keys.
You can also read in this introduction how ElementTree handles namespaces.
|
: in node causing Keyerror in xmlparsing using ElementTree
|
Hi I'm using ElementTree to parse out an xml feed from Kuler. I'm only beginning in python but am stuck here.
The parsing works fine until I attempt to retrieve any nodes containing ':'
e.g kuler:swatchHexColor
Below is a cut down version of the full feed but same structure:
<rss xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:kuler="http://kuler.adobe.com/kuler/API/rss/" xmlns:rss="http://blogs.law.harvard.edu/tech/rss" version="2.0">
<channel>
<title>kuler popular themes</title>
<item>
<title>Theme Title: Fresh Money</title>
<description>
<img src="http://kuler-api.adobe.com/kuler/themeImages/theme_808366.png" /><br />
Artist: thesylph005<br />
ThemeID: 808366<br />
Posted: 03/02/2010<br />
Hex:
2F400D, 8CBF26, A8CA65, E8E5B0, 419184
</description>
<kuler:themeItem>
<kuler:themeID>808366</kuler:themeID>
<kuler:themeTitle>Fresh Money</kuler:themeTitle>
<kuler:themeImage>http://kuler-api.adobe.com/kuler/themeImages/theme_808366.png</kuler:themeImage>
<kuler:themeAuthor>
<kuler:authorID>370750</kuler:authorID>
<kuler:authorLabel>thesylph005</kuler:authorLabel>
</kuler:themeAuthor>
<kuler:themeTags/>
<kuler:themeRating>4</kuler:themeRating>
<kuler:themeDownloadCount>708</kuler:themeDownloadCount>
<kuler:themeCreatedAt>20100302</kuler:themeCreatedAt>
<kuler:themeEditedAt>20100302</kuler:themeEditedAt>
<kuler:themeSwatches>
<kuler:swatch>
<kuler:swatchHexColor>2F400D</kuler:swatchHexColor>
<kuler:swatchColorMode>rgb</kuler:swatchColorMode>
<kuler:swatchChannel1>0.183333</kuler:swatchChannel1>
<kuler:swatchChannel2>0.25</kuler:swatchChannel2>
<kuler:swatchChannel3>0.05</kuler:swatchChannel3>
<kuler:swatchChannel4>0.0</kuler:swatchChannel4>
<kuler:swatchIndex>0</kuler:swatchIndex>
</kuler:swatch>
<kuler:swatch>
<kuler:swatchHexColor>8CBF26</kuler:swatchHexColor>
<kuler:swatchColorMode>rgb</kuler:swatchColorMode>
<kuler:swatchChannel1>0.55</kuler:swatchChannel1>
<kuler:swatchChannel2>0.75</kuler:swatchChannel2>
<kuler:swatchChannel3>0.15</kuler:swatchChannel3>
<kuler:swatchChannel4>0.0</kuler:swatchChannel4>
<kuler:swatchIndex>1</kuler:swatchIndex>
</kuler:swatch>
<kuler:swatch>
<kuler:swatchHexColor>A8CA65</kuler:swatchHexColor>
<kuler:swatchColorMode>rgb</kuler:swatchColorMode>
<kuler:swatchChannel1>0.659722</kuler:swatchChannel1>
<kuler:swatchChannel2>0.791667</kuler:swatchChannel2>
<kuler:swatchChannel3>0.395833</kuler:swatchChannel3>
<kuler:swatchChannel4>0.0</kuler:swatchChannel4>
<kuler:swatchIndex>2</kuler:swatchIndex>
</kuler:swatch>
<kuler:swatch>
<kuler:swatchHexColor>E8E5B0</kuler:swatchHexColor>
<kuler:swatchColorMode>rgb</kuler:swatchColorMode>
<kuler:swatchChannel1>0.91</kuler:swatchChannel1>
<kuler:swatchChannel2>0.898047</kuler:swatchChannel2>
<kuler:swatchChannel3>0.688705</kuler:swatchChannel3>
<kuler:swatchChannel4>0.0</kuler:swatchChannel4>
<kuler:swatchIndex>3</kuler:swatchIndex>
</kuler:swatch>
<kuler:swatch>
<kuler:swatchHexColor>419184</kuler:swatchHexColor>
<kuler:swatchColorMode>rgb</kuler:swatchColorMode>
<kuler:swatchChannel1>0.254901</kuler:swatchChannel1>
<kuler:swatchChannel2>0.57</kuler:swatchChannel2>
<kuler:swatchChannel3>0.519034</kuler:swatchChannel3>
<kuler:swatchChannel4>0.0</kuler:swatchChannel4>
<kuler:swatchIndex>4</kuler:swatchIndex>
</kuler:swatch>
</kuler:themeSwatches>
Tue, 30 Mar 2010 11:27:12 PST
So if I do a findall on say each item's description, I get that back fine.
But the minute I try to retrieve anything with a : in the nodename I get
Exception Type: KeyError
Exception Value: ':'
So this works
from elementtree.ElementTree import Element, SubElement, dump, parse
def xml():
kulerurl = 'http://kuler-api.adobe.com/rss/get.cfm?listType=popular&startIndex=0&itemsPerPage=5&timeSpan=30&key=mykey'
rss = parse(urllib.urlopen(kulerurl)).getroot()
for element in rss.findall('channel/item'):
print(element.findtext('description'))
dump (rss)
but this doesn't
def xml():
kulerurl = 'http://kuler-api.adobe.com/rss/get.cfm?listType=popular&startIndex=0&itemsPerPage=5&timeSpan=30&key=mykey'
rss = parse(urllib.urlopen(kulerurl)).getroot()
for element in rss.findall('channel/item/kuler:themeItem'):
print(element.findtext('kuler:themeID'))
dump (rss)
I'm sure it's something simple if anyone could point me to what I'm doing wrong here I'd be most grateful
thanks
Kieran
|
[
"Based on this article (and comments on this article) I think you have to substitute the namespace name with the actual URI (and remove the colon and put it in {}):\nnamespace = 'http://kuler.adobe.com/kuler/API/rss/'\n\ndef xml():\n kulerurl = 'http://kuler-api.adobe.com/rss/get.cfm?listType=popular&startIndex=0&itemsPerPage=5&timeSpan=30&key=mykey'\n rss = parse(urllib.urlopen(kulerurl)).getroot()\n for element in rss.findall('channel/item/{%s}themeItem' % namespace):\n print(element.findtext('{%s}themeID' % namespace))\n dump (rss)\n\n\n[XML namespaces]\n The element type represents a qualified name pair, also called universal name, as a string of the form “{uri}local“. This syntax can be used both for tag names and for attribute keys.\n\nYou can also read in this introduction how ElementTree handles namespaces.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"elementtree",
"parsing",
"python",
"xml"
] |
stackoverflow_0002549211_django_elementtree_parsing_python_xml.txt
|
Q:
Exit python program when argument is less than 0
I'd like the program to exit if the input number is less than 0, but sys.exit() isn't doing the trick. This is what I have now:
if len( sys.argv ) > 1:
number = sys.argv[1]
if number <= 0:
print "Invalid number! Must be greater than 0"
sys.exit()
A:
Your test is failing because number is a string.
>>> '-1' <= 0
False
You need to convert number to an integer:
number = int(sys.argv[1])
Note that in Python 3.0 your code would have given an error, allowing you to find your mistake more easily:
>>> '-1' <= 0
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
'-1' <= 0
TypeError: unorderable types: str() <= int()
|
Exit python program when argument is less than 0
|
I'd like the program to exit if the input number is less than 0, but sys.exit() isn't doing the trick. This is what I have now:
if len( sys.argv ) > 1:
number = sys.argv[1]
if number <= 0:
print "Invalid number! Must be greater than 0"
sys.exit()
|
[
"Your test is failing because number is a string.\n>>> '-1' <= 0\nFalse\n\nYou need to convert number to an integer:\nnumber = int(sys.argv[1])\n\nNote that in Python 3.0 your code would have given an error, allowing you to find your mistake more easily:\n>>> '-1' <= 0\nTraceback (most recent call last):\n File \"<pyshell#0>\", line 1, in <module>\n '-1' <= 0\nTypeError: unorderable types: str() <= int()\n\n"
] |
[
10
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002549300_python.txt
|
Q:
working python xml
my question is the following, which is the best way of working XML (kml) with python?, especially script serializable.
thanks for your attention and answers
A:
For Python and XML I routinely use xml.etree (see its documentation). The good thing with xml.etree is that it's included in the Python standard library. I've heard good things about lxml as well, which exposes an etree compatible api.
A:
lxml is very fast. With large data its best choice.
Edit: But "Note that lxml does not provide any thread-safety by itself (mainly for performance reasons), so you have to take care when you use parts of the API concurrently."
A:
For very small and simple things, xml.dom.minidom is the easiest route. If you're looking for something which can handle large files with very little memory usage then you'll want to use an xml.sax parser.
|
working python xml
|
my question is the following, which is the best way of working XML (kml) with python?, especially script serializable.
thanks for your attention and answers
|
[
"For Python and XML I routinely use xml.etree (see its documentation). The good thing with xml.etree is that it's included in the Python standard library. I've heard good things about lxml as well, which exposes an etree compatible api.\n",
"lxml is very fast. With large data its best choice.\nEdit: But \"Note that lxml does not provide any thread-safety by itself (mainly for performance reasons), so you have to take care when you use parts of the API concurrently.\"\n",
"For very small and simple things, xml.dom.minidom is the easiest route. If you're looking for something which can handle large files with very little memory usage then you'll want to use an xml.sax parser.\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"kml",
"python",
"xml",
"xml_serialization"
] |
stackoverflow_0002548659_kml_python_xml_xml_serialization.txt
|
Q:
What is the difference between AF_INET and PF_INET constants?
Looking at examples about socket programming, we can see that some people use AF_INET while others use PF_INET. In addition, sometimes both of them are used at the same example. The question is: Is there any difference between them? Which one should we use?
If you can answer that, another question would be... Why there are these two similar (but equal) constants?
What I've discovered, so far:
The socket manpage
In (Unix) socket programming, we have the socket() function that receives the following parameters:
int socket(int domain, int type, int protocol);
The manpage says:
The domain argument specifies a communication domain; this selects the
protocol family which will be used for communication. These families
are defined in <sys/socket.h>.
And the manpage cites AF_INET as well as some other AF_ constants for the domain parameter. Also, at the NOTES section of the same manpage, we can read:
The manifest constants used under 4.x BSD for protocol families are
PF_UNIX, PF_INET, etc., while AF_UNIX etc. are used for address families.
However, already the BSD man page promises: "The protocol family
generally is the same as the address family", and subsequent standards
use AF_* everywhere.
The C headers
The sys/socket.h does not actually define those constants, but instead includes bits/socket.h. This file defines around 38 AF_ constants and 38 PF_ constants like this:
#define PF_INET 2 /* IP protocol family. */
#define AF_INET PF_INET
Python
The Python socket module is very similar to the C API. However, there are many AF_ constants but only one PF_ constant (PF_PACKET). Thus, in Python we have no choice but use AF_INET.
I think this decision to include only the AF_ constants follows one of the guiding principles: "There should be one-- and preferably only one --obvious way to do it." (The Zen of Python)
Other info
This forum post links to this old message, which contains some historical information.
A:
I think the Wikipedia notes on this sum it up pretty well:
The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF_ instead of PF_. The AF_-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.
Even if someone came up with a reason to have a difference today, they'd have to come up with new identifiers or so much stuff would break...
|
What is the difference between AF_INET and PF_INET constants?
|
Looking at examples about socket programming, we can see that some people use AF_INET while others use PF_INET. In addition, sometimes both of them are used at the same example. The question is: Is there any difference between them? Which one should we use?
If you can answer that, another question would be... Why there are these two similar (but equal) constants?
What I've discovered, so far:
The socket manpage
In (Unix) socket programming, we have the socket() function that receives the following parameters:
int socket(int domain, int type, int protocol);
The manpage says:
The domain argument specifies a communication domain; this selects the
protocol family which will be used for communication. These families
are defined in <sys/socket.h>.
And the manpage cites AF_INET as well as some other AF_ constants for the domain parameter. Also, at the NOTES section of the same manpage, we can read:
The manifest constants used under 4.x BSD for protocol families are
PF_UNIX, PF_INET, etc., while AF_UNIX etc. are used for address families.
However, already the BSD man page promises: "The protocol family
generally is the same as the address family", and subsequent standards
use AF_* everywhere.
The C headers
The sys/socket.h does not actually define those constants, but instead includes bits/socket.h. This file defines around 38 AF_ constants and 38 PF_ constants like this:
#define PF_INET 2 /* IP protocol family. */
#define AF_INET PF_INET
Python
The Python socket module is very similar to the C API. However, there are many AF_ constants but only one PF_ constant (PF_PACKET). Thus, in Python we have no choice but use AF_INET.
I think this decision to include only the AF_ constants follows one of the guiding principles: "There should be one-- and preferably only one --obvious way to do it." (The Zen of Python)
Other info
This forum post links to this old message, which contains some historical information.
|
[
"I think the Wikipedia notes on this sum it up pretty well:\n\nThe original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF_ instead of PF_. The AF_-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.\n\nEven if someone came up with a reason to have a difference today, they'd have to come up with new identifiers or so much stuff would break...\n"
] |
[
27
] |
[] |
[] |
[
"c",
"python",
"sockets",
"unix"
] |
stackoverflow_0002549461_c_python_sockets_unix.txt
|
Q:
Django Timezone Confusion; Postgres and Apache
Setup: Multiple sites on Django on the same set of servers, being served by the same group of Apache processes. Some sites are Eastern TZ; some are Central. Database is PSQL running on a separate server.
When I started, I didn't put much thought into how the various sites would handle timezones; I guess I saw the TIMEZONE setting in Django and just figured it'd 'handle it'. Now I'm seeing the cracks.
First problem: The timezone seems to flip back and forth between Eastern and Central. My understanding of that from searching around on this site are that it's because the os environ var for TZ gets set to the Apache process depending on which Django site it's handling a request for, and if that process then handles a request for a site on another TZ, the timezone is wrong. I believe the solution I found here was that sites of different timezones need to have different process groups serving them. Please correct if wrong.
Second problem: Locally on Linux, I did a ./manage.py runserver from one of my sites with Central time (I'm in Eastern). I created an asset, whose publish date correctly displayed as one hour behind in the admin. Looking at the actual PostgresSQL entry, the publish date's timezone is still listed as -04. Does Postgres just use the timezone of the server/computer itself and ignore any TZ setting in Django? So all entries saved on a Postgres server on Eastern time would show as -04 or -05 depending on Daylight Savings?
If anyone else has dealt with something like this, advice is appreciated. Even if I split out the Apache processes for the Central sites such that their TZ settings don't cross, I still have the Postgres problem to deal with. And then I'm curious; if the PSQL timestamp is Central, and the TZ setting is Eastern, say, do the datetime fields take TZ into account? i.e., if you do datetime.datetime.now() when Django is set to EST, and it returns 2:00 PM, then you have it filter content by its publish date being less than that result, would it account for TZ by only looking for content whose publish time was 1:00PM CST or earlier?
A:
Here are some details on time zone handling in Django and Postgres, but I strongly recommend dealing exclusively with UTC on the backend and only converting to a local time zone in the frontend when presenting a UTC timestamp to a user. In Python, you can get the current time in UTC via datetime.datetime.utcnow(). I even put my servers in the UTC time zone, but that isn't strictly necessary.
Multiple time zones don't work well in Django; see this ticket. The datetime objects in the Python standard library are time zone naive, and you need a library like pytz to fix that, but as far as I know Django still returns naive datetime objects, not the time zone aware ones that you can construct with pytz.
Postgres will check several places to determine the time zone, including the TZ environment variable, but TZ will have to be in the environment of the postgres process:
PostgreSQL 8.5.3. Time Zones
If timezone is not specified in
postgresql.conf nor as a postmaster
command-line switch, the server
attempts to use the value of the TZ
environment variable as the default
time zone. If TZ is not defined or is
not any of the time zone names known
to PostgreSQL, the server attempts to
determine the operating system's
default time zone by checking the
behavior of the C library function
localtime(). The default time zone is
selected as the closest match among
PostgreSQL's known time zones.
|
Django Timezone Confusion; Postgres and Apache
|
Setup: Multiple sites on Django on the same set of servers, being served by the same group of Apache processes. Some sites are Eastern TZ; some are Central. Database is PSQL running on a separate server.
When I started, I didn't put much thought into how the various sites would handle timezones; I guess I saw the TIMEZONE setting in Django and just figured it'd 'handle it'. Now I'm seeing the cracks.
First problem: The timezone seems to flip back and forth between Eastern and Central. My understanding of that from searching around on this site are that it's because the os environ var for TZ gets set to the Apache process depending on which Django site it's handling a request for, and if that process then handles a request for a site on another TZ, the timezone is wrong. I believe the solution I found here was that sites of different timezones need to have different process groups serving them. Please correct if wrong.
Second problem: Locally on Linux, I did a ./manage.py runserver from one of my sites with Central time (I'm in Eastern). I created an asset, whose publish date correctly displayed as one hour behind in the admin. Looking at the actual PostgresSQL entry, the publish date's timezone is still listed as -04. Does Postgres just use the timezone of the server/computer itself and ignore any TZ setting in Django? So all entries saved on a Postgres server on Eastern time would show as -04 or -05 depending on Daylight Savings?
If anyone else has dealt with something like this, advice is appreciated. Even if I split out the Apache processes for the Central sites such that their TZ settings don't cross, I still have the Postgres problem to deal with. And then I'm curious; if the PSQL timestamp is Central, and the TZ setting is Eastern, say, do the datetime fields take TZ into account? i.e., if you do datetime.datetime.now() when Django is set to EST, and it returns 2:00 PM, then you have it filter content by its publish date being less than that result, would it account for TZ by only looking for content whose publish time was 1:00PM CST or earlier?
|
[
"Here are some details on time zone handling in Django and Postgres, but I strongly recommend dealing exclusively with UTC on the backend and only converting to a local time zone in the frontend when presenting a UTC timestamp to a user. In Python, you can get the current time in UTC via datetime.datetime.utcnow(). I even put my servers in the UTC time zone, but that isn't strictly necessary.\nMultiple time zones don't work well in Django; see this ticket. The datetime objects in the Python standard library are time zone naive, and you need a library like pytz to fix that, but as far as I know Django still returns naive datetime objects, not the time zone aware ones that you can construct with pytz. \nPostgres will check several places to determine the time zone, including the TZ environment variable, but TZ will have to be in the environment of the postgres process:\nPostgreSQL 8.5.3. Time Zones\n\nIf timezone is not specified in\n postgresql.conf nor as a postmaster\n command-line switch, the server\n attempts to use the value of the TZ\n environment variable as the default\n time zone. If TZ is not defined or is\n not any of the time zone names known\n to PostgreSQL, the server attempts to\n determine the operating system's\n default time zone by checking the\n behavior of the C library function\n localtime(). The default time zone is\n selected as the closest match among\n PostgreSQL's known time zones.\n\n"
] |
[
2
] |
[] |
[] |
[
"django",
"python",
"timezone"
] |
stackoverflow_0002518240_django_python_timezone.txt
|
Q:
Is there a Python package similar to Perl's Archive::Extract?
I'm looking for a package that will automatically detect the type of and extract an archive (zip, tar.gz, etc). In Perl, this is easy - in Python, I can't find any simple package/class to do it...
A:
In Python you can use:
zipfile
tarfile - Note: Tarfile can also handle bz2ed and gzipped tar files.
bz2
gzip
I'm not aware of any wrapper that can choose the right format automatically. If it exists it doesn't seem to be mentioned in the documentation for any of the above modules.
A:
Riding off of Mark Byers' response, perhaps you can tie all of these together with mimetypes (also from the standard library). You could identify the type of file, and process it accordingly. The world needs a Python version of Archive::Extract, and we want you to write it!
|
Is there a Python package similar to Perl's Archive::Extract?
|
I'm looking for a package that will automatically detect the type of and extract an archive (zip, tar.gz, etc). In Perl, this is easy - in Python, I can't find any simple package/class to do it...
|
[
"In Python you can use:\n\nzipfile\ntarfile - Note: Tarfile can also handle bz2ed and gzipped tar files.\nbz2\ngzip\n\nI'm not aware of any wrapper that can choose the right format automatically. If it exists it doesn't seem to be mentioned in the documentation for any of the above modules.\n",
"Riding off of Mark Byers' response, perhaps you can tie all of these together with mimetypes (also from the standard library). You could identify the type of file, and process it accordingly. The world needs a Python version of Archive::Extract, and we want you to write it!\n"
] |
[
1,
1
] |
[] |
[] |
[
"archive",
"extract",
"gzip",
"python",
"zip"
] |
stackoverflow_0002549134_archive_extract_gzip_python_zip.txt
|
Q:
Django Form for date range
I am trying to come up with a form that lets the user select a date range to generate a web query in Django. I am having errors getting the date to filter with in my view, I am unable to strip the date.
Here is my forms.py:
class ReportFiltersForm(forms.Form):
start_date = forms.DateField(input_formats='%Y,%m,%d',widget=SelectDateWidget())
end_date = forms.DateField(input_formats='%Y,%m,%d',widget=SelectDateWidget())
And my view
if request.method == 'POST':
form = ReportFiltersForm(request.POST)
sdy = request.POST['start_date_year']
sdm = request.POST['start_date_month']
sdd = request.POST['start_date_day']
edy = request.POST['end_date_year']
edm = request.POST['end_date_month']
edd = request.POST['end_date_day']
start_date= datetime.date(sdy, sdm, sdd)
end_date= datetime.date(edy, edm,edd)
Traceback
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/django/core/servers/basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "/usr/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 134, in get_response
return self.handle_uncaught_exception(request, resolver, exc_info)
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 154, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 92, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/projects/acms/cms/views.py", line 470, in eventreports
start_date= datetime.date(sdy, sdm, sdd)
TypeError: an integer is required
A:
There are many mistakes you are making here.
First off, to fix your TypeError, you need to cast your data into int like so:
...
sdy = int(request.POST['start_date_year'])
#Do the same with the other 5 fields
However, this is a really bad way of doing things. For one, you will have to put try/except blocks around each field to make sure the user entered an integer and not a string.
Since you are already using Django Forms, why not let it do all the work for you? Here is how you would do this:
if request.method == 'POST':
form = ReportFiltersForm(request.POST)
if form.is_valid():
start_date = form.cleaned_data['start_date']
end_date = form.cleaned_data['end_date']
#Do whatever you need to do with this data now. Since you had
#defined the fields as DateFields, you will automatically get
#datetime.date objects.
else:
return render_to_response('mytemplate.html', {'form' : form})
....
This is a much better way to do things for a couple of reasons. Using this way, you can let Django take care of validating the user input for you. Additionally, it will also cast this data into datetime.date objects. Finally, it will allow you to give better error messages to your user if they entered invalid data.
|
Django Form for date range
|
I am trying to come up with a form that lets the user select a date range to generate a web query in Django. I am having errors getting the date to filter with in my view, I am unable to strip the date.
Here is my forms.py:
class ReportFiltersForm(forms.Form):
start_date = forms.DateField(input_formats='%Y,%m,%d',widget=SelectDateWidget())
end_date = forms.DateField(input_formats='%Y,%m,%d',widget=SelectDateWidget())
And my view
if request.method == 'POST':
form = ReportFiltersForm(request.POST)
sdy = request.POST['start_date_year']
sdm = request.POST['start_date_month']
sdd = request.POST['start_date_day']
edy = request.POST['end_date_year']
edm = request.POST['end_date_month']
edd = request.POST['end_date_day']
start_date= datetime.date(sdy, sdm, sdd)
end_date= datetime.date(edy, edm,edd)
Traceback
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/django/core/servers/basehttp.py", line 651, in __call__
return self.application(environ, start_response)
File "/usr/lib/python2.6/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 134, in get_response
return self.handle_uncaught_exception(request, resolver, exc_info)
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 154, in handle_uncaught_exception
return debug.technical_500_response(request, *exc_info)
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py", line 92, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/projects/acms/cms/views.py", line 470, in eventreports
start_date= datetime.date(sdy, sdm, sdd)
TypeError: an integer is required
|
[
"There are many mistakes you are making here.\nFirst off, to fix your TypeError, you need to cast your data into int like so:\n...\nsdy = int(request.POST['start_date_year'])\n#Do the same with the other 5 fields\n\nHowever, this is a really bad way of doing things. For one, you will have to put try/except blocks around each field to make sure the user entered an integer and not a string.\nSince you are already using Django Forms, why not let it do all the work for you? Here is how you would do this:\nif request.method == 'POST':\n form = ReportFiltersForm(request.POST)\n if form.is_valid():\n start_date = form.cleaned_data['start_date']\n end_date = form.cleaned_data['end_date']\n #Do whatever you need to do with this data now. Since you had\n #defined the fields as DateFields, you will automatically get\n #datetime.date objects.\n else:\n return render_to_response('mytemplate.html', {'form' : form})\n....\n\nThis is a much better way to do things for a couple of reasons. Using this way, you can let Django take care of validating the user input for you. Additionally, it will also cast this data into datetime.date objects. Finally, it will allow you to give better error messages to your user if they entered invalid data.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_forms",
"python"
] |
stackoverflow_0002549655_django_django_forms_python.txt
|
Q:
python socket.recv/sendall call blocking
This post is incorrectly tagged 'send' since I cannot create new tags.
I have a very basic question about this simple echo server. Here are some code snippets.
client
while True:
data = raw_input("Enter data: ")
mySock.sendall(data)
echoedData = mySock.recv(1024)
if not echoedData: break
print echoedData
server
while True:
print "Waiting for connection"
(clientSock, address) = serverSock.accept()
print "Entering read loop"
while True:
print "Waiting for data"
data = clientSock.recv(1024)
if not data: break
clientSock.send(data)
clientSock.close()
Now this works alright, except when the client sends an empty string (by hitting the return key in response to "enter data: "), in which case I see some deadlock-ish behavior.
Now, what exactly happens when the user presses return on the client side? I can only imagine that the sendall call blocks waiting for some data to be added to the send buffer, causing the recv call to block in turn. What's going on here?
Thanks for reading!
A:
More like, the sendall() call does nothing (since there's no data to send), and thus the recv() call on the client blocks waiting for data, but since nothing was sent to the server, the server never sends any data back since it's also blocked on its initial recv(), and thus both processes are blocked.
|
python socket.recv/sendall call blocking
|
This post is incorrectly tagged 'send' since I cannot create new tags.
I have a very basic question about this simple echo server. Here are some code snippets.
client
while True:
data = raw_input("Enter data: ")
mySock.sendall(data)
echoedData = mySock.recv(1024)
if not echoedData: break
print echoedData
server
while True:
print "Waiting for connection"
(clientSock, address) = serverSock.accept()
print "Entering read loop"
while True:
print "Waiting for data"
data = clientSock.recv(1024)
if not data: break
clientSock.send(data)
clientSock.close()
Now this works alright, except when the client sends an empty string (by hitting the return key in response to "enter data: "), in which case I see some deadlock-ish behavior.
Now, what exactly happens when the user presses return on the client side? I can only imagine that the sendall call blocks waiting for some data to be added to the send buffer, causing the recv call to block in turn. What's going on here?
Thanks for reading!
|
[
"More like, the sendall() call does nothing (since there's no data to send), and thus the recv() call on the client blocks waiting for data, but since nothing was sent to the server, the server never sends any data back since it's also blocked on its initial recv(), and thus both processes are blocked.\n"
] |
[
4
] |
[] |
[] |
[
"python",
"recv",
"send",
"sockets"
] |
stackoverflow_0002549788_python_recv_send_sockets.txt
|
Q:
Using ftplib for multithread uploads
I'm trying to do multithread uploads, but get errors.
I guessed that maybe it's impossible to use multithreads with ftplib?
Here comes my code:
class myThread (threading.Thread):
def __init__(self, threadID, src, counter, image_name):
self.threadID = threadID
self.src = src
self.counter = counter
self.image_name = image_name
threading.Thread.__init__(self)
def run(self):
uploadFile(self.src, self.image_name)
def uploadFile(src, image_name):
f = open(src, "rb")
ftp.storbinary('STOR ' + image_name, f)
f.close()
ftp = FTP('host') # connect to host, default port
ftp.login() # user anonymous, passwd anonymous@
dirname = "/home/folder/"
i = 1
threads = []
for image in os.listdir(dirname):
if os.path.isfile(dirname + image):
thread = myThread(i , dirname + image, i, image )
thread.start()
threads.append( thread )
i += 1
for t in threads:
t.join()
Get bunch of ftplib errors like
raise error_reply, resp
error_reply: 200 Type set to I
If I try to upload one by one, everything works fine
A:
Have you tried to put the connection code inside the thread?
In other words, make each thread do their own separate connection with FTP.host() and FTP.login(). The server may not like multiple uploads at the same time on a single connection, because it may be parsing commands one at a time and can't handle a second upload or "STOR" command. But if you can do multiple connections from the same IP address, you'll have separate session on which to issue the 'STOR' command.
Here's an example:
class myThread (threading.Thread):
def __init__(self, threadID, src, counter, image_name):
###############
#Add ftp connection here!
self.ftp = FTP('host') # connect to host, default port
self.ftp.login() # user anonymous, passwd anonymous@
################
self.threadID = threadID
self.src = src
self.counter = counter
self.image_name = image_name
threading.Thread.__init__(self)
def run(self):
uploadFile(self.src, self.image_name)
def uploadFile(src, image_name):
f = open(src, "rb")
self.ftp.storbinary('STOR ' + image_name, f)
f.close()
dirname = "/home/folder/"
i = 1
threads = []
for image in os.listdir(dirname):
if os.path.isfile(dirname + image):
thread = myThread(i , dirname + image, i, image )
thread.start()
threads.append( thread )
i += 1
for t in threads:
t.join()
See if that behaves better.
P.S. Not sure if all my tabs are aligned.
|
Using ftplib for multithread uploads
|
I'm trying to do multithread uploads, but get errors.
I guessed that maybe it's impossible to use multithreads with ftplib?
Here comes my code:
class myThread (threading.Thread):
def __init__(self, threadID, src, counter, image_name):
self.threadID = threadID
self.src = src
self.counter = counter
self.image_name = image_name
threading.Thread.__init__(self)
def run(self):
uploadFile(self.src, self.image_name)
def uploadFile(src, image_name):
f = open(src, "rb")
ftp.storbinary('STOR ' + image_name, f)
f.close()
ftp = FTP('host') # connect to host, default port
ftp.login() # user anonymous, passwd anonymous@
dirname = "/home/folder/"
i = 1
threads = []
for image in os.listdir(dirname):
if os.path.isfile(dirname + image):
thread = myThread(i , dirname + image, i, image )
thread.start()
threads.append( thread )
i += 1
for t in threads:
t.join()
Get bunch of ftplib errors like
raise error_reply, resp
error_reply: 200 Type set to I
If I try to upload one by one, everything works fine
|
[
"Have you tried to put the connection code inside the thread? \nIn other words, make each thread do their own separate connection with FTP.host() and FTP.login(). The server may not like multiple uploads at the same time on a single connection, because it may be parsing commands one at a time and can't handle a second upload or \"STOR\" command. But if you can do multiple connections from the same IP address, you'll have separate session on which to issue the 'STOR' command.\nHere's an example:\n class myThread (threading.Thread):\n def __init__(self, threadID, src, counter, image_name):\n ###############\n #Add ftp connection here!\n self.ftp = FTP('host') # connect to host, default port\n self.ftp.login() # user anonymous, passwd anonymous@ \n ################\n self.threadID = threadID\n self.src = src\n self.counter = counter\n self.image_name = image_name\n threading.Thread.__init__(self)\n def run(self):\n uploadFile(self.src, self.image_name)\n\n def uploadFile(src, image_name):\n f = open(src, \"rb\") \n self.ftp.storbinary('STOR ' + image_name, f)\n f.close()\n\n dirname = \"/home/folder/\"\n i = 1 \n threads = []\n\n for image in os.listdir(dirname):\n if os.path.isfile(dirname + image):\n thread = myThread(i , dirname + image, i, image ) \n thread.start()\n threads.append( thread ) \n i += 1 \n\n for t in threads:\n t.join()\n\nSee if that behaves better.\nP.S. Not sure if all my tabs are aligned.\n"
] |
[
5
] |
[] |
[] |
[
"ftplib",
"multithreading",
"python"
] |
stackoverflow_0002549829_ftplib_multithreading_python.txt
|
Q:
Populate a list from xml using python
I have an xml file in the following format:
<food>
<desert>
cake
<desert>
</food>
<history>
currently in my belly
</history>
I want to create two list, food and text populated with cake and history in string format. Is there an easy way to do it in python?
A:
ElementTree (and the faster compatible implementations in cElementTree and lxml) let you very easily extract information from XML -- as long as the XML is correct and your goals are well defined.
Your example XML has at least two problems (you're opening another dessert tag instead of closing the first one, and you're missing any root element) and your goals are pretty mysterious to me (e.g., where's "text" supposed to come from?). If you edit your Q to fix your XML and clarify your exact specifications, I'm sure we can help you more.
A:
You could import xml.dom and use it to create a DOM tree which you can then read like any other DOM tree
|
Populate a list from xml using python
|
I have an xml file in the following format:
<food>
<desert>
cake
<desert>
</food>
<history>
currently in my belly
</history>
I want to create two list, food and text populated with cake and history in string format. Is there an easy way to do it in python?
|
[
"ElementTree (and the faster compatible implementations in cElementTree and lxml) let you very easily extract information from XML -- as long as the XML is correct and your goals are well defined.\nYour example XML has at least two problems (you're opening another dessert tag instead of closing the first one, and you're missing any root element) and your goals are pretty mysterious to me (e.g., where's \"text\" supposed to come from?). If you edit your Q to fix your XML and clarify your exact specifications, I'm sure we can help you more.\n",
"You could import xml.dom and use it to create a DOM tree which you can then read like any other DOM tree\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0002549895_python_xml.txt
|
Q:
Converting a Doc object into a string in python
I'm using minidom to parse through an xml document. I took the data with yum tags and stored them in a list and calculated the frequency of the words. However, its not storing or reading them as strings in the list. Is there another way to do it? Right now this is what I have:
yumNodes = [node for node in doc.getElementsByTagName("yum")]
for node in yumNodes:
yumlist.append(t.data for t in node.childNodes if t.nodeType == t.TEXT_NODE)
for ob in yumlist:
for o in ob:
if word not in freqDict:
freqDict[word] = 1
else:
freqDict[word] += 1
A:
Not directly related to your question, but as a remark that could improve your code...the pattern
freqDict = {}
...
if word not in freqDict:
freqDict[word] = 1
else:
freqDict[word] += 1
is usually replaced with
import collections
freqDict = collections.defaultdict(int)
...
freqDict[word] += 1
or pre-2.5
freqDict = {}
...
freqDict.setdefault(word, 0) += 1
A:
Replace
yumlist.append(t.data for t in node.childNodes if t.nodeType == t.TEXT_NODE)
with the following:
yumlist.append(t.nodeValue for t in node.childNodes if t.nodeType == 3)
|
Converting a Doc object into a string in python
|
I'm using minidom to parse through an xml document. I took the data with yum tags and stored them in a list and calculated the frequency of the words. However, its not storing or reading them as strings in the list. Is there another way to do it? Right now this is what I have:
yumNodes = [node for node in doc.getElementsByTagName("yum")]
for node in yumNodes:
yumlist.append(t.data for t in node.childNodes if t.nodeType == t.TEXT_NODE)
for ob in yumlist:
for o in ob:
if word not in freqDict:
freqDict[word] = 1
else:
freqDict[word] += 1
|
[
"Not directly related to your question, but as a remark that could improve your code...the pattern\nfreqDict = {}\n...\nif word not in freqDict:\n freqDict[word] = 1\nelse:\n freqDict[word] += 1\n\nis usually replaced with\nimport collections\nfreqDict = collections.defaultdict(int)\n...\nfreqDict[word] += 1\n\nor pre-2.5\nfreqDict = {}\n...\nfreqDict.setdefault(word, 0) += 1\n\n",
"Replace\nyumlist.append(t.data for t in node.childNodes if t.nodeType == t.TEXT_NODE)\n\nwith the following:\nyumlist.append(t.nodeValue for t in node.childNodes if t.nodeType == 3)\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"minidom",
"python"
] |
stackoverflow_0002549789_minidom_python.txt
|
Q:
How do I write this query in Django?
Suppose I have a datetime column.
"SELECT * FROM mytable WHERE thetime < INTERVAL 1 HOUR"
How do you write this in Django?
A:
MyModel.objects.extra(where=['thetime < INTERVAL 1 HOUR'])
|
How do I write this query in Django?
|
Suppose I have a datetime column.
"SELECT * FROM mytable WHERE thetime < INTERVAL 1 HOUR"
How do you write this in Django?
|
[
"MyModel.objects.extra(where=['thetime < INTERVAL 1 HOUR'])\n\n"
] |
[
0
] |
[] |
[] |
[
"database",
"django",
"mysql",
"python"
] |
stackoverflow_0002550164_database_django_mysql_python.txt
|
Q:
How to concat a string in Python
query = "SELECT * FROM mytable WHERE time=%s", (mytime)
Currently, I"m doing this, but I want to split it into 2 strings (so I can do them separately)
cursor.execute("SELECT * FROM mytable WHERE time=%s",(mytime))
Then, I want to add a limit %s to it. How can I do that without messing up the %s in mytime?
Edit: I want to concat query2, which has "LIMIT %s, %s"
A:
Being wary of SQL injection, you can dynamically compose your query as Ignacio suggests.
>>> qry = 'SELECT t.mycol FROM mytable t WHERE t.mycol = %%s %s' % 'LIMIT %s,%s'
You ask:
How can I do that without messing up
the %s in mytime?
Notice that you escape the first %s with an additional %.
That gives you this string (which of course looks lovely as far as the DB-API is concerned):
>>> qry
'SELECT * FROM mytable t WHERE t.mycol = %s LIMIT %s,%s'
Then pass this string and your parameters to the execute() method:
curs.execute(qry, (mytime,1,2,))
HTH
A:
cxn.execute("SELECT * FROM mytable WHERE time=%%s LIMIT %d" % (mylimit,), mytime)
Or:
cxn.execute("SELECT * FROM mytable WHERE time=%s" + (" LIMIT %d" % (mylimit,)), mytime)
|
How to concat a string in Python
|
query = "SELECT * FROM mytable WHERE time=%s", (mytime)
Currently, I"m doing this, but I want to split it into 2 strings (so I can do them separately)
cursor.execute("SELECT * FROM mytable WHERE time=%s",(mytime))
Then, I want to add a limit %s to it. How can I do that without messing up the %s in mytime?
Edit: I want to concat query2, which has "LIMIT %s, %s"
|
[
"Being wary of SQL injection, you can dynamically compose your query as Ignacio suggests.\n>>> qry = 'SELECT t.mycol FROM mytable t WHERE t.mycol = %%s %s' % 'LIMIT %s,%s'\n\nYou ask: \n\nHow can I do that without messing up\n the %s in mytime?\n\nNotice that you escape the first %s with an additional %.\nThat gives you this string (which of course looks lovely as far as the DB-API is concerned):\n>>> qry\n'SELECT * FROM mytable t WHERE t.mycol = %s LIMIT %s,%s'\n\nThen pass this string and your parameters to the execute() method:\ncurs.execute(qry, (mytime,1,2,))\n\nHTH\n",
"cxn.execute(\"SELECT * FROM mytable WHERE time=%%s LIMIT %d\" % (mylimit,), mytime)\n\nOr:\ncxn.execute(\"SELECT * FROM mytable WHERE time=%s\" + (\" LIMIT %d\" % (mylimit,)), mytime)\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002549672_python.txt
|
Q:
figuring out objects created 30 min ago in django
I have a DateTimeField called created in my model and I would like to get all the objects where created date is 30 min or more. How would query this using MyModel.objects(....) in django?
A:
Maybe something like:
import datetime
created_time = datetime.datetime.now() - datetime.timedelta(minutes=30)
old_objects = MyModel.objects.filter(created__lte=created_time)
See http://docs.djangoproject.com/en/dev/topics/db/queries/ for more information on creating queries, filtering, etc.
A:
Use this function:
.filter(created__lte=datetime.datetime.now() - datetime.timedelta(seconds=60 * 30))
|
figuring out objects created 30 min ago in django
|
I have a DateTimeField called created in my model and I would like to get all the objects where created date is 30 min or more. How would query this using MyModel.objects(....) in django?
|
[
"Maybe something like:\nimport datetime\ncreated_time = datetime.datetime.now() - datetime.timedelta(minutes=30)\nold_objects = MyModel.objects.filter(created__lte=created_time)\n\nSee http://docs.djangoproject.com/en/dev/topics/db/queries/ for more information on creating queries, filtering, etc.\n",
"Use this function:\n.filter(created__lte=datetime.datetime.now() - datetime.timedelta(seconds=60 * 30))\n\n"
] |
[
9,
1
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002550238_django_django_models_python.txt
|
Q:
Django pagination | get current index of paginated item in page index, (not the page index range itself)
I am trying to build a photo gallery with Django.
It is set up by category.
I have paginated the results of a category by n amount of images per page. I want to also use the paginator on the page that shows just the single image and have a prev/next button for the prev/next image in that category.
My thought was to get the current index for the image itself and have that be the link to the /category/CUR_IMG_ID_PAGINATION_LIST/ as the result of paginating the entire set would yield the same index as the current image index in the paginated results.
For instance if the image i want is image 45 out of 150 images total for a category, then when i paginate the 150 images the 45 will be the actual number of the page I want.
If there's an easier way to do this, let me know. Django 1.1
A:
I think the way you're describing it would work ok because behind the scenes I believe what Django is doing is using an SQL LIMIT to simply let the database do the heavy lifting of sorting out what and how much data to return. Because the database is optimized for doing this type of thing it's probably a reasonable way to perform this.
The key will probably be to keep the query the same and as you've demonstrated you could use the same view to do that. The view could simply have a mode which is a fancy way of changing the pagination page count.
You could end up with urls like this...
# View all "landscape" items in gallery mode starting on page 3
http://www.example.com/gallery/landscape/multi/3
# View the 45th landscape item in singular mode
http://www.example.com/gallery/landscape/single/45
When the template is rendered, the paginator will offer the has_next and has_previous methods letting you know if you can use render a Next/Previous link.
Here's what I'm thinking for the view, or something along these lines (this is totally un-tested and written off the top of my head)...
url(r'gallery/(?P<category>.+)/(?P<mode>.+)/(?P<offset>\d+)$', 'whatever.views.media_gallery'),
def media_gallery(request, category, mode, offset):
"""
Render a media gallery.
category = media item category filter
mode = ( multi | single )
offset = The pagination offset in multi mode or the media ID in single mode
"""
if mode == 'multi':
per_page = 20 # or however many items per page
elif mode == 'single':
per_page = 1
else:
pass # handle this however
# Queryitems
raw_media_items = Media.objects.filter(category=category)
# Setup paginator
paginator = Paginator(raw_media_items, per_page)
try:
# in multi mode offset is the page offset
# in single mode offset is the media ID
page = int(offset)
except:
page = 1
try:
media_items = paginator.page(page)
except (EmptyPage, InvalidPage):
media_items = paginator.page(paginator.num_pages)
if len(paginated_items) == 1:
# Render single view
return render_to_response('gallery/gallery_view.html',
{ 'media_item':media_items[0], 'paginator':paginator },
context_instance=RequestContext(request) )
else:
# Render gallery view
return render_to_response('gallery/gallery_view.html',
{ 'media_items':media_items, 'paginator':paginator },
context_instance=RequestContext(request) )
|
Django pagination | get current index of paginated item in page index, (not the page index range itself)
|
I am trying to build a photo gallery with Django.
It is set up by category.
I have paginated the results of a category by n amount of images per page. I want to also use the paginator on the page that shows just the single image and have a prev/next button for the prev/next image in that category.
My thought was to get the current index for the image itself and have that be the link to the /category/CUR_IMG_ID_PAGINATION_LIST/ as the result of paginating the entire set would yield the same index as the current image index in the paginated results.
For instance if the image i want is image 45 out of 150 images total for a category, then when i paginate the 150 images the 45 will be the actual number of the page I want.
If there's an easier way to do this, let me know. Django 1.1
|
[
"I think the way you're describing it would work ok because behind the scenes I believe what Django is doing is using an SQL LIMIT to simply let the database do the heavy lifting of sorting out what and how much data to return. Because the database is optimized for doing this type of thing it's probably a reasonable way to perform this.\nThe key will probably be to keep the query the same and as you've demonstrated you could use the same view to do that. The view could simply have a mode which is a fancy way of changing the pagination page count.\nYou could end up with urls like this...\n# View all \"landscape\" items in gallery mode starting on page 3\nhttp://www.example.com/gallery/landscape/multi/3\n\n# View the 45th landscape item in singular mode\nhttp://www.example.com/gallery/landscape/single/45\n\nWhen the template is rendered, the paginator will offer the has_next and has_previous methods letting you know if you can use render a Next/Previous link.\nHere's what I'm thinking for the view, or something along these lines (this is totally un-tested and written off the top of my head)...\nurl(r'gallery/(?P<category>.+)/(?P<mode>.+)/(?P<offset>\\d+)$', 'whatever.views.media_gallery'),\n\ndef media_gallery(request, category, mode, offset):\n \"\"\"\n Render a media gallery.\n category = media item category filter\n mode = ( multi | single )\n offset = The pagination offset in multi mode or the media ID in single mode\n \"\"\"\n\n if mode == 'multi':\n per_page = 20 # or however many items per page\n\n elif mode == 'single':\n per_page = 1\n else:\n pass # handle this however\n\n # Queryitems\n raw_media_items = Media.objects.filter(category=category)\n\n # Setup paginator\n paginator = Paginator(raw_media_items, per_page)\n\n try:\n # in multi mode offset is the page offset\n # in single mode offset is the media ID\n page = int(offset)\n except:\n page = 1\n\n try:\n media_items = paginator.page(page)\n except (EmptyPage, InvalidPage):\n media_items = paginator.page(paginator.num_pages)\n\n if len(paginated_items) == 1:\n # Render single view\n return render_to_response('gallery/gallery_view.html',\n { 'media_item':media_items[0], 'paginator':paginator },\n context_instance=RequestContext(request) )\n else:\n # Render gallery view\n return render_to_response('gallery/gallery_view.html',\n { 'media_items':media_items, 'paginator':paginator },\n context_instance=RequestContext(request) )\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_pagination",
"pagination",
"python"
] |
stackoverflow_0002549549_django_django_pagination_pagination_python.txt
|
Q:
Are there any libraries to allow Python or Ruby to get info from SVN?
I'm looking for plugins that will allow my codebase to interact with, browse, and poll an SVN server for information about a repository.
Trac can do this, but I was hoping there was an easy-to-use library available to accomplish the task, rather than trolling through the Trac codebase. Googling for this returns mostly vague results about storing your code in and SVN repository, which is far from what I'm looking for.
A:
pysvn
A:
Apparently Subversion ships with Ruby bindings. There is some information on Ruby SVN bindings here and here.
|
Are there any libraries to allow Python or Ruby to get info from SVN?
|
I'm looking for plugins that will allow my codebase to interact with, browse, and poll an SVN server for information about a repository.
Trac can do this, but I was hoping there was an easy-to-use library available to accomplish the task, rather than trolling through the Trac codebase. Googling for this returns mostly vague results about storing your code in and SVN repository, which is far from what I'm looking for.
|
[
"pysvn\n",
"Apparently Subversion ships with Ruby bindings. There is some information on Ruby SVN bindings here and here.\n"
] |
[
3,
2
] |
[] |
[] |
[
"python",
"ruby",
"ruby_on_rails",
"svn"
] |
stackoverflow_0002550198_python_ruby_ruby_on_rails_svn.txt
|
Q:
Python unicode issues (2.6)
I'm currently working on a irc bot for a multi-lingual channel, and I'm encountering some issues with unicode which are proving nearly impossible to solve.
No matter what configuration of unicode encoding I seem to try, the list function which the below code sits within just flat out does nothing (c.notice is a class function which sends a NOTICE command to the irc server) or when it does do something, spits out something which obviously isn't encoded.
The command should be sending 天子, but instead it seems hellbent on sending 天å with a previous configuration of the same commands. The one I have specified below is of the 'send nothing' variety. I haven't worked with unicode before this, and thus I am quite stuck. I'm also positive that I'm doing this completely wrong as a consequence.
(compileCMD just takes a list and spits out a single string of all the elements within the list)
uk = self.compileCMD(self.faq.keys(),0)
ukeys = unicode(uk,"utf-8").encode("utf-8")
c.notice(nick, u"Current list of faq entries: %s" % (uk))
A:
A few points:
The bytes "天å" are the UTF-8 encoding of "天子", so are you sure it's wrong that this is sent? Does the program/... that should process the data use UTF-8, or does it just interpret the input as a different encoding like Latin-1?
unicode(uk,"utf-8").encode("utf-8"): Decoding UTF-8 and then reencoding as UTF-8 doesn't change anything.
ukeys = unicode(uk,"utf-8").encode("utf-8"): The ukeys variable that contains the reencoded data is not used later on.
A:
Turns out the issue was with the client I was using to test the output - it wasn't handling unicode properly itself!
A:
Change this:
u"Current list of faq entries: %s" % (uk)
into this:
"Current list of faq entries: %s" % (uk)
and try again. Make sure that uk is already a UTF-8 encoded string (not unicode).
I assume that the c.notice method takes an encoded string as argument, since it's got to send an encoded string over the wire. If the channel is multilingual, it's a safe bet that it expects it to be encoded as UTF-8. Also, drop the useless ukeys = unicode(uk,"utf-8").encode("utf-8") line.
|
Python unicode issues (2.6)
|
I'm currently working on a irc bot for a multi-lingual channel, and I'm encountering some issues with unicode which are proving nearly impossible to solve.
No matter what configuration of unicode encoding I seem to try, the list function which the below code sits within just flat out does nothing (c.notice is a class function which sends a NOTICE command to the irc server) or when it does do something, spits out something which obviously isn't encoded.
The command should be sending 天子, but instead it seems hellbent on sending 天å with a previous configuration of the same commands. The one I have specified below is of the 'send nothing' variety. I haven't worked with unicode before this, and thus I am quite stuck. I'm also positive that I'm doing this completely wrong as a consequence.
(compileCMD just takes a list and spits out a single string of all the elements within the list)
uk = self.compileCMD(self.faq.keys(),0)
ukeys = unicode(uk,"utf-8").encode("utf-8")
c.notice(nick, u"Current list of faq entries: %s" % (uk))
|
[
"A few points:\n\nThe bytes \"天å\" are the UTF-8 encoding of \"天子\", so are you sure it's wrong that this is sent? Does the program/... that should process the data use UTF-8, or does it just interpret the input as a different encoding like Latin-1?\nunicode(uk,\"utf-8\").encode(\"utf-8\"): Decoding UTF-8 and then reencoding as UTF-8 doesn't change anything.\nukeys = unicode(uk,\"utf-8\").encode(\"utf-8\"): The ukeys variable that contains the reencoded data is not used later on.\n\n",
"Turns out the issue was with the client I was using to test the output - it wasn't handling unicode properly itself!\n",
"Change this:\nu\"Current list of faq entries: %s\" % (uk)\n\ninto this:\n\"Current list of faq entries: %s\" % (uk)\n\nand try again. Make sure that uk is already a UTF-8 encoded string (not unicode).\nI assume that the c.notice method takes an encoded string as argument, since it's got to send an encoded string over the wire. If the channel is multilingual, it's a safe bet that it expects it to be encoded as UTF-8. Also, drop the useless ukeys = unicode(uk,\"utf-8\").encode(\"utf-8\") line.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"encoding",
"irc",
"python",
"unicode",
"utf_8"
] |
stackoverflow_0002547517_encoding_irc_python_unicode_utf_8.txt
|
Q:
how to write re-usable views in django?
These are the techniques that I use regularly to make my views reusable:
take the template_name as an argument with a default
take an optional extra_context which defaults to empty {}
right before the template is rendered the context is updated with the extra_context
for further re-usability, call any callable in extra_context.values()
whenever the view deals with a queryset, there is a queryset argument with a default
whenever the view needs a particular object from the ORM, it attempts to fetch it using any "id" parameter in several ways (e.g. as a slug, as a database id) (this may be a bad practice...)
First, should I add anything to my list? Should I remove anything from my list?
The items accommodates a large number of cases. However, whenever an app extends a model of another in some way (e.g. adding a field or changing the behavior in some way) I end up writing my own views and only reusing the model. Is this normal?
Edit/answering my own question partially:
signals: the view should emit a signal when it starts and one before it returns the response
A:
I would think that doing all of those puts a large burden on your urlconf to get everything right. Perhaps making a function that takes all that and hardcoding your views to be a glorified wrapper around said function would be better.
A:
whenever the view needs a particular object from the ORM, it attempts to fetch it using any "id" parameter in several ways (e.g. as a slug, as a database id) (this may be a bad practice...)
So... why not just expect a model instance to be passed in as a parameter? Or a QuerySet from which you will take element 0? Then you can combine it with the QuerySet case, and maybe roll it into get_object_or_404.
My suggestion is to look at how Django's generic views are written. They're solving the same general class of problems you are. You seem most of the way there, except for the last part.
|
how to write re-usable views in django?
|
These are the techniques that I use regularly to make my views reusable:
take the template_name as an argument with a default
take an optional extra_context which defaults to empty {}
right before the template is rendered the context is updated with the extra_context
for further re-usability, call any callable in extra_context.values()
whenever the view deals with a queryset, there is a queryset argument with a default
whenever the view needs a particular object from the ORM, it attempts to fetch it using any "id" parameter in several ways (e.g. as a slug, as a database id) (this may be a bad practice...)
First, should I add anything to my list? Should I remove anything from my list?
The items accommodates a large number of cases. However, whenever an app extends a model of another in some way (e.g. adding a field or changing the behavior in some way) I end up writing my own views and only reusing the model. Is this normal?
Edit/answering my own question partially:
signals: the view should emit a signal when it starts and one before it returns the response
|
[
"I would think that doing all of those puts a large burden on your urlconf to get everything right. Perhaps making a function that takes all that and hardcoding your views to be a glorified wrapper around said function would be better.\n",
"\nwhenever the view needs a particular object from the ORM, it attempts to fetch it using any \"id\" parameter in several ways (e.g. as a slug, as a database id) (this may be a bad practice...)\n\nSo... why not just expect a model instance to be passed in as a parameter? Or a QuerySet from which you will take element 0? Then you can combine it with the QuerySet case, and maybe roll it into get_object_or_404.\nMy suggestion is to look at how Django's generic views are written. They're solving the same general class of problems you are. You seem most of the way there, except for the last part.\n"
] |
[
0,
0
] |
[] |
[] |
[
"django",
"python",
"views"
] |
stackoverflow_0002550308_django_python_views.txt
|
Q:
Correct way to put long function calls on multiple lines
I have a long function, as seen below:
hash_correct = hashlib.md5(salt + password)).digest().encode("base64")
I'd like to split it up into two lines but am not sure of the correct way to do this in Python?
Thanks.
A:
The coding guidelines limiting length of lines is there, in part, to make the code more readable. In your case of chained method calls, the meaning is not clear. You should pick some temporary variable names for the intermediate values so that a reader of the code can understand the chain easily.
One example might be:
safe_md5 = hashlib.md5(salt + password)
crypto_hash = safe_md5.digest()
hash_correct = crypto_hash.encode('base64')
This leads the reader down a garden path to understanding. Very little is lost in performance, and the additional code is all added for purpose.
A:
Prefer Charles Merram's answer, but I thought this worth noting as working but ugly and to be discouraged. Because '.' is a lexical delimiter, the following worked:
>>> 'abc def' . split()
['abc', 'def']
>>> 'abc def' . \
... split()
['abc', 'def']
>>> sys.version
'2.6.4 (r264:75706, Dec 7 2009, 18:45:15) \n[GCC 4.4.1]'
but don't do that.
|
Correct way to put long function calls on multiple lines
|
I have a long function, as seen below:
hash_correct = hashlib.md5(salt + password)).digest().encode("base64")
I'd like to split it up into two lines but am not sure of the correct way to do this in Python?
Thanks.
|
[
"The coding guidelines limiting length of lines is there, in part, to make the code more readable. In your case of chained method calls, the meaning is not clear. You should pick some temporary variable names for the intermediate values so that a reader of the code can understand the chain easily.\nOne example might be:\nsafe_md5 = hashlib.md5(salt + password)\ncrypto_hash = safe_md5.digest()\nhash_correct = crypto_hash.encode('base64')\n\nThis leads the reader down a garden path to understanding. Very little is lost in performance, and the additional code is all added for purpose.\n",
"Prefer Charles Merram's answer, but I thought this worth noting as working but ugly and to be discouraged. Because '.' is a lexical delimiter, the following worked:\n>>> 'abc def' . split()\n['abc', 'def']\n>>> 'abc def' . \\\n... split()\n['abc', 'def']\n>>> sys.version\n'2.6.4 (r264:75706, Dec 7 2009, 18:45:15) \\n[GCC 4.4.1]'\n\nbut don't do that.\n"
] |
[
21,
3
] |
[] |
[] |
[
"multiline",
"python"
] |
stackoverflow_0002550439_multiline_python.txt
|
Q:
Purpose of SQLAlchemy over MySQLdb
Why do people use SQLAlchemy instead of MySQLdb? What advantages does it offer?
A:
You don't use SQLAlchemy instead of MySQLdb—you use SQLAlchemy to access something like MySQLdb, oursql (another MySQL driver that I hear is nicer and has better performance), the sqlite3 module, psycopg2, or whatever other database driver you are using.
An ORM (like SQLAlchemy) helps abstract away the details of the database you are using. This allows you to keep from the miry details of the database system you're using, avoiding the possibility of errors some times (and introducing the possibility of others), and making porting trivial (at least in theory).
A:
Easier portability among different DB engines (say that tomorrow you decide you want to move to sqlite, or PostgreSQL, or...), and higher level of abstraction (and thus potentially higher productivity).
Those are some of the good reasons. There are also some bad reasons for using an ORM, such as not wanting to learn SQL, but I suspect SQLAlchemy in particular is not really favored by people for such bad reasons for wanting an ORM rather than bare SQL;-).
A:
In addition to what Alex said...
"Not wanting to learn SQL" is probably a bad thing. However, if you want to get more people who want to avoid SQL involved as part of the development process, ORMs do a pretty good job at it because it abstracts away "raw SQL," pushing that level of complexity down a notch. One of the elements that has made Django successful is its ability to let "newspaper journalists" maintain a website, rather than software engineers.
One of the limitations of ORMs is that they are not as scalable as using raw SQL. At a previous job, we wanted to get rid of a lot of manual SQL generation and switched to an ORM for ease-of-use (SQLAlchemy, Elixir, etc.), but months later, I ended up having to write raw SQL again to get around the inefficient or high latency queries that were generated by the ORM system.
|
Purpose of SQLAlchemy over MySQLdb
|
Why do people use SQLAlchemy instead of MySQLdb? What advantages does it offer?
|
[
"You don't use SQLAlchemy instead of MySQLdb—you use SQLAlchemy to access something like MySQLdb, oursql (another MySQL driver that I hear is nicer and has better performance), the sqlite3 module, psycopg2, or whatever other database driver you are using. \nAn ORM (like SQLAlchemy) helps abstract away the details of the database you are using. This allows you to keep from the miry details of the database system you're using, avoiding the possibility of errors some times (and introducing the possibility of others), and making porting trivial (at least in theory).\n",
"Easier portability among different DB engines (say that tomorrow you decide you want to move to sqlite, or PostgreSQL, or...), and higher level of abstraction (and thus potentially higher productivity).\nThose are some of the good reasons. There are also some bad reasons for using an ORM, such as not wanting to learn SQL, but I suspect SQLAlchemy in particular is not really favored by people for such bad reasons for wanting an ORM rather than bare SQL;-).\n",
"In addition to what Alex said...\n\n\"Not wanting to learn SQL\" is probably a bad thing. However, if you want to get more people who want to avoid SQL involved as part of the development process, ORMs do a pretty good job at it because it abstracts away \"raw SQL,\" pushing that level of complexity down a notch. One of the elements that has made Django successful is its ability to let \"newspaper journalists\" maintain a website, rather than software engineers.\n\nOne of the limitations of ORMs is that they are not as scalable as using raw SQL. At a previous job, we wanted to get rid of a lot of manual SQL generation and switched to an ORM for ease-of-use (SQLAlchemy, Elixir, etc.), but months later, I ended up having to write raw SQL again to get around the inefficient or high latency queries that were generated by the ORM system.\n\n\n"
] |
[
34,
13,
5
] |
[] |
[] |
[
"mysql",
"python",
"sql",
"sqlalchemy"
] |
stackoverflow_0002550292_mysql_python_sql_sqlalchemy.txt
|
Q:
Python - List and Loop in one def
I'm trying to get the def wfsc_pod1 and wfsc_ip into the same def. I'm not quite sure how to approach the problem. I want wfsc_pod1 to display all the information for name, subnet and gateway. Then wfsc_ip shows the ip addresses below it. I also get a None value when I run it as it. Not sure why. Anything more pythonic is more appreciated.
class OutageAddress:
subnet = ["255.255.255.0", "255.255.255.1"]
# Gateway order is matched with names
gateway = ["192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4",
"192.168.1.5", "192.168.1.6", "192.168.1.7", "192.168.1.8",
"192.168.1.9"]
name = ["LOC1", "LOC2", "LOC3", "LOC4",
"LOC5", "LOC6", "LOC7", "LOC8",
"LOC9"]
def wfsc_pod1(self):
wfsc_1 = "%s\t %s\t %s\t" % (network.name[0],network.subnet[0],network.gateway[0])
return wfsc_1
def wfsc_ip(self):
for ip in range(100,110):
ip = "192.168.1."+str(ip)
print ip
network = OutageAddress()
print network.wfsc_pod1()
print network.wfsc_ip()
A:
First of all, you probably meant to write wfsc_pod1 like this:
def wfsc_pod1(self):
return "%s\t%s\t%s" % (self.name[0], self.subnet[0], self.gateway[0])
and call wfsc_ip like this:
network.wfsc_ip() # no print
If you want to combine wfsc_pod1 and wfsc_ip, you can do this:
def wfsc_combined(self):
output = []
output.append("%s\t%s\t%s" % (self.name[0], self.subnet[0], self.gateway[0]))
for ip in range(100,110):
output.append("192.168.1.%d" % ip)
return '\n'.join(output)
and call this function with a print statement.
However, a better approach (IMO) would be to add print statements inside wfsc_combined and call it without a print statement:
def wfsc_combined(self):
print "%s\t%s\t%s" % (self.name[0], self.subnet[0], self.gateway[0])
for ip in range(100,110):
print "192.168.1.%d" % ip
A:
OutageAddress.wfsc_ip returns None because it has no return statement.
A:
You get a None because that is what wfsc_ip returns. Functions/methods that don't return anything else return None.
A:
You get None from print network.wfsc_ip() because wfsc_ip doesn't return anything, which is the same thing as returning None -- what else did you expect to get from printing the value of a function that just doesn't return anything?!
You seem to be in thrall to a deep confusion between displaying stuff (e.g. with print statements, as wfsc_ip does) and returning information, as wfsc_pod1 does. Until and unless you clarify that confusion, nobody can really help you much.
|
Python - List and Loop in one def
|
I'm trying to get the def wfsc_pod1 and wfsc_ip into the same def. I'm not quite sure how to approach the problem. I want wfsc_pod1 to display all the information for name, subnet and gateway. Then wfsc_ip shows the ip addresses below it. I also get a None value when I run it as it. Not sure why. Anything more pythonic is more appreciated.
class OutageAddress:
subnet = ["255.255.255.0", "255.255.255.1"]
# Gateway order is matched with names
gateway = ["192.168.1.1", "192.168.1.2", "192.168.1.3", "192.168.1.4",
"192.168.1.5", "192.168.1.6", "192.168.1.7", "192.168.1.8",
"192.168.1.9"]
name = ["LOC1", "LOC2", "LOC3", "LOC4",
"LOC5", "LOC6", "LOC7", "LOC8",
"LOC9"]
def wfsc_pod1(self):
wfsc_1 = "%s\t %s\t %s\t" % (network.name[0],network.subnet[0],network.gateway[0])
return wfsc_1
def wfsc_ip(self):
for ip in range(100,110):
ip = "192.168.1."+str(ip)
print ip
network = OutageAddress()
print network.wfsc_pod1()
print network.wfsc_ip()
|
[
"First of all, you probably meant to write wfsc_pod1 like this:\ndef wfsc_pod1(self):\n return \"%s\\t%s\\t%s\" % (self.name[0], self.subnet[0], self.gateway[0])\n\nand call wfsc_ip like this:\nnetwork.wfsc_ip() # no print\n\nIf you want to combine wfsc_pod1 and wfsc_ip, you can do this:\ndef wfsc_combined(self):\n output = []\n output.append(\"%s\\t%s\\t%s\" % (self.name[0], self.subnet[0], self.gateway[0]))\n for ip in range(100,110):\n output.append(\"192.168.1.%d\" % ip)\n return '\\n'.join(output)\n\nand call this function with a print statement.\nHowever, a better approach (IMO) would be to add print statements inside wfsc_combined and call it without a print statement:\ndef wfsc_combined(self):\n print \"%s\\t%s\\t%s\" % (self.name[0], self.subnet[0], self.gateway[0])\n for ip in range(100,110):\n print \"192.168.1.%d\" % ip\n\n",
"OutageAddress.wfsc_ip returns None because it has no return statement.\n",
"You get a None because that is what wfsc_ip returns. Functions/methods that don't return anything else return None.\n",
"You get None from print network.wfsc_ip() because wfsc_ip doesn't return anything, which is the same thing as returning None -- what else did you expect to get from printing the value of a function that just doesn't return anything?!\nYou seem to be in thrall to a deep confusion between displaying stuff (e.g. with print statements, as wfsc_ip does) and returning information, as wfsc_pod1 does. Until and unless you clarify that confusion, nobody can really help you much.\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002550642_python.txt
|
Q:
How do I use Django to insert a Geometry Field into the database?
class LocationLog(models.Model):
user = models.ForeignKey(User)
utm = models.GeometryField(spatial_index=True)
This is my database model. I would like to insert a row.
I want to insert a circle at point -55, 333. With a radius of 10. How can I put this circle into the geometry field?
Of course, then I would want to check which circles overlap a given circle. (my select statement)
A:
Solved.
I created a square.
from django.contrib.gis.geos import Polygon
s = Polygon(( (x-rad,y+rad)
,(x+rad,y+rad)
,(x+rad,y-rad)
,(x-rad,y-rad)
,(x-rad,y+rad) )
)
Then you insert s into the database as a GeometryField.
|
How do I use Django to insert a Geometry Field into the database?
|
class LocationLog(models.Model):
user = models.ForeignKey(User)
utm = models.GeometryField(spatial_index=True)
This is my database model. I would like to insert a row.
I want to insert a circle at point -55, 333. With a radius of 10. How can I put this circle into the geometry field?
Of course, then I would want to check which circles overlap a given circle. (my select statement)
|
[
"Solved.\nI created a square.\nfrom django.contrib.gis.geos import Polygon\n\ns = Polygon(( (x-rad,y+rad)\n ,(x+rad,y+rad)\n ,(x+rad,y-rad)\n ,(x-rad,y-rad)\n ,(x-rad,y+rad) )\n )\n\nThen you insert s into the database as a GeometryField.\n"
] |
[
1
] |
[] |
[] |
[
"database",
"django",
"geometry",
"mysql",
"python"
] |
stackoverflow_0002550506_database_django_geometry_mysql_python.txt
|
Q:
Disable Plone Archetypes index/convert doc/pdf files
If I rebuild my catalog in plone I get many of these infos:
2010-02-18T11:26:09 INFO Archetypes Error while trying to convert file contents to 'text/plain' in <Field file(file:rw)>.getIndexable() of <ATFile at /site/test1/test.doc>: Unable to find binary "wvHtml" in /sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/usr/games:/usr/lib/jvm/jre/bin
This happens to .doc and .pdf files.
I don't want to convert docs or PDFs. How can I disable it completely?
A:
You can disable (remove) transforms in ZMI/portal_transforms tool. If Plone does not find transform from Word to plain text or PDF to plain text, it won't try to index the file contents.
Go to ZMI/portal_transforms and remove word_to_html item.
A:
It is trying to index your doc/pdf files by converting them to HTML files first. Just install wv(ware). The message will go away and all your DOC & PDF files will be indexed and show up in your searches.
On Ubuntu/Debian: sudo apt-get install wv
Is there a reason you don't want to index PDFs or Word documents?
A:
I don't wanna convert docs or pdfs. How can i disable it completly? [sic]
Well, you're currently not indexing them, so there's nothing to change.
The above message is an INFO message, it's not an error. If you don't want to see these in your event log, you can change the event-log-level in your buildout configuration or your zope.conf
from the docs:
event-log-level
Set the level of the console output for the event log. Level may be any of
CRITICAL, ERROR, WARN, INFO, DEBUG, or ALL. Defaults to INFO.
|
Disable Plone Archetypes index/convert doc/pdf files
|
If I rebuild my catalog in plone I get many of these infos:
2010-02-18T11:26:09 INFO Archetypes Error while trying to convert file contents to 'text/plain' in <Field file(file:rw)>.getIndexable() of <ATFile at /site/test1/test.doc>: Unable to find binary "wvHtml" in /sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/usr/games:/usr/lib/jvm/jre/bin
This happens to .doc and .pdf files.
I don't want to convert docs or PDFs. How can I disable it completely?
|
[
"You can disable (remove) transforms in ZMI/portal_transforms tool. If Plone does not find transform from Word to plain text or PDF to plain text, it won't try to index the file contents.\nGo to ZMI/portal_transforms and remove word_to_html item.\n",
"It is trying to index your doc/pdf files by converting them to HTML files first. Just install wv(ware). The message will go away and all your DOC & PDF files will be indexed and show up in your searches.\nOn Ubuntu/Debian: sudo apt-get install wv\nIs there a reason you don't want to index PDFs or Word documents?\n",
"\nI don't wanna convert docs or pdfs. How can i disable it completly? [sic]\n\nWell, you're currently not indexing them, so there's nothing to change.\nThe above message is an INFO message, it's not an error. If you don't want to see these in your event log, you can change the event-log-level in your buildout configuration or your zope.conf\nfrom the docs:\nevent-log-level\n Set the level of the console output for the event log. Level may be any of\n CRITICAL, ERROR, WARN, INFO, DEBUG, or ALL. Defaults to INFO.\n\n"
] |
[
4,
2,
1
] |
[] |
[] |
[
"archetypes",
"plone",
"plone_3.x",
"python",
"zope"
] |
stackoverflow_0002288470_archetypes_plone_plone_3.x_python_zope.txt
|
Q:
In Python, how would I do this Datetime?
right_now = datetime.datetime.now()
one_hour_before = ?????
How can I use right_now to get one_hour_before?
A:
right_now = datetime.datetime.now()
one_hour_before = right_now - datetime.timedelta(hours=1)
A:
You need to use datetime.timedelta like so:
right_now = datetime.datetime.now()
one_hour_before = right_now - datetime.timedelta(hours = 1)
|
In Python, how would I do this Datetime?
|
right_now = datetime.datetime.now()
one_hour_before = ?????
How can I use right_now to get one_hour_before?
|
[
"right_now = datetime.datetime.now()\none_hour_before = right_now - datetime.timedelta(hours=1)\n\n",
"You need to use datetime.timedelta like so:\nright_now = datetime.datetime.now()\none_hour_before = right_now - datetime.timedelta(hours = 1)\n\n"
] |
[
7,
1
] |
[] |
[] |
[
"datetime",
"python"
] |
stackoverflow_0002550812_datetime_python.txt
|
Q:
How do I write this insert statement in Django?
newthing = Link(user=request.user,last_updated=datetime.datetime.now())
However, this uses datetime , not the MYSQL "now()".
How can I use mysql's now()?
A:
I'm not sure if this uses the MySQL now() call, but the right way to do this in Django is to use the auto_now_add or auto_add options on a DateField/DateTimeField:
class Link(models.Model):
...
last_updated = models.DateTimeField(auto_now_add = True)
...
Note: I am assuming here that Link is a Model.
|
How do I write this insert statement in Django?
|
newthing = Link(user=request.user,last_updated=datetime.datetime.now())
However, this uses datetime , not the MYSQL "now()".
How can I use mysql's now()?
|
[
"I'm not sure if this uses the MySQL now() call, but the right way to do this in Django is to use the auto_now_add or auto_add options on a DateField/DateTimeField:\nclass Link(models.Model):\n ...\n last_updated = models.DateTimeField(auto_now_add = True)\n ...\n\nNote: I am assuming here that Link is a Model.\n"
] |
[
2
] |
[] |
[] |
[
"database",
"django",
"mysql",
"python"
] |
stackoverflow_0002550806_database_django_mysql_python.txt
|
Q:
exe created by py2exe give error
i have created an exe from py2exe. After successfully creating the exe, i got the following error when i run main.exe.
File "_mssql.pyc", line 12, in <module>
File "_mssql.pyc", line 10, in __load
ImportError: DLL load failed: The specified module could not be found.
I am using pymssql module for sql server.
A:
make sure you include the module under the options dictionary. I think it also needs a dll file called ntwdblib.dll. you can find that file and include it into your setup.py.
import os, pymssql
from distutils.core import setup
import py2exe
dll = []
dll.append(os.path.join(os.path.split(pymssql.__file__)[0], 'ntwdblib.dll'))
pyops = {"includes": ['decimal']}
setup(console=['app.py'], options={"py2exe": pyops}, data_files=dll)
|
exe created by py2exe give error
|
i have created an exe from py2exe. After successfully creating the exe, i got the following error when i run main.exe.
File "_mssql.pyc", line 12, in <module>
File "_mssql.pyc", line 10, in __load
ImportError: DLL load failed: The specified module could not be found.
I am using pymssql module for sql server.
|
[
"make sure you include the module under the options dictionary. I think it also needs a dll file called ntwdblib.dll. you can find that file and include it into your setup.py.\nimport os, pymssql\nfrom distutils.core import setup\nimport py2exe\ndll = []\ndll.append(os.path.join(os.path.split(pymssql.__file__)[0], 'ntwdblib.dll'))\npyops = {\"includes\": ['decimal']}\nsetup(console=['app.py'], options={\"py2exe\": pyops}, data_files=dll)\n\n"
] |
[
5
] |
[] |
[] |
[
"py2exe",
"python"
] |
stackoverflow_0002551003_py2exe_python.txt
|
Q:
Why does a JRuby application on App Engine take so long to start (versus a Python app)?
I'm considering using JRuby on App Engine but have heard that Juby app on App Engine have a long startup lag versus a Python app. Why is this?
Is it because the JRuby jar files are so large that a cold startup requires them to be loaded into memory before the app can start serving? That would be my guess but I'm not sure if that's a precise technical explanation. And, if so, why is Python different?
A:
That's basically it. When your app hasn't been used in a while, App Engine swaps it out until another request comes in.
When that happens, it loads all the JARs your app requires, which may take a very long time, upwards of 10-15+ seconds in some cases.
I don't have any experience with JRuby in particular, but this page has some tips on how to reduce your app's cold start time. The tips should be useful even if you're not strictly writing vanilla Java.
Basically, just don't include any JARs that your app doesn't rely heavily upon.
A:
Disclaimer: I haven't benchmarked this myself
The difference between the Python version and JRuby in particular
probably have lots to do with the fact that JRuby is a language
implemented on top of another language. The Python engine on the other
hand is native, and much closer to CPython (some in-house variant of
Unladen swallow, I would guess). This means that for Python, the
interpreter is by definition already loaded, but for JRuby, your
application must start with loading the Ruby interpreter before it can
start with it's application's logic.
|
Why does a JRuby application on App Engine take so long to start (versus a Python app)?
|
I'm considering using JRuby on App Engine but have heard that Juby app on App Engine have a long startup lag versus a Python app. Why is this?
Is it because the JRuby jar files are so large that a cold startup requires them to be loaded into memory before the app can start serving? That would be my guess but I'm not sure if that's a precise technical explanation. And, if so, why is Python different?
|
[
"That's basically it. When your app hasn't been used in a while, App Engine swaps it out until another request comes in.\nWhen that happens, it loads all the JARs your app requires, which may take a very long time, upwards of 10-15+ seconds in some cases.\nI don't have any experience with JRuby in particular, but this page has some tips on how to reduce your app's cold start time. The tips should be useful even if you're not strictly writing vanilla Java.\nBasically, just don't include any JARs that your app doesn't rely heavily upon.\n",
"Disclaimer: I haven't benchmarked this myself\nThe difference between the Python version and JRuby in particular\nprobably have lots to do with the fact that JRuby is a language\nimplemented on top of another language. The Python engine on the other\nhand is native, and much closer to CPython (some in-house variant of\nUnladen swallow, I would guess). This means that for Python, the\ninterpreter is by definition already loaded, but for JRuby, your\napplication must start with loading the Ruby interpreter before it can\nstart with it's application's logic.\n"
] |
[
10,
0
] |
[] |
[] |
[
"google_app_engine",
"java",
"jruby",
"python",
"ruby"
] |
stackoverflow_0002547498_google_app_engine_java_jruby_python_ruby.txt
|
Q:
String formatting: string specifier in a string constant
Is there a way to insert a string in a string constant/variable that contains a string specifier?
Example:
temp_body = 'Hello %s, please visit %s to confirm your registration.'
body = temp_body % (name, url)
But this raises a TypeError.
A:
Works on my machine(TM).
Are you sure that name and url really are strings? What do you get when you do
>>> type(name), type(url)
A:
Usually it is the way strings are generated e.g. msg template will be loaded from db or some file and things inserted in between, what is url and name in your case?
This works on my machine
>>> temp_body = 'Hello %s, please visit %s to confirm your registration.'
>>> temp_body%("anurag", "stackoverflow")
'Hello anurag, please visit stackoverflow to confirm your registration.'
Also try if str(name), str(url) works , ost probably it won't and try to fix that problem instead.
|
String formatting: string specifier in a string constant
|
Is there a way to insert a string in a string constant/variable that contains a string specifier?
Example:
temp_body = 'Hello %s, please visit %s to confirm your registration.'
body = temp_body % (name, url)
But this raises a TypeError.
|
[
"Works on my machine(TM).\nAre you sure that name and url really are strings? What do you get when you do\n>>> type(name), type(url)\n\n",
"Usually it is the way strings are generated e.g. msg template will be loaded from db or some file and things inserted in between, what is url and name in your case?\nThis works on my machine\n>>> temp_body = 'Hello %s, please visit %s to confirm your registration.'\n>>> temp_body%(\"anurag\", \"stackoverflow\")\n'Hello anurag, please visit stackoverflow to confirm your registration.'\n\nAlso try if str(name), str(url) works , ost probably it won't and try to fix that problem instead.\n"
] |
[
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002551236_python.txt
|
Q:
django send_mail from queryset
I am trying to use the django send_mail method. I am running into 2 issues, notably converting mail addresses from a list into a csv to be used in the recipients. The second issue is getting the list of user emails from the notifications model.
my models
class notifications(models.Model):
notID = models.AutoField(primary_key=True)
notSubject = models.CharField(max_length=100)
notBody = models.TextField()
notDate = models.DateField(auto_now_add=True)
notRecepients = models.ManyToManyField(UserProfile, related_name='recepients')
notPoster = models.ForeignKey(UserProfile,related_name='notposter')
deleted = models.BooleanField()
def __unicode__(self):
return u'%s ' % ( self.notSubject)
class UserProfile(User):
onames = models.CharField(max_length=30, blank=True)
phoneNumber = models.CharField(max_length=15, blank=True)
regNo = models.CharField(max_length=15)
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True, default='photos/2010/03/placeholder.jpg')
course = models.CharField(max_length=30, blank=True, null=True)
timezone = models.CharField(max_length=50, default='Africa/Nairobi')
smsCom = models.BooleanField()
mailCom = models.BooleanField()
class notifications_sms_mail(models.Model):
notId = models.OneToOneField(notifications)
sms = models.BooleanField()
email = models.BooleanField()
my view
def notif_sms_mail(request):
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
mailform = notif_sms_mail_Form(request.POST)
if mailform.is_valid():
notid=request.POST['notId']
mailform.save()
notif = notifications.objects.get(deleted='0', notID = notid)
rec = (UserProfile.objects.values('email')).filter(mailCom='1')
mail = notifications_sms_mail.objects.get(email='1', notId=notid)
if notif.notID == mail.notId:
send_mail(notSubject, notBody, 'from ****@gmail.com',rec, fail_silently=False)
A:
UserProfile.objects.filter(mailCom='1').values_list('email', flat=True)
|
django send_mail from queryset
|
I am trying to use the django send_mail method. I am running into 2 issues, notably converting mail addresses from a list into a csv to be used in the recipients. The second issue is getting the list of user emails from the notifications model.
my models
class notifications(models.Model):
notID = models.AutoField(primary_key=True)
notSubject = models.CharField(max_length=100)
notBody = models.TextField()
notDate = models.DateField(auto_now_add=True)
notRecepients = models.ManyToManyField(UserProfile, related_name='recepients')
notPoster = models.ForeignKey(UserProfile,related_name='notposter')
deleted = models.BooleanField()
def __unicode__(self):
return u'%s ' % ( self.notSubject)
class UserProfile(User):
onames = models.CharField(max_length=30, blank=True)
phoneNumber = models.CharField(max_length=15, blank=True)
regNo = models.CharField(max_length=15)
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True, default='photos/2010/03/placeholder.jpg')
course = models.CharField(max_length=30, blank=True, null=True)
timezone = models.CharField(max_length=50, default='Africa/Nairobi')
smsCom = models.BooleanField()
mailCom = models.BooleanField()
class notifications_sms_mail(models.Model):
notId = models.OneToOneField(notifications)
sms = models.BooleanField()
email = models.BooleanField()
my view
def notif_sms_mail(request):
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
mailform = notif_sms_mail_Form(request.POST)
if mailform.is_valid():
notid=request.POST['notId']
mailform.save()
notif = notifications.objects.get(deleted='0', notID = notid)
rec = (UserProfile.objects.values('email')).filter(mailCom='1')
mail = notifications_sms_mail.objects.get(email='1', notId=notid)
if notif.notID == mail.notId:
send_mail(notSubject, notBody, 'from ****@gmail.com',rec, fail_silently=False)
|
[
"UserProfile.objects.filter(mailCom='1').values_list('email', flat=True)\n\n"
] |
[
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002551353_django_python.txt
|
Q:
How can I write this query in Django? (datetime)
| time_before | datetime | YES | MUL | NULL | |
| time_after | datetime | YES | MUL | NULL | |
the_tag = Tag.objects.get(id=tag_id)
Log.objects.filter(blah).extra(where=['last_updated >'+the_tag.time_before, 'last_updated' < the_tag.time_after])
Ok. Basically, I have an object that's called "the_tag". I want to select from Log where log.last_updated (which is a datetime field) is between the tag's time. But, I don't know how to write the last part of this Django query.
A:
To get the exact behaviour of your example:
Log.objects.filter(last_updated__gt=the_tag.time_before, last_updated__lt=the_tag.time_after)
For an inclusive range (equivalent to __gte, __lte) the query is a bit simpler:
Log.objects.filter(last_updated__range=(the_tag.time_before, the_tag.time_after))
|
How can I write this query in Django? (datetime)
|
| time_before | datetime | YES | MUL | NULL | |
| time_after | datetime | YES | MUL | NULL | |
the_tag = Tag.objects.get(id=tag_id)
Log.objects.filter(blah).extra(where=['last_updated >'+the_tag.time_before, 'last_updated' < the_tag.time_after])
Ok. Basically, I have an object that's called "the_tag". I want to select from Log where log.last_updated (which is a datetime field) is between the tag's time. But, I don't know how to write the last part of this Django query.
|
[
"To get the exact behaviour of your example:\nLog.objects.filter(last_updated__gt=the_tag.time_before, last_updated__lt=the_tag.time_after)\n\nFor an inclusive range (equivalent to __gte, __lte) the query is a bit simpler:\nLog.objects.filter(last_updated__range=(the_tag.time_before, the_tag.time_after))\n\n"
] |
[
6
] |
[] |
[] |
[
"database",
"django",
"mysql",
"python"
] |
stackoverflow_0002551475_database_django_mysql_python.txt
|
Q:
Processing RSS/RDF via xml.dom.minidom
I'm trying to process a delicious rss feed via python. Here's a sample:
...
<item rdf:about="http://weblist.me/">
<title>WebList - The Place To Find The Best List On The Web</title>
<dc:date>2009-12-24T17:46:14Z</dc:date>
<link>http://weblist.me/</link>
...
</item>
<item rdf:about="http://thumboo.com/">
<title>Thumboo! Free Website Thumbnails and PHP Script to Generate Web Screenshots</title>
<dc:date>2006-10-24T18:11:32Z</dc:date>
<link>http://thumboo.com/</link>
...
The relevant code is:
def getText(nodelist):
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
return rc
dom = xml.dom.minidom.parse(file)
items = dom.getElementsByTagName("item")
for i in items:
title = i.getElementsByTagName("title")
print getText(title)
I would think this would print out each title, but instead I get basically get blank output. I'm sure I'm doing something stupid wrong, but no idea what?
A:
You are passing the title nodes to getText, whose nodeTypes are not node.TEXT_NODE. You have to loop over all the children of the node instead in your getText method:
def getTextSingle(node):
parts = [child.data for child in node.childNodes if child.nodeType == node.TEXT_NODE]
return u"".join(parts)
def getText(nodelist):
return u"".join(getTextSingle(node) for node in nodelist)
Even better, call node.normalize() before calling getTextSingle which ensures that consecutive children of type node.TEXT_NODE are merged into a single node.TEXT_NODE.
|
Processing RSS/RDF via xml.dom.minidom
|
I'm trying to process a delicious rss feed via python. Here's a sample:
...
<item rdf:about="http://weblist.me/">
<title>WebList - The Place To Find The Best List On The Web</title>
<dc:date>2009-12-24T17:46:14Z</dc:date>
<link>http://weblist.me/</link>
...
</item>
<item rdf:about="http://thumboo.com/">
<title>Thumboo! Free Website Thumbnails and PHP Script to Generate Web Screenshots</title>
<dc:date>2006-10-24T18:11:32Z</dc:date>
<link>http://thumboo.com/</link>
...
The relevant code is:
def getText(nodelist):
rc = ""
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
rc = rc + node.data
return rc
dom = xml.dom.minidom.parse(file)
items = dom.getElementsByTagName("item")
for i in items:
title = i.getElementsByTagName("title")
print getText(title)
I would think this would print out each title, but instead I get basically get blank output. I'm sure I'm doing something stupid wrong, but no idea what?
|
[
"You are passing the title nodes to getText, whose nodeTypes are not node.TEXT_NODE. You have to loop over all the children of the node instead in your getText method:\ndef getTextSingle(node):\n parts = [child.data for child in node.childNodes if child.nodeType == node.TEXT_NODE]\n return u\"\".join(parts)\n\ndef getText(nodelist):\n return u\"\".join(getTextSingle(node) for node in nodelist)\n\nEven better, call node.normalize() before calling getTextSingle which ensures that consecutive children of type node.TEXT_NODE are merged into a single node.TEXT_NODE.\n"
] |
[
4
] |
[] |
[] |
[
"python",
"rss"
] |
stackoverflow_0002551214_python_rss.txt
|
Q:
Python - CSV: Large file with rows of different lengths
In short, I have a 20,000,000 line csv file that has different row lengths. This is due to archaic data loggers and proprietary formats. We get the end result as a csv file in the following format. MY goal is to insert this file into a postgres database. How Can I do the following:
Keep the first 8 columns and my last 2 columns, to have a consistent CSV file
Add a new column to the csv file ether at the first or last position.
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0 img_id.jpg, -50
A:
Read a row with csv, then:
newrow = row[:8] + row[-2:]
then add your new field and write it out (also with csv).
A:
You can open the file as a textfile and read the lines one at a time. Are there quoted or escaped commas that don't "split fields"? If not, you can do
with open('thebigfile.csv', 'r') as thecsv:
for line in thecsv:
fields = [f.strip() for f in thecsv.split(',')]
consist = fields[:8] + fields[-2:] + ['onemore']
... use the `consist` list as warranted ...
I suspect that where I have + ['onemore'] you may want to "add a column", as you say, with some very different content, but of course I can't guess what it might be.
Don't send each line separately with an insert to the DB -- 20 million inserts would take a long time. Rather, group the "made-consistent" lists, appending them to a temporary list -- each time that list's length hits, say, 1000, use an executemany to add all those entries.
Edit: to clarify, I don't recommend using csv to process a file you know is not in "proper" csv format: processing it directly gives you more direct control (especially as and when you discover other irregularities beyond the varying number of commas per line).
A:
I would recommend using the csv module. Here's some code based off CSV processing that I've done elsewhere
from __future__ import with_statement
import csv
def process( reader, writer):
for line in reader:
data = row[:8] + row[-2:]
writer.write( data )
def main( infilename, outfilename ):
with open( infilename, 'rU' ) as infile:
reader = csv.reader( infile )
with open( outfilename, 'w') as outfile:
writer = csv.writer( outfile )
process( reader, writer )
if __name__ == '__main__':
if len(sys.argv) != 3:
print "syntax: python process.py filename outname"
sys.exit(1)
main( sys.argv[1], sys.argv[2] )
A:
Sorry, you will need to write some code with this one. When you have a huge file like this, it's worth checking all of it to be sure it's consistent with what you expect. If you let the unhappy data into your database, you will never get all of it out.
Remember oddities about CSV: it's a mishmash of a bunch of similar standards with different rules about quoting, escaping, null characters, unicode, empty fields (",,,"),
multi-line inputs, and blank lines. The csv module has 'dialects' and options, and you might find the csv.Sniffer class helpful.
I recommend you:
run a 'tail' command to look at the last few lines.
if it appears well behaved, run the whole file through csv reader to see
it breaks. Make a quick histogram of "fields per line".
Think about "valid" ranges and character types and rigorously check them as
you read. Especially watch for unusual unicode or characters outside of the
printable range.
Seriously consider if you want to keep the extra, odd-ball values in a "rest of the line" text field.
Toss any unexpected lines into an exception file.
Fix up your code to handle the new pattern in exceptions file. Rinse. Repeat.
Finally, run the whole thing again, actually dumping data into the database.
Your development time will be faster from not touching a database until you are completely done. Also, be advised the SQLite is blazingly fast on read only data, so PostGres might not be the best solution.
Your final code will probably look like this, but I can't be sure without knowing your data, especially how 'well behaved' it is:
while not eof
out = []
for chunk in range(1000):
try:
fields = csv.reader.next()
except StopIteration:
break
except:
print str(reader.line_num) + ", 'failed to parse'"
try:
assert len(fields) > 5 and len(fields < 12)
assert int(fields[3]) > 0 and int(fields[3]) < 999999
assert int(fields[4]) >= 1 and int(fields[4] <= 12) # date
assert field[5] == field[5].strip() # no extra whitespace
assert not field[5].strip(printable_chars) # no odd chars
...
except AssertionError:
print str(reader.line_num) + ", 'failed checks'"
new_rec = [reader.line_num] # new first item
new_rec.extend(fields[:8]) # first eight
new_rec.extend(fields[-2:]) # last two
new_rec.append(",".join(field[8:-2])) # and the rest
out.append(new_rec)
if database:
cursor.execute_many("INSERT INTO raw_table VALUES %d,...", out)
Of course, your mileage my vary with this code. It's a first draft of pseduo-code. Expect writing solid code for the input to take most of a day.
|
Python - CSV: Large file with rows of different lengths
|
In short, I have a 20,000,000 line csv file that has different row lengths. This is due to archaic data loggers and proprietary formats. We get the end result as a csv file in the following format. MY goal is to insert this file into a postgres database. How Can I do the following:
Keep the first 8 columns and my last 2 columns, to have a consistent CSV file
Add a new column to the csv file ether at the first or last position.
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0, img_id.jpg, -50
1, 2, 3, 4, 5, 0,0,0,0,0,0,0,0,0,0,0 img_id.jpg, -50
|
[
"Read a row with csv, then:\nnewrow = row[:8] + row[-2:]\n\nthen add your new field and write it out (also with csv).\n",
"You can open the file as a textfile and read the lines one at a time. Are there quoted or escaped commas that don't \"split fields\"? If not, you can do\nwith open('thebigfile.csv', 'r') as thecsv:\n for line in thecsv:\n fields = [f.strip() for f in thecsv.split(',')]\n consist = fields[:8] + fields[-2:] + ['onemore']\n ... use the `consist` list as warranted ...\n\nI suspect that where I have + ['onemore'] you may want to \"add a column\", as you say, with some very different content, but of course I can't guess what it might be.\nDon't send each line separately with an insert to the DB -- 20 million inserts would take a long time. Rather, group the \"made-consistent\" lists, appending them to a temporary list -- each time that list's length hits, say, 1000, use an executemany to add all those entries.\nEdit: to clarify, I don't recommend using csv to process a file you know is not in \"proper\" csv format: processing it directly gives you more direct control (especially as and when you discover other irregularities beyond the varying number of commas per line).\n",
"I would recommend using the csv module. Here's some code based off CSV processing that I've done elsewhere\nfrom __future__ import with_statement\nimport csv\n\ndef process( reader, writer):\n for line in reader:\n data = row[:8] + row[-2:]\n writer.write( data )\n\ndef main( infilename, outfilename ):\n with open( infilename, 'rU' ) as infile:\n reader = csv.reader( infile )\n with open( outfilename, 'w') as outfile:\n writer = csv.writer( outfile )\n process( reader, writer )\n\nif __name__ == '__main__':\n if len(sys.argv) != 3:\n print \"syntax: python process.py filename outname\"\n sys.exit(1)\n main( sys.argv[1], sys.argv[2] )\n\n",
"Sorry, you will need to write some code with this one. When you have a huge file like this, it's worth checking all of it to be sure it's consistent with what you expect. If you let the unhappy data into your database, you will never get all of it out.\nRemember oddities about CSV: it's a mishmash of a bunch of similar standards with different rules about quoting, escaping, null characters, unicode, empty fields (\",,,\"), \nmulti-line inputs, and blank lines. The csv module has 'dialects' and options, and you might find the csv.Sniffer class helpful.\nI recommend you:\n\nrun a 'tail' command to look at the last few lines.\nif it appears well behaved, run the whole file through csv reader to see\nit breaks. Make a quick histogram of \"fields per line\".\nThink about \"valid\" ranges and character types and rigorously check them as\nyou read. Especially watch for unusual unicode or characters outside of the\nprintable range.\nSeriously consider if you want to keep the extra, odd-ball values in a \"rest of the line\" text field.\nToss any unexpected lines into an exception file. \nFix up your code to handle the new pattern in exceptions file. Rinse. Repeat.\nFinally, run the whole thing again, actually dumping data into the database.\n\nYour development time will be faster from not touching a database until you are completely done. Also, be advised the SQLite is blazingly fast on read only data, so PostGres might not be the best solution.\nYour final code will probably look like this, but I can't be sure without knowing your data, especially how 'well behaved' it is:\nwhile not eof\n out = []\n for chunk in range(1000):\n try:\n fields = csv.reader.next()\n except StopIteration:\n break\n except:\n print str(reader.line_num) + \", 'failed to parse'\"\n try:\n assert len(fields) > 5 and len(fields < 12)\n assert int(fields[3]) > 0 and int(fields[3]) < 999999\n assert int(fields[4]) >= 1 and int(fields[4] <= 12) # date\n assert field[5] == field[5].strip() # no extra whitespace\n assert not field[5].strip(printable_chars) # no odd chars\n ...\n except AssertionError:\n print str(reader.line_num) + \", 'failed checks'\"\n new_rec = [reader.line_num] # new first item\n new_rec.extend(fields[:8]) # first eight\n new_rec.extend(fields[-2:]) # last two\n new_rec.append(\",\".join(field[8:-2])) # and the rest\n out.append(new_rec)\n if database:\n cursor.execute_many(\"INSERT INTO raw_table VALUES %d,...\", out)\n\nOf course, your mileage my vary with this code. It's a first draft of pseduo-code. Expect writing solid code for the input to take most of a day.\n"
] |
[
8,
2,
1,
1
] |
[] |
[] |
[
"csv",
"etl",
"parsing",
"python"
] |
stackoverflow_0002549746_csv_etl_parsing_python.txt
|
Q:
How to list directory hierarchy in GtkTreeView widget?
I am trying to generate a hierarchical directory listing in pyGTK.
Currently, I have this following directory tree:
/root
folderA
- subdirA
- subA.py
- a.py
folderB
- b.py
I have written a function that -almost- seem to work:
def go(root, piter=None):
for filename in os.listdir(root):
isdir = os.path.isdir(os.path.join(root, filename))
piter = self.treestore.append(piter, [filename])
if isdir == True:
go(os.path.join(root, filename), piter)
This is what i get when i run the app:
I also think my function is inefficient and that i should be using os.walk(), since it already exists for such purpose.
How can I, and what is the proper/most efficient way of generating a directory tree with pyGTK?
---edit----
the block of code i ended up using, that works, is:
parents = {}
for dir, dirs, files in os.walk(root):
for subdir in dirs:
parents[os.path.join(dir, subdir)] = self.treestore.append(parents.get(dir, None), [subdir])
for item in files:
self.treestore.append(parents.get(dir, None), [item])
A:
About the performance, this is a FAQ.
About your algorithm: when you reach subdirA piter points to subdirA, at the next iteration when you reach a.py piter still points to subdirA.
As you said, use os.walk.
|
How to list directory hierarchy in GtkTreeView widget?
|
I am trying to generate a hierarchical directory listing in pyGTK.
Currently, I have this following directory tree:
/root
folderA
- subdirA
- subA.py
- a.py
folderB
- b.py
I have written a function that -almost- seem to work:
def go(root, piter=None):
for filename in os.listdir(root):
isdir = os.path.isdir(os.path.join(root, filename))
piter = self.treestore.append(piter, [filename])
if isdir == True:
go(os.path.join(root, filename), piter)
This is what i get when i run the app:
I also think my function is inefficient and that i should be using os.walk(), since it already exists for such purpose.
How can I, and what is the proper/most efficient way of generating a directory tree with pyGTK?
---edit----
the block of code i ended up using, that works, is:
parents = {}
for dir, dirs, files in os.walk(root):
for subdir in dirs:
parents[os.path.join(dir, subdir)] = self.treestore.append(parents.get(dir, None), [subdir])
for item in files:
self.treestore.append(parents.get(dir, None), [item])
|
[
"About the performance, this is a FAQ.\nAbout your algorithm: when you reach subdirA piter points to subdirA, at the next iteration when you reach a.py piter still points to subdirA.\nAs you said, use os.walk.\n"
] |
[
1
] |
[] |
[] |
[
"gtktreeview",
"pygtk",
"python"
] |
stackoverflow_0002551147_gtktreeview_pygtk_python.txt
|
Q:
How to extend/patch an existing module or package?
I want to extend some locale-specific features of a python application named OpenERP. All I need is implementing a third party module.function that would be called every time OpenERP calls locale.setlocale() function without changing neither OpenERP nor locale module source code.
The only way I can imagine is provide a module named locale.py inside main application package dir, but It seems that is an unpythonic workaround.
A:
Look up Monkey Patching. It's not most elegant technique, but sometimes it's the only option.
In your case you can substitute your own function for locale.setlocale() which will do whatever you want. It would look something like that:
import locale
original_setlocale = locale.setlocale
def my_setlocale(category, locale=None):
# Do anything you want
# optionally call original function
original_setlocale(category, locale)
|
How to extend/patch an existing module or package?
|
I want to extend some locale-specific features of a python application named OpenERP. All I need is implementing a third party module.function that would be called every time OpenERP calls locale.setlocale() function without changing neither OpenERP nor locale module source code.
The only way I can imagine is provide a module named locale.py inside main application package dir, but It seems that is an unpythonic workaround.
|
[
"Look up Monkey Patching. It's not most elegant technique, but sometimes it's the only option.\nIn your case you can substitute your own function for locale.setlocale() which will do whatever you want. It would look something like that:\nimport locale\n\noriginal_setlocale = locale.setlocale\n\ndef my_setlocale(category, locale=None):\n # Do anything you want\n # optionally call original function\n original_setlocale(category, locale)\n\n"
] |
[
2
] |
[] |
[] |
[
"extend",
"locale",
"python"
] |
stackoverflow_0002551972_extend_locale_python.txt
|
Q:
Hyphenate a random string to an exact format
I am creating a random ID using the below code:
from random import *
import string
# The characters to make up the random password
chars = string.ascii_letters + string.digits
def random_password():
return "".join(choice(chars) for x in range(32))
This will output something like:
60ff612332b741508bc4432e34ec1d3e
I would like the format to be in this format:
60ff6123-32b7-4150-8bc4-432e34ec1d3e
I was looking at the .split() method but can't see how to do this with a random id, also the hyphen's must be at these places so splitting them by a certain amount of digits is out. I'm asking is there a way to split these random id's by 8 number's then 4 etc.
Thanks
A:
The uuid module can be used for generating UUIDs.
A:
What's wrong with generating every part separately? Like that:
def random_password():
return "-".join(["".join(choice(chars) for x in range(n))
for n in (8, 4, 4, 4, 8)])
A:
how about simple concat?
>>> s="60ff612332b741508bc4432e34ec1d3e"
>>> s[:8]+"-"+s[8:12]+"-"+s[12:16]+"-"+s[16:20]+"-"+s[20:]
'60ff6123-32b7-4150-8bc4-432e34ec1d3e'
A:
pos = set([8, 12, 16])
print "".join(map(lambda x: (x[1], "%s-" % x[1])[x[0] in pos], list(enumerate(random_password()))))
|
Hyphenate a random string to an exact format
|
I am creating a random ID using the below code:
from random import *
import string
# The characters to make up the random password
chars = string.ascii_letters + string.digits
def random_password():
return "".join(choice(chars) for x in range(32))
This will output something like:
60ff612332b741508bc4432e34ec1d3e
I would like the format to be in this format:
60ff6123-32b7-4150-8bc4-432e34ec1d3e
I was looking at the .split() method but can't see how to do this with a random id, also the hyphen's must be at these places so splitting them by a certain amount of digits is out. I'm asking is there a way to split these random id's by 8 number's then 4 etc.
Thanks
|
[
"The uuid module can be used for generating UUIDs.\n",
"What's wrong with generating every part separately? Like that:\ndef random_password():\n return \"-\".join([\"\".join(choice(chars) for x in range(n)) \n for n in (8, 4, 4, 4, 8)])\n\n",
"how about simple concat?\n>>> s=\"60ff612332b741508bc4432e34ec1d3e\"\n>>> s[:8]+\"-\"+s[8:12]+\"-\"+s[12:16]+\"-\"+s[16:20]+\"-\"+s[20:]\n'60ff6123-32b7-4150-8bc4-432e34ec1d3e'\n\n",
"pos = set([8, 12, 16])\nprint \"\".join(map(lambda x: (x[1], \"%s-\" % x[1])[x[0] in pos], list(enumerate(random_password()))))\n\n"
] |
[
4,
3,
2,
1
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002552027_python_string.txt
|
Q:
How do I do this Database Model in Django?
Django currently does not support the "Point" datatype in MySQL. That's why I created my own.
class PointField(models.Field):
def db_type(self):
return 'Point'
class Tag(models.Model):
user = models.ForeignKey(User)
utm = PointField()
As you can see, this works, and syncdb creates the model fine.
However, my current code calculates a length between two Points using raw SQL.
cursor.execute("SELECT user_id FROM life_tag WHERE\
(GLength(LineStringFromWKB(LineString(asbinary(utm), asbinary(PointFromWKB(point(%s, %s)))))) < 55)...
This says: Select where the length between the given point and the table point is less than 55.
How can I do this with Django instead of RAW SQL? I don't want to do cursors and SELECT statements anymore. How can I modify the models.py in order to do this?
A:
Your question is a bit unclear - are you just asking how to calculate the distance between 2 points? Or are you hoping the ORM will give you some functionality to do it?
If the latter, then that's not going to happen without some external assistance; geometry and geography are beyond the remit of most typical database mapping systems. You can always use the automatic mappings to retrieve the properties you're interested in and compare them manually using Pythagoras or whatever; no SQL there.
Regarding the 'external assistance' I mentioned, you could look at GeoDjango which might be of some use to you. (There is also GeoAlchemy for people with similar problems but not using Django for the ORM.)
|
How do I do this Database Model in Django?
|
Django currently does not support the "Point" datatype in MySQL. That's why I created my own.
class PointField(models.Field):
def db_type(self):
return 'Point'
class Tag(models.Model):
user = models.ForeignKey(User)
utm = PointField()
As you can see, this works, and syncdb creates the model fine.
However, my current code calculates a length between two Points using raw SQL.
cursor.execute("SELECT user_id FROM life_tag WHERE\
(GLength(LineStringFromWKB(LineString(asbinary(utm), asbinary(PointFromWKB(point(%s, %s)))))) < 55)...
This says: Select where the length between the given point and the table point is less than 55.
How can I do this with Django instead of RAW SQL? I don't want to do cursors and SELECT statements anymore. How can I modify the models.py in order to do this?
|
[
"Your question is a bit unclear - are you just asking how to calculate the distance between 2 points? Or are you hoping the ORM will give you some functionality to do it?\nIf the latter, then that's not going to happen without some external assistance; geometry and geography are beyond the remit of most typical database mapping systems. You can always use the automatic mappings to retrieve the properties you're interested in and compare them manually using Pythagoras or whatever; no SQL there.\nRegarding the 'external assistance' I mentioned, you could look at GeoDjango which might be of some use to you. (There is also GeoAlchemy for people with similar problems but not using Django for the ORM.)\n"
] |
[
0
] |
[] |
[] |
[
"database",
"django",
"mysql",
"python"
] |
stackoverflow_0002549616_database_django_mysql_python.txt
|
Q:
How do you invoke a python script inside a jar file using python?
I'm working on an application that intersperses a bunch of jython and java code. Due to the nature of the program (using wsadmin) we are really restricted to Python 2.1
We currently have a jar containing both java source and .py modules. The code is currently invoked using java, but I'd like to remove this in favor of migrating as much functionality as possible to jython.
The problem I have is that I want to either import or execute python modules inside the existing jar file from a calling jython script. I've tried a couple of different ways without success.
My directory structure looks like:
application.jar
|-- com
|--example
|-- action
|-- MyAction.class
|-- pre_myAction.py
The 1st approach I tried was to do imports from the jar. I added the jar to my sys.path and tried to import the module using both import com.example.action.myAction and import myAction. No success however, even when I put init.py files into the directory at each level.
The 2nd approach I tried was to load the resource using the java class. So I wrote the below code:
import sys
import os
import com.example.action.MyAction as MyAction
scriptName = str(MyAction.getResource('/com/example/action/myAction.py'))
scriptStr = MyAction.getResourceAsStream('/com/example/action/myAction.py')
try:
print execfile(scriptStr)
except:
print "failed 1"
try:
print execfile(scriptName)
except:
print "failed 2"
Both of these failed. I'm at a bit of a loss now as to how I should proceed. Any ideas ?
cheers,
Trevor
A:
the following works for me :
import sys
import os
import java.lang.ClassLoader
import java.io.InputStreamReader
import java.io.BufferedReader
loader = java.lang.ClassLoader.getSystemClassLoader()
stream = loader.getResourceAsStream("com/example/action/myAction.py")
reader = java.io.BufferedReader(java.io.InputStreamReader(stream))
script = ""
line = reader.readLine()
while (line != None) :
script += line + "\n"
line = reader.readLine()
exec(script)
Loading the Script from the ClassPath as a String in 'script'
exec the script with exec
|
How do you invoke a python script inside a jar file using python?
|
I'm working on an application that intersperses a bunch of jython and java code. Due to the nature of the program (using wsadmin) we are really restricted to Python 2.1
We currently have a jar containing both java source and .py modules. The code is currently invoked using java, but I'd like to remove this in favor of migrating as much functionality as possible to jython.
The problem I have is that I want to either import or execute python modules inside the existing jar file from a calling jython script. I've tried a couple of different ways without success.
My directory structure looks like:
application.jar
|-- com
|--example
|-- action
|-- MyAction.class
|-- pre_myAction.py
The 1st approach I tried was to do imports from the jar. I added the jar to my sys.path and tried to import the module using both import com.example.action.myAction and import myAction. No success however, even when I put init.py files into the directory at each level.
The 2nd approach I tried was to load the resource using the java class. So I wrote the below code:
import sys
import os
import com.example.action.MyAction as MyAction
scriptName = str(MyAction.getResource('/com/example/action/myAction.py'))
scriptStr = MyAction.getResourceAsStream('/com/example/action/myAction.py')
try:
print execfile(scriptStr)
except:
print "failed 1"
try:
print execfile(scriptName)
except:
print "failed 2"
Both of these failed. I'm at a bit of a loss now as to how I should proceed. Any ideas ?
cheers,
Trevor
|
[
"the following works for me :\nimport sys\nimport os\n\nimport java.lang.ClassLoader \nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\nloader = java.lang.ClassLoader.getSystemClassLoader()\nstream = loader.getResourceAsStream(\"com/example/action/myAction.py\")\nreader = java.io.BufferedReader(java.io.InputStreamReader(stream))\n\nscript = \"\" \nline = reader.readLine()\nwhile (line != None) : \n script += line + \"\\n\"\n line = reader.readLine()\n\nexec(script)\n\n\nLoading the Script from the ClassPath as a String in 'script' \nexec the script with exec\n\n"
] |
[
5
] |
[] |
[] |
[
"import",
"jar",
"java",
"jython",
"python"
] |
stackoverflow_0002551269_import_jar_java_jython_python.txt
|
Q:
Losing 'post' requests sent to Pylons paster server
I'm sending post requests to a Pylons server (served by paster serve), and if I send them with any frequency many don't arrive at the server. One at a time is ok, but if I fire off a few (or more) within seconds, only a small number get dealt with. If I send with no post data, or with get, it works fine, but putting just one character of data in the post fields causes massive losses.
For example, sending 200, 2 will come back. Sending 100 more slowly, 10 will come back.
I'm making the requests form inside a Qt application. Tis will work ok (no data):
QString postFields = ""
QNetworkRequest
request(QUrl("http://server.com/endpoint"));
QNetworkReply *reply =
networkAccessManager->post(request,
postFields.toAscii());
And this will result in only a fraction of the requests being dealt with:
QString postFields = ""
QNetworkRequest
request(QUrl("http://server.com/endpoint"));
QNetworkReply *reply =
networkAccessManager->post(request,
postFields.toAscii());
I've played around with turning on use_threadpool, and other options (threadpool_workers, threadpool_max_requests = 300), of which some combinations can alter the results slightly (best case 10 responses in 200).
If I send similar requests to other (non paster) servers, the replies come back ok, so I'm almost certain its'a paster serve config issue.
Any help or advice greatly appreciated.
Thanks
Philip
A:
Thanks for you reply.
Tracked it doen to the fact that paster serve only supports HTTP 1.0, and so wasn't responding to initial requests with a 100 code.
Switched to Apache, all working now!
A:
Could you add logging on paster/pylons side to find where exactly these requests get lost? Are you sure that QT app is working right, may it be limit on the number of concurrent connections in QNetworkRequest? AFAIR QT networking uses separate thread for connection allocated from thread pool. Try adding error handling on QT side.
|
Losing 'post' requests sent to Pylons paster server
|
I'm sending post requests to a Pylons server (served by paster serve), and if I send them with any frequency many don't arrive at the server. One at a time is ok, but if I fire off a few (or more) within seconds, only a small number get dealt with. If I send with no post data, or with get, it works fine, but putting just one character of data in the post fields causes massive losses.
For example, sending 200, 2 will come back. Sending 100 more slowly, 10 will come back.
I'm making the requests form inside a Qt application. Tis will work ok (no data):
QString postFields = ""
QNetworkRequest
request(QUrl("http://server.com/endpoint"));
QNetworkReply *reply =
networkAccessManager->post(request,
postFields.toAscii());
And this will result in only a fraction of the requests being dealt with:
QString postFields = ""
QNetworkRequest
request(QUrl("http://server.com/endpoint"));
QNetworkReply *reply =
networkAccessManager->post(request,
postFields.toAscii());
I've played around with turning on use_threadpool, and other options (threadpool_workers, threadpool_max_requests = 300), of which some combinations can alter the results slightly (best case 10 responses in 200).
If I send similar requests to other (non paster) servers, the replies come back ok, so I'm almost certain its'a paster serve config issue.
Any help or advice greatly appreciated.
Thanks
Philip
|
[
"Thanks for you reply.\nTracked it doen to the fact that paster serve only supports HTTP 1.0, and so wasn't responding to initial requests with a 100 code.\nSwitched to Apache, all working now!\n",
"Could you add logging on paster/pylons side to find where exactly these requests get lost? Are you sure that QT app is working right, may it be limit on the number of concurrent connections in QNetworkRequest? AFAIR QT networking uses separate thread for connection allocated from thread pool. Try adding error handling on QT side.\n"
] |
[
1,
0
] |
[] |
[] |
[
"http",
"paster",
"pylons",
"python",
"qt"
] |
stackoverflow_0002545643_http_paster_pylons_python_qt.txt
|
Q:
Google Apps shared contacts API get a contact for python
I'm having some issues trying to pull a shared contact using the gdata api for python that Google provides. Here is what I have to get the contacts.. but they are not all listed there
feed = gd_client.GetContactsFeed()
for i, entry in enumerate(feed.entry):
print entry.title
I can't figure out how to pull out a single contact so I can edit the contact information..
thanks!
A:
Google API lacks of features here.
You need to query all your contacts and then iter on them like this:
feedquery = gdata.contacts.service.ContactsQuery()
feedquery.query.max_results = 1000
gmlf = gd_client.GetContactsFeed(feedquery.ToUri())
for index,gmc in enumerate(gmlf.entry):
print str(index) +":"+ gmc .title.text
Remember to set query.max_results to your needs because by default is set to 25 contacts max;
this is probably the reason because they are not all listed after your query.
You can't retrieve one specific contact; you need to retrieve all and filter them using their email or title.
|
Google Apps shared contacts API get a contact for python
|
I'm having some issues trying to pull a shared contact using the gdata api for python that Google provides. Here is what I have to get the contacts.. but they are not all listed there
feed = gd_client.GetContactsFeed()
for i, entry in enumerate(feed.entry):
print entry.title
I can't figure out how to pull out a single contact so I can edit the contact information..
thanks!
|
[
"Google API lacks of features here.\nYou need to query all your contacts and then iter on them like this:\nfeedquery = gdata.contacts.service.ContactsQuery()\nfeedquery.query.max_results = 1000\ngmlf = gd_client.GetContactsFeed(feedquery.ToUri())\nfor index,gmc in enumerate(gmlf.entry):\n print str(index) +\":\"+ gmc .title.text\n\nRemember to set query.max_results to your needs because by default is set to 25 contacts max;\nthis is probably the reason because they are not all listed after your query.\nYou can't retrieve one specific contact; you need to retrieve all and filter them using their email or title.\n"
] |
[
4
] |
[] |
[] |
[
"google_api",
"python"
] |
stackoverflow_0002545711_google_api_python.txt
|
Q:
How do I resolve this curl-related error?
please tell me the solution
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-x86_64/egg/pycurl.py", line 7, in <module>
File "build/bdist.linux-x86_64/egg/pycurl.py", line 6, in __bootstrap__
ImportError: libcurl.so.4: cannot open shared object file: No such file or directory
A:
You're trying to invoke the cURL library, but you don't have curl installed (or it's not installed properly). It looks like you're running Linux, so simply install the appropriate package (for instance, sudo apt-get install curl if you're on Ubuntu).
|
How do I resolve this curl-related error?
|
please tell me the solution
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-x86_64/egg/pycurl.py", line 7, in <module>
File "build/bdist.linux-x86_64/egg/pycurl.py", line 6, in __bootstrap__
ImportError: libcurl.so.4: cannot open shared object file: No such file or directory
|
[
"You're trying to invoke the cURL library, but you don't have curl installed (or it's not installed properly). It looks like you're running Linux, so simply install the appropriate package (for instance, sudo apt-get install curl if you're on Ubuntu).\n"
] |
[
3
] |
[] |
[] |
[
"pycurl",
"python"
] |
stackoverflow_0002552865_pycurl_python.txt
|
Q:
Missing multiprocessing module when freezing Python code
I'm using cx_Freeze to freeze my Python code so I can distribute it as executable on Windows systems. It works fine but it's missing a few modules. I use some open-source libraries in my project e.g. BeautifulSoup and Periscope. They use some libraries for backward compatibility which i don't need to include as Python 2.6 has them. The problem is the third import — multiprocessing._multiprocessing. Can anyone tell me what I need to install in order to fix this? The mutiprocessing module seems to come bundled with Python so what's causing this error?
Missing modules:
? cjkcodecs.aliases imported from BeautifulSoup.BeautifulSoup
? iconv_codec imported from BeautifulSoup.BeautifulSoup
? multiprocessing._multiprocessing imported from multiprocessing.forking
? xdg.BaseDirectory imported from periscope.periscope
Any help?
Thanks guys!
A:
There was a similar issue on Google App Engine. See this
I fixed this my putting a _multiprocessing.py file into the multiprocessing module's folder. This file contained the code:
import multiprocessing
This works but it isn't a robust answer.
|
Missing multiprocessing module when freezing Python code
|
I'm using cx_Freeze to freeze my Python code so I can distribute it as executable on Windows systems. It works fine but it's missing a few modules. I use some open-source libraries in my project e.g. BeautifulSoup and Periscope. They use some libraries for backward compatibility which i don't need to include as Python 2.6 has them. The problem is the third import — multiprocessing._multiprocessing. Can anyone tell me what I need to install in order to fix this? The mutiprocessing module seems to come bundled with Python so what's causing this error?
Missing modules:
? cjkcodecs.aliases imported from BeautifulSoup.BeautifulSoup
? iconv_codec imported from BeautifulSoup.BeautifulSoup
? multiprocessing._multiprocessing imported from multiprocessing.forking
? xdg.BaseDirectory imported from periscope.periscope
Any help?
Thanks guys!
|
[
"There was a similar issue on Google App Engine. See this\nI fixed this my putting a _multiprocessing.py file into the multiprocessing module's folder. This file contained the code:\n\nimport multiprocessing\n\nThis works but it isn't a robust answer.\n"
] |
[
1
] |
[] |
[] |
[
"cx_freeze",
"distutils",
"python"
] |
stackoverflow_0002552682_cx_freeze_distutils_python.txt
|
Q:
Django JSON serializable error
With the following code below, There is an error saying
File "/home/user/web_pro/info/views.py", line 184, in headerview,
raise TypeError("%r is not JSON serializable" % (o,))
TypeError: <lastname: jerry> is not JSON serializable
In the models code
header(models.Model):
firstname = models.ForeignKey(Firstname)
lastname = models.ForeignKey(Lastname)
In the views code
headerview(request):
header = header.objects.filter(created_by=my_id).order_by(order_by)[offset:limit]
l_array = []
l_array_obj = []
for obj in header:
l_array_obj = [obj.title, obj.lastname ,obj.firstname ]
l_array.append(l_array_obj)
dictionary_l.update({'Data': l_array}) ;
return HttpResponse(simplejson.dumps(dictionary_l), mimetype='application/javascript')
what is this error and how to resolve this?
thanks..
A:
The quick read is that obj.lastname is a Lastname model not a String. You probably need to say something like:
l_array_obj = [..., obj.lastname.value, .... ]
to get the string value, rather than the Model object.
A:
Have you considered using Django's own serialization functionality?
|
Django JSON serializable error
|
With the following code below, There is an error saying
File "/home/user/web_pro/info/views.py", line 184, in headerview,
raise TypeError("%r is not JSON serializable" % (o,))
TypeError: <lastname: jerry> is not JSON serializable
In the models code
header(models.Model):
firstname = models.ForeignKey(Firstname)
lastname = models.ForeignKey(Lastname)
In the views code
headerview(request):
header = header.objects.filter(created_by=my_id).order_by(order_by)[offset:limit]
l_array = []
l_array_obj = []
for obj in header:
l_array_obj = [obj.title, obj.lastname ,obj.firstname ]
l_array.append(l_array_obj)
dictionary_l.update({'Data': l_array}) ;
return HttpResponse(simplejson.dumps(dictionary_l), mimetype='application/javascript')
what is this error and how to resolve this?
thanks..
|
[
"The quick read is that obj.lastname is a Lastname model not a String. You probably need to say something like:\nl_array_obj = [..., obj.lastname.value, .... ]\n\nto get the string value, rather than the Model object.\n",
"Have you considered using Django's own serialization functionality?\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"django_models",
"django_views",
"python"
] |
stackoverflow_0002552719_django_django_models_django_views_python.txt
|
Q:
Which files to distribute using cx_Freeze?
I'm using cx_freeze to freeze a Python script for distribution to other windows systems. I did everything as instructed and cx_freeze generated a build\exe.win32-2.6 folder in the folder containing my sources. This directory now contains a a bunch of PYD files, a library.zip file, the python DLL file and the main executable. Which of these files would I need to distribute? Any help, guys?
Thanks in advance.
A:
You need all of them.
|
Which files to distribute using cx_Freeze?
|
I'm using cx_freeze to freeze a Python script for distribution to other windows systems. I did everything as instructed and cx_freeze generated a build\exe.win32-2.6 folder in the folder containing my sources. This directory now contains a a bunch of PYD files, a library.zip file, the python DLL file and the main executable. Which of these files would I need to distribute? Any help, guys?
Thanks in advance.
|
[
"You need all of them.\n"
] |
[
10
] |
[] |
[] |
[
"cx_freeze",
"distutils",
"python"
] |
stackoverflow_0002553110_cx_freeze_distutils_python.txt
|
Q:
Get a specific string from a service list using WSDiscovery
I am using the WSDiscovery module for python. I have been able to search for services on my network. I am trying to discover a client and get the XAddress from this. The WSDiscovery module has very little documentation, actually so little the only piece is in the readme file of the module which is a few lines long. I have manged to get this specific code working below:
import WSDiscovery
from WSDiscovery import WSDiscovery
def printService():
wsd = WSDiscovery()
wsd.start()
services = wsd.searchServices()
for service in services:
try:
print service.getEPR() + ":" + str(service.getXAddrs())
print service.getTypes()
except:
print "Error with "+service.getEPR()
wsd.stop()
This get's all services and I can get different XAddresses using:
service.getXAddrs()[0]
But I am looking for one in particular with a specific id. The one of the addresses would come up as:
4yr8343-r48d-3ref-4fsw-5r4tw432:[u'http://10.10.10.10:5321']
Can anyone think of a suggestion to select the address with this id number for example.
Thanks
A:
Looking at sources you could see that
1.
searchServices signature has few parameters:
def searchServices(self, types=None, scopes=None, timeout=3)
and i don't think filtering by types\scopes can be useful, isn't it?
2.
service CLASS has those parameters:
class Service:
def __init__(self, types, scopes, xAddrs, epr, instanceId):
self.__types = types
self.__scopes = scopes
self.__xAddrs = xAddrs
self.__epr = epr
self.__instanceId = instanceId
self.__messageNumber = 0
self.__metadataVersion = 1
For what i see, the only thing you could do is iterate over services retrieved by searchServices and filter by one of the attributes available.
|
Get a specific string from a service list using WSDiscovery
|
I am using the WSDiscovery module for python. I have been able to search for services on my network. I am trying to discover a client and get the XAddress from this. The WSDiscovery module has very little documentation, actually so little the only piece is in the readme file of the module which is a few lines long. I have manged to get this specific code working below:
import WSDiscovery
from WSDiscovery import WSDiscovery
def printService():
wsd = WSDiscovery()
wsd.start()
services = wsd.searchServices()
for service in services:
try:
print service.getEPR() + ":" + str(service.getXAddrs())
print service.getTypes()
except:
print "Error with "+service.getEPR()
wsd.stop()
This get's all services and I can get different XAddresses using:
service.getXAddrs()[0]
But I am looking for one in particular with a specific id. The one of the addresses would come up as:
4yr8343-r48d-3ref-4fsw-5r4tw432:[u'http://10.10.10.10:5321']
Can anyone think of a suggestion to select the address with this id number for example.
Thanks
|
[
"Looking at sources you could see that \n1.\nsearchServices signature has few parameters:\ndef searchServices(self, types=None, scopes=None, timeout=3)\n\nand i don't think filtering by types\\scopes can be useful, isn't it?\n2.\nservice CLASS has those parameters:\nclass Service:\n\ndef __init__(self, types, scopes, xAddrs, epr, instanceId):\n self.__types = types\n self.__scopes = scopes\n self.__xAddrs = xAddrs\n self.__epr = epr\n self.__instanceId = instanceId\n self.__messageNumber = 0\n self.__metadataVersion = 1\n\nFor what i see, the only thing you could do is iterate over services retrieved by searchServices and filter by one of the attributes available.\n"
] |
[
1
] |
[] |
[] |
[
"list",
"python",
"search",
"string",
"ws_discovery"
] |
stackoverflow_0002553582_list_python_search_string_ws_discovery.txt
|
Q:
Unexplained file not found for an existing file
Following is the error that occurs in this part of the code. Although the path is valid, a RuntimeError occurs—strange. What is happening, and how can I get this to work?
for root,dirs,files in os.walk(self.path):
for f in files :
if (f.split('.')[1] == "mb"):
z = utils.executeInMainThreadWithResult(self.contains,(f.split('.')[0]))
if not (isinstance(z,NoneType)):
cmds.symbolButton(self.arSubCategory + f.split('.')[0], image=(z[1].replace("\\","/")), width = 35,height = 70, c = "h.imp_file(" + "\"" + root.replace("\\","/") + "/" + f + "\"" + ")")
def contains(self,imageName):
print 'imageName : ',imageName,'\n'
for root, dirs, files in os.walk(self.path+"images"):
for g in files:
x = re.search(imageName,g)
if not (isinstance(x, NoneType)):
print 'g ',root+"/"+g.replace("\\","/"),'\n'
return (1,(root+"/"+g))
Error:
# z is (1, 'T:/Reference_Library/Reference_work/Char_models/Workfiles/images\\rboxdisk1\\female\\highpoly/granny01_highpoly.jpg')
Error: File not found: T:/Reference_Library/Reference_work/Char_models/Workfiles/images/rboxdisk1/female/highpoly/granny01_highpoly.jpg
Traceback (most recent call last):
File "<maya console>", line 115, in <module>
File "<maya console>", line 65, in showWindowanimLibrary
RuntimeError: File not found: T:/Reference_Library/Reference_work/Char_models/Workfiles/images/rboxdisk1/female/highpoly/granny01_highpoly.jpg
A:
Do you have write permission to all the files in the folder?
|
Unexplained file not found for an existing file
|
Following is the error that occurs in this part of the code. Although the path is valid, a RuntimeError occurs—strange. What is happening, and how can I get this to work?
for root,dirs,files in os.walk(self.path):
for f in files :
if (f.split('.')[1] == "mb"):
z = utils.executeInMainThreadWithResult(self.contains,(f.split('.')[0]))
if not (isinstance(z,NoneType)):
cmds.symbolButton(self.arSubCategory + f.split('.')[0], image=(z[1].replace("\\","/")), width = 35,height = 70, c = "h.imp_file(" + "\"" + root.replace("\\","/") + "/" + f + "\"" + ")")
def contains(self,imageName):
print 'imageName : ',imageName,'\n'
for root, dirs, files in os.walk(self.path+"images"):
for g in files:
x = re.search(imageName,g)
if not (isinstance(x, NoneType)):
print 'g ',root+"/"+g.replace("\\","/"),'\n'
return (1,(root+"/"+g))
Error:
# z is (1, 'T:/Reference_Library/Reference_work/Char_models/Workfiles/images\\rboxdisk1\\female\\highpoly/granny01_highpoly.jpg')
Error: File not found: T:/Reference_Library/Reference_work/Char_models/Workfiles/images/rboxdisk1/female/highpoly/granny01_highpoly.jpg
Traceback (most recent call last):
File "<maya console>", line 115, in <module>
File "<maya console>", line 65, in showWindowanimLibrary
RuntimeError: File not found: T:/Reference_Library/Reference_work/Char_models/Workfiles/images/rboxdisk1/female/highpoly/granny01_highpoly.jpg
|
[
"Do you have write permission to all the files in the folder?\n"
] |
[
0
] |
[] |
[] |
[
"maya",
"python"
] |
stackoverflow_0002553341_maya_python.txt
|
Q:
How Do I code this in python with simplejson
how do i code a python program that return a json element that look like this
{1:{'name':foo,'age':xl}
2:{'name':vee,'age':xx}
....
}
What i meant is that i want return nested dictionaries
What i hoped to accomplish is something like this
var foo = 1.name # to the the value of name in the clientside
I hope all this made sense .English is my second language
thanks in advance
A:
>>> import simplejson as json
# "simplejson" works exactly the same as with "json"
>>> json.dumps({})
'{}'
>>> json.dumps({'asdf':1,'poi':[2,3,4,{'qwer':5}]})
'{"asdf": 1, "poi": [2, 3, 4, {"qwer": 5}]}'
>>>
|
How Do I code this in python with simplejson
|
how do i code a python program that return a json element that look like this
{1:{'name':foo,'age':xl}
2:{'name':vee,'age':xx}
....
}
What i meant is that i want return nested dictionaries
What i hoped to accomplish is something like this
var foo = 1.name # to the the value of name in the clientside
I hope all this made sense .English is my second language
thanks in advance
|
[
">>> import simplejson as json \n # \"simplejson\" works exactly the same as with \"json\"\n>>> json.dumps({})\n'{}'\n>>> json.dumps({'asdf':1,'poi':[2,3,4,{'qwer':5}]})\n'{\"asdf\": 1, \"poi\": [2, 3, 4, {\"qwer\": 5}]}'\n>>> \n\n"
] |
[
3
] |
[] |
[] |
[
"json",
"python"
] |
stackoverflow_0002553954_json_python.txt
|
Q:
Copy whole SQL Server database into JSON from Python
I facing an atypical conversion problem. About a decade ago I coded up a large site in ASP. Over the years this turned into ASP.NET but kept the same database.
I've just re-done the site in Django and I've copied all the core data but before I cancel my account with the host, I need to make sure I've got a long-term backup of the data so if it turns out I'm missing something, I can copy it from a local copy.
To complicate matters, I no longer have Windows. I moved to Ubuntu on all my machines some time back. I could ask the host to send me a backup but having no access to a machine with MSSQL, I wouldn't be able to use that if I needed to.
So I'm looking for something that does:
db = {}
for table in database:
db[table.name] = [row for row in table]
And then I could serialize db off somewhere for later consumption... But how do I do the table iteration? Is there an easier way to do all of this? Can MSSQL do a cross-platform SQLDump (inc data)?
For previous MSSQL I've used pymssql but I don't know how to iterate the tables and copy rows (ideally with column headers so I can tell what the data is). I'm not looking for much code but I need a poke in the right direction.
A:
Have a look at the sysobjects and syscolumns tables. Also try:
SELECT * FROM sysobjects WHERE name LIKE 'sys%'
to find any other metatables of interest. See here for more info on these tables and the newer SQL2005 counterparts.
A:
I've liked the ADOdb python module when I've needed to connect to sql server from python. Here is a link to a simple tutorial/example: http://phplens.com/lens/adodb/adodb-py-docs.htm#tutorial
A:
I know you said JSON, but it's very simple to generate a SQL script to do an entire dump in XML:
SELECT REPLACE(REPLACE('SELECT * FROM {TABLE_SCHEMA}.{TABLE_NAME} FOR XML RAW', '{TABLE_SCHEMA}',
QUOTENAME(TABLE_SCHEMA)), '{TABLE_NAME}', QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
ORDER BY TABLE_SCHEMA
,TABLE_NAME
A:
As an aside to your coding approach - I'd say :
set up a virtual machine with an eval on windows
put sql server eval on it
restore your data
check it manually or automatically using the excellent db scripting tools from red-gate to script the data and the schema
if fine then you have (a) a good backup and (b) a scripted output.
|
Copy whole SQL Server database into JSON from Python
|
I facing an atypical conversion problem. About a decade ago I coded up a large site in ASP. Over the years this turned into ASP.NET but kept the same database.
I've just re-done the site in Django and I've copied all the core data but before I cancel my account with the host, I need to make sure I've got a long-term backup of the data so if it turns out I'm missing something, I can copy it from a local copy.
To complicate matters, I no longer have Windows. I moved to Ubuntu on all my machines some time back. I could ask the host to send me a backup but having no access to a machine with MSSQL, I wouldn't be able to use that if I needed to.
So I'm looking for something that does:
db = {}
for table in database:
db[table.name] = [row for row in table]
And then I could serialize db off somewhere for later consumption... But how do I do the table iteration? Is there an easier way to do all of this? Can MSSQL do a cross-platform SQLDump (inc data)?
For previous MSSQL I've used pymssql but I don't know how to iterate the tables and copy rows (ideally with column headers so I can tell what the data is). I'm not looking for much code but I need a poke in the right direction.
|
[
"Have a look at the sysobjects and syscolumns tables. Also try:\nSELECT * FROM sysobjects WHERE name LIKE 'sys%'\n\nto find any other metatables of interest. See here for more info on these tables and the newer SQL2005 counterparts.\n",
"I've liked the ADOdb python module when I've needed to connect to sql server from python. Here is a link to a simple tutorial/example: http://phplens.com/lens/adodb/adodb-py-docs.htm#tutorial\n",
"I know you said JSON, but it's very simple to generate a SQL script to do an entire dump in XML:\nSELECT REPLACE(REPLACE('SELECT * FROM {TABLE_SCHEMA}.{TABLE_NAME} FOR XML RAW', '{TABLE_SCHEMA}',\n QUOTENAME(TABLE_SCHEMA)), '{TABLE_NAME}', QUOTENAME(TABLE_NAME))\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_TYPE = 'BASE TABLE'\nORDER BY TABLE_SCHEMA\n ,TABLE_NAME\n\n",
"As an aside to your coding approach - I'd say :\n\nset up a virtual machine with an eval on windows\nput sql server eval on it\nrestore your data\ncheck it manually or automatically using the excellent db scripting tools from red-gate to script the data and the schema\nif fine then you have (a) a good backup and (b) a scripted output.\n\n"
] |
[
1,
1,
1,
0
] |
[] |
[] |
[
"pymssql",
"python",
"sql_server"
] |
stackoverflow_0002552629_pymssql_python_sql_server.txt
|
Q:
Exponential distribution in Python
What's the easiest way to draw a random number from an exponential distribution in Python?
A:
random.expovariate of course.
A:
You can use the random module. For more information, consult its documentation.
|
Exponential distribution in Python
|
What's the easiest way to draw a random number from an exponential distribution in Python?
|
[
"random.expovariate of course.\n",
"You can use the random module. For more information, consult its documentation.\n"
] |
[
18,
0
] |
[] |
[] |
[
"exponential_distribution",
"python"
] |
stackoverflow_0002553994_exponential_distribution_python.txt
|
Q:
Django: Getting a Python encoding error when handling HTTP response in Latin1?
I'm working in Django, and using urllib2 and simplejson to parse some information from an API.
The problem is that the API returns information in the Latin-1 encoding, and just once in a while there's a character in there that causes Django to crash horribly with an encoding error. This is my code:
get_person_id_url = "http://www.domain.com/api/get?" + \
"key=KEY&num="+ urllib2.quote(number) + "&always_return=true&output=js"
request = urllib2.Request(get_person_id_url, None, {'Referer': ''})
response = urllib2.urlopen(request)
results = json.load(response)
person_id = results["person_id"]
I know that I can use something like this to turn Latin1 strings into UTF8:
responseString = responseString.decode('latin1').encode('utf-8')
but it seems this only works on strings, so I'm not completely sure how or where to apply it in the above code. What should I decode and where to trap any errors before they occur?
Unfortunately I don't remember what API call to make to return a character that will crash Django - so I can't do much testing before it goes live. I'm hoping StackOverflow can help... Thanks!
A:
Call response.read() to get the data of the response. Then in a try/except do your latin1 decoding and json loading. In general, Django should never crash if you wrap potentially error-causing operations in exception handlers and take care of them appropriately (at least log them somewhere so you can deal with them at some point in the future).
|
Django: Getting a Python encoding error when handling HTTP response in Latin1?
|
I'm working in Django, and using urllib2 and simplejson to parse some information from an API.
The problem is that the API returns information in the Latin-1 encoding, and just once in a while there's a character in there that causes Django to crash horribly with an encoding error. This is my code:
get_person_id_url = "http://www.domain.com/api/get?" + \
"key=KEY&num="+ urllib2.quote(number) + "&always_return=true&output=js"
request = urllib2.Request(get_person_id_url, None, {'Referer': ''})
response = urllib2.urlopen(request)
results = json.load(response)
person_id = results["person_id"]
I know that I can use something like this to turn Latin1 strings into UTF8:
responseString = responseString.decode('latin1').encode('utf-8')
but it seems this only works on strings, so I'm not completely sure how or where to apply it in the above code. What should I decode and where to trap any errors before they occur?
Unfortunately I don't remember what API call to make to return a character that will crash Django - so I can't do much testing before it goes live. I'm hoping StackOverflow can help... Thanks!
|
[
"Call response.read() to get the data of the response. Then in a try/except do your latin1 decoding and json loading. In general, Django should never crash if you wrap potentially error-causing operations in exception handlers and take care of them appropriately (at least log them somewhere so you can deal with them at some point in the future).\n"
] |
[
0
] |
[] |
[] |
[
"character_encoding",
"django",
"encoding",
"python"
] |
stackoverflow_0002553748_character_encoding_django_encoding_python.txt
|
Q:
how to ask user input a string with a timeout embeded in python on windows machine?
want to ask user to input something but not want to wait forever. There is a solution for Linux, Keyboard input with timeout in Python, but I am in windows environment. anybody can help me?
A:
Credit to Alex Martelli
Unfortunately, on Windows,
select.select works only on sockets,
not ordinary files nor the console.
So, if you want to run on Windows, you
need a different approach. On Windows
only, the Python standard library has
a small module named msvcrt, including
functions such as msvcrt.kbhit which
tells you whether any keystroke is
waiting to be read. Here, you might
sys.stdout.write the prompt, then
enter a small loop (including a
time.sleep(0.2) or so) which waits to
see whether the user is pressing any
key -- if so then you can
sys.stdin.readline etc, but if after
your desired timeout is over no key
has been hit, then just return the
empty string from your function.
All of this assumes that if the user
has STARTED typing something then you
want to wait indefinitely (not timeout
in the middle of their entering their
answer!). Otherwise, you have more
work to do, since you must ensure that
the user has hit a Return (which means
you must peek at exactly what's in
sys.stdin, resp. use msvcrt.getch, one
character at a time). Fortunately, the
slightly simpler approach of waiting
indefinitely if the user has started
entering seems to be the preferable
one from a user interface viewpoint --
it lets you deal with unattended
consoles as you desire, yet IF the
user is around at all it gives the
user all the time they want to
COMPLETE their answer.
|
how to ask user input a string with a timeout embeded in python on windows machine?
|
want to ask user to input something but not want to wait forever. There is a solution for Linux, Keyboard input with timeout in Python, but I am in windows environment. anybody can help me?
|
[
"Credit to Alex Martelli\n\nUnfortunately, on Windows,\n select.select works only on sockets,\n not ordinary files nor the console.\n So, if you want to run on Windows, you\n need a different approach. On Windows\n only, the Python standard library has\n a small module named msvcrt, including\n functions such as msvcrt.kbhit which\n tells you whether any keystroke is\n waiting to be read. Here, you might\n sys.stdout.write the prompt, then\n enter a small loop (including a\n time.sleep(0.2) or so) which waits to\n see whether the user is pressing any\n key -- if so then you can\n sys.stdin.readline etc, but if after\n your desired timeout is over no key\n has been hit, then just return the\n empty string from your function.\nAll of this assumes that if the user\n has STARTED typing something then you\n want to wait indefinitely (not timeout\n in the middle of their entering their\n answer!). Otherwise, you have more\n work to do, since you must ensure that\n the user has hit a Return (which means\n you must peek at exactly what's in\n sys.stdin, resp. use msvcrt.getch, one\n character at a time). Fortunately, the\n slightly simpler approach of waiting\n indefinitely if the user has started\n entering seems to be the preferable\n one from a user interface viewpoint --\n it lets you deal with unattended\n consoles as you desire, yet IF the\n user is around at all it gives the\n user all the time they want to\n COMPLETE their answer.\n\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002554187_python.txt
|
Q:
How do I access session data in Jinja2 templates (Bottle framework on app engine)?
I'm running the micro framework Bottle on Google App Engine. I'm using Jinja2 for my templates. And I'm using Beaker to handle the sessions. I'm still a pretty big Python newbie and am pretty stoked I got this far :) My question is how do I access the session data within the templates? I can get the session data no problem within the actual python code. And I could pass the session data each time I call a jinja template. But since I need the session data in the main menu bar of the site... that means I would have to pass it on every single page. Does anyone know if I can access it directly in the templates?
For example I need the session data for my header links:
Home | FAQ | Login
or
Home | FAQ | Logout
Any help is greatly appreciated! :D
A:
You can add things to the Jinja2 environment globals if you want them to be accessible to all templates. See this page for additional information.
Update:
A simple example is, for your setup code:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
Then, in your request handling code:
env.globals['session'] = session # Your session
# Your template can contain things like {{ session['key'] }}
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')
#return response using rendered data
|
How do I access session data in Jinja2 templates (Bottle framework on app engine)?
|
I'm running the micro framework Bottle on Google App Engine. I'm using Jinja2 for my templates. And I'm using Beaker to handle the sessions. I'm still a pretty big Python newbie and am pretty stoked I got this far :) My question is how do I access the session data within the templates? I can get the session data no problem within the actual python code. And I could pass the session data each time I call a jinja template. But since I need the session data in the main menu bar of the site... that means I would have to pass it on every single page. Does anyone know if I can access it directly in the templates?
For example I need the session data for my header links:
Home | FAQ | Login
or
Home | FAQ | Logout
Any help is greatly appreciated! :D
|
[
"You can add things to the Jinja2 environment globals if you want them to be accessible to all templates. See this page for additional information.\nUpdate:\nA simple example is, for your setup code:\nfrom jinja2 import Environment, PackageLoader\nenv = Environment(loader=PackageLoader('yourapplication', 'templates'))\n\nThen, in your request handling code:\nenv.globals['session'] = session # Your session\n# Your template can contain things like {{ session['key'] }}\ntemplate = env.get_template('mytemplate.html')\nprint template.render(the='variables', go='here')\n#return response using rendered data\n\n"
] |
[
11
] |
[] |
[] |
[
"beaker",
"google_app_engine",
"jinja2",
"python",
"session"
] |
stackoverflow_0002554174_beaker_google_app_engine_jinja2_python_session.txt
|
Q:
GAE HTTP method support
I get an "unrecognized HTTP method" when trying to do a REPORT request using httplib and gae. Is there a workaround available? An httplib patch for gae? Do you I have to find another host in order to do this natively?
According to the docs, only certain fetch actions are valid: GET, POST, HEAD,
PUT, and DELETE: http://code.google.com/appengine/docs/python/urlfetch/
fetchfunction.html
A:
httplib on App Engine is a wrapper around the urlfetch API, which only supports the GET, POST, PUT, HEAD and DELETE methods. I'm afraid you're out of luck unless the API you're accessing supports some sort of X-HTTP-Method-Override functionality.
|
GAE HTTP method support
|
I get an "unrecognized HTTP method" when trying to do a REPORT request using httplib and gae. Is there a workaround available? An httplib patch for gae? Do you I have to find another host in order to do this natively?
According to the docs, only certain fetch actions are valid: GET, POST, HEAD,
PUT, and DELETE: http://code.google.com/appengine/docs/python/urlfetch/
fetchfunction.html
|
[
"httplib on App Engine is a wrapper around the urlfetch API, which only supports the GET, POST, PUT, HEAD and DELETE methods. I'm afraid you're out of luck unless the API you're accessing supports some sort of X-HTTP-Method-Override functionality.\n"
] |
[
4
] |
[] |
[] |
[
"google_app_engine",
"httpwebrequest",
"python"
] |
stackoverflow_0002553672_google_app_engine_httpwebrequest_python.txt
|
Q:
Python: why does str() on some text from a UTF-8 file give a UnicodeDecodeError?
I'm processing a UTF-8 file in Python, and have used simplejson to load it into a dictionary. However, I'm getting a UnicodeDecodeError when I try to turn one of the dictionary values into a string:
f = open('my_json.json', 'r')
master_dictionary = json.load(f)
#some json wrangling, then it fails on this line...
mysql_string += " ('" + str(v_dict['code'])
Traceback (most recent call last):
File "my_file.py", line 25, in <module>
str(v_dict['code']) + "'), "
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf4' in position 35: ordinal not in range(128)
Why is Python even using ASCII? I thought it used UTF-8 by default, and the input is from a UTF-8 file.
$ file my_json.json
my_json.json: UTF-8 Unicode English text
What is the problem?
A:
Python 2.x uses ASCII by default. Use unicode.encode() if you want to turn a unicode into a str:
v_dict['code'].encode('utf-8')
A:
One way to make this work would be to set the default encoding to UTF-8 explicitly, like:
import sys
sys.setdefaultencoding("utf-8")
This could lead to unintended consequences if you don't want everything to be unicode by default.
A cleaner way could be to use the unicode function rather than str:
mysql_string += " ('" + unicode(v_dict['code'])
or specify the encoding explicitly:
mysql_string += " ('" + unicode(v_dict['code'], "utf-8")
|
Python: why does str() on some text from a UTF-8 file give a UnicodeDecodeError?
|
I'm processing a UTF-8 file in Python, and have used simplejson to load it into a dictionary. However, I'm getting a UnicodeDecodeError when I try to turn one of the dictionary values into a string:
f = open('my_json.json', 'r')
master_dictionary = json.load(f)
#some json wrangling, then it fails on this line...
mysql_string += " ('" + str(v_dict['code'])
Traceback (most recent call last):
File "my_file.py", line 25, in <module>
str(v_dict['code']) + "'), "
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf4' in position 35: ordinal not in range(128)
Why is Python even using ASCII? I thought it used UTF-8 by default, and the input is from a UTF-8 file.
$ file my_json.json
my_json.json: UTF-8 Unicode English text
What is the problem?
|
[
"Python 2.x uses ASCII by default. Use unicode.encode() if you want to turn a unicode into a str:\nv_dict['code'].encode('utf-8')\n\n",
"One way to make this work would be to set the default encoding to UTF-8 explicitly, like:\nimport sys\nsys.setdefaultencoding(\"utf-8\")\n\nThis could lead to unintended consequences if you don't want everything to be unicode by default.\nA cleaner way could be to use the unicode function rather than str:\nmysql_string += \" ('\" + unicode(v_dict['code'])\nor specify the encoding explicitly:\nmysql_string += \" ('\" + unicode(v_dict['code'], \"utf-8\")\n"
] |
[
6,
2
] |
[] |
[] |
[
"character_encoding",
"python"
] |
stackoverflow_0002554545_character_encoding_python.txt
|
Q:
Parsing a file with hierarchical structure in Python
I'm trying to parse the output from a tool into a data structure but I'm having some difficulty getting things right. The file looks like this:
Fruits
Apple
Auxiliary
Core
Extras
Banana
Something
Coconut
Vegetables
Eggplant
Rutabaga
You can see that top-level items are indented by one space, and items beneath that are indented by two spaces for each level. The items are also in alphabetical order.
How do I turn the file into a Python list that's something like ["Fruits", "Fruits/Apple", "Fruits/Banana", ..., "Vegetables", "Vegetables/Eggplant", "Vegetables/Rutabaga"]?
A:
>>> with open("food.txt") as f:
... res = []
... s=[]
... for line in f:
... line=line.rstrip()
... x=len(line)
... line=line.lstrip()
... indent = x-len(line)
... s=s[:indent/2]+[line]
... res.append("/".join(s))
... print res
...
['Fruits', 'Fruits/Apple', 'Fruits/Apple/Auxiliary', 'Fruits/Apple/Core', 'Fruits/Apple/Extras', 'Fruits/Banana', 'Fruits/Banana/Something', 'Fruits/Coconut', 'Vegetables', 'Vegetables/Eggplant', 'Vegetables/Rutabaga']
A:
so you don't want the deepest level right? I don't know if i get you correct, but nevertheless, here's one approach
d=[]
for line in open("file"):
if not line.startswith(" "):
if line.startswith(" "):
d.append(p+"/"+line.strip())
elif line.startswith(" "):
p=line.rstrip()
output
$ ./python.py
[' Fruits/Apple', ' Fruits/Banana', ' Fruits/Coconut', ' Vegetables/Eggplant', ' Vegetables/Rutabaga']
A:
This assumes your input file is 'datafile.txt', you only use whitespaces to indent, you specify your indent_string per level and your level 0 starts without any indent (no whitespace on lowest indent at all). All this contraints can be removed with little effort.
But basic layout should be clear:
import re
indent_string = ' '
pattern = re.compile('(?P<blanks>\s*)(?P<name>.*)')
f = open('datafile.txt')
cache={}
for line in f:
m = pattern.match(line)
d = m.groupdict()
level = len(d['blanks']) / len(indent_string)
cache.update({level: d['name']})
s = ''
for i in xrange(level+1):
s += '/' + cache[i]
print s
A:
You could do something like this:
builder, outlist = [], []
current_spacing = 0
with open('input.txt') as f:
for line in f:
stripped = line.lstrip()
num_spaces = len(line) - len(stripped)
if num_spaces == current_spacing:
builder.pop()
elif num_spaces < current_spacing:
for i in xrange(current_spacing - num_spaces):
builder.pop()
builder.append(stripped)
current_spacing = num_spaces
outlist.append("/".join(builder))
print outlist
|
Parsing a file with hierarchical structure in Python
|
I'm trying to parse the output from a tool into a data structure but I'm having some difficulty getting things right. The file looks like this:
Fruits
Apple
Auxiliary
Core
Extras
Banana
Something
Coconut
Vegetables
Eggplant
Rutabaga
You can see that top-level items are indented by one space, and items beneath that are indented by two spaces for each level. The items are also in alphabetical order.
How do I turn the file into a Python list that's something like ["Fruits", "Fruits/Apple", "Fruits/Banana", ..., "Vegetables", "Vegetables/Eggplant", "Vegetables/Rutabaga"]?
|
[
">>> with open(\"food.txt\") as f:\n... res = []\n... s=[]\n... for line in f:\n... line=line.rstrip()\n... x=len(line)\n... line=line.lstrip()\n... indent = x-len(line)\n... s=s[:indent/2]+[line]\n... res.append(\"/\".join(s))\n... print res\n... \n['Fruits', 'Fruits/Apple', 'Fruits/Apple/Auxiliary', 'Fruits/Apple/Core', 'Fruits/Apple/Extras', 'Fruits/Banana', 'Fruits/Banana/Something', 'Fruits/Coconut', 'Vegetables', 'Vegetables/Eggplant', 'Vegetables/Rutabaga']\n\n",
"so you don't want the deepest level right? I don't know if i get you correct, but nevertheless, here's one approach\nd=[]\nfor line in open(\"file\"):\n if not line.startswith(\" \"):\n if line.startswith(\" \"):\n d.append(p+\"/\"+line.strip())\n elif line.startswith(\" \"):\n p=line.rstrip()\n\noutput\n$ ./python.py\n[' Fruits/Apple', ' Fruits/Banana', ' Fruits/Coconut', ' Vegetables/Eggplant', ' Vegetables/Rutabaga']\n\n",
"This assumes your input file is 'datafile.txt', you only use whitespaces to indent, you specify your indent_string per level and your level 0 starts without any indent (no whitespace on lowest indent at all). All this contraints can be removed with little effort.\nBut basic layout should be clear: \nimport re\n\nindent_string = ' '\npattern = re.compile('(?P<blanks>\\s*)(?P<name>.*)')\n\n\nf = open('datafile.txt')\n\ncache={}\n\nfor line in f:\n m = pattern.match(line)\n d = m.groupdict()\n level = len(d['blanks']) / len(indent_string)\n cache.update({level: d['name']})\n s = ''\n for i in xrange(level+1):\n s += '/' + cache[i]\n print s\n\n",
"You could do something like this:\nbuilder, outlist = [], []\ncurrent_spacing = 0\n\nwith open('input.txt') as f:\n for line in f:\n stripped = line.lstrip()\n num_spaces = len(line) - len(stripped)\n if num_spaces == current_spacing:\n builder.pop()\n elif num_spaces < current_spacing:\n for i in xrange(current_spacing - num_spaces):\n builder.pop()\n builder.append(stripped)\n current_spacing = num_spaces\n outlist.append(\"/\".join(builder))\n\nprint outlist\n\n"
] |
[
4,
1,
0,
0
] |
[] |
[] |
[
"data_structures",
"file_io",
"python"
] |
stackoverflow_0002554474_data_structures_file_io_python.txt
|
Q:
Cheetah with Cherrypy: how to load base templates, and do so automatically on change during development
I am working on a cherrypy+cheetah app and would like to improve the development experience.
I have everything working when I manually compile templates beforehand. (Update: This is how things work for production: precompile, don't ship *.tmpl and load templates as regular python modules.) However, during development I'd rather just load the templates every time they are referenced so that I don't need to kill and restart my application. I have a couple of issues I am facing:
If I have templates inheriting from base templates, I get import errors (can't find base templates). I think I had this actually working during my experiments, but unfortunately didn't save it and now I can't make it work.
Suppose I get 1. working, how do make it so that edits even in base templates get picked up without restart.
Below is my sample application that should demonstrate the problems. The directory structure is as follows:
t.py
templates/
base.tmpl
index.tmpl
t.py:
import sys
import cherrypy
from Cheetah.Template import Template
class T:
def __init__(self, foo):
self.foo = foo
@cherrypy.expose
def index(self):
return Template(file='templates/index.tmpl',
searchList=[{'foo': self.foo}]).respond()
cherrypy.quickstart(T(sys.argv[1]))
base.tmpl:
#def body
This is the body from the base
#end def
This is the base doc
index.tmpl:
#from templates.base import base
#extends base
#def body
$base.body(self)
This is the extended body
#end def
This is from index
Run it like this:
python t.py Something
A:
Try this:
Replace base.tmpl with:
#from Cheetah.Template import Template
#def body
#set $base = Template(file="templates/base.tmpl")
$base.body()
<br/>
This is the extended body
#end def
$body()
<br/>
This is from index
A:
Looks like this question was kind of answered in another SO question. By using the cheetah_import function, I can write my methods like this:
@cherrypy.expose
def index(self):
templates = cheetah_import('templates.index')
t = getattr(getattr(templates, 'index'), 'index')(searchList=[{'foo': self.foo}])
return t.respond()
I will also need to add an __init__.py into the templates directory. This approach also requires that Cherrypy's engine.autoreload_on setting is set to True.
To make production more efficient, I can make cheetah_import = __import__ and not replace the default __builtin__.import.
|
Cheetah with Cherrypy: how to load base templates, and do so automatically on change during development
|
I am working on a cherrypy+cheetah app and would like to improve the development experience.
I have everything working when I manually compile templates beforehand. (Update: This is how things work for production: precompile, don't ship *.tmpl and load templates as regular python modules.) However, during development I'd rather just load the templates every time they are referenced so that I don't need to kill and restart my application. I have a couple of issues I am facing:
If I have templates inheriting from base templates, I get import errors (can't find base templates). I think I had this actually working during my experiments, but unfortunately didn't save it and now I can't make it work.
Suppose I get 1. working, how do make it so that edits even in base templates get picked up without restart.
Below is my sample application that should demonstrate the problems. The directory structure is as follows:
t.py
templates/
base.tmpl
index.tmpl
t.py:
import sys
import cherrypy
from Cheetah.Template import Template
class T:
def __init__(self, foo):
self.foo = foo
@cherrypy.expose
def index(self):
return Template(file='templates/index.tmpl',
searchList=[{'foo': self.foo}]).respond()
cherrypy.quickstart(T(sys.argv[1]))
base.tmpl:
#def body
This is the body from the base
#end def
This is the base doc
index.tmpl:
#from templates.base import base
#extends base
#def body
$base.body(self)
This is the extended body
#end def
This is from index
Run it like this:
python t.py Something
|
[
"Try this: \nReplace base.tmpl with:\n#from Cheetah.Template import Template\n#def body\n #set $base = Template(file=\"templates/base.tmpl\") \n $base.body()\n <br/>\nThis is the extended body\n#end def\n\n$body()\n<br/>\nThis is from index\n\n",
"Looks like this question was kind of answered in another SO question. By using the cheetah_import function, I can write my methods like this:\n@cherrypy.expose\ndef index(self):\n templates = cheetah_import('templates.index')\n t = getattr(getattr(templates, 'index'), 'index')(searchList=[{'foo': self.foo}])\n return t.respond()\n\nI will also need to add an __init__.py into the templates directory. This approach also requires that Cherrypy's engine.autoreload_on setting is set to True.\nTo make production more efficient, I can make cheetah_import = __import__ and not replace the default __builtin__.import.\n"
] |
[
1,
1
] |
[] |
[] |
[
"cheetah",
"cherrypy",
"python",
"template_engine"
] |
stackoverflow_0002550511_cheetah_cherrypy_python_template_engine.txt
|
Q:
Python enumerate built-in error when using the start parameter
I'm modifying some code that calls enumerate on a list declared via a list comprehension e.g.
self.groups = [Groups(self, idx) for idx in range(n_groups)]
then later:
for idx, group in enumerate(self.groups):
# do some stuff
but when I change the enumerate call to start at the 2nd list element via the start parameter e.g.
for idx, group in enumerate(self.groups[1]):
I get an exception:
exceptions.TypeError: 'Group' object is not iterable
Could someone explain why this is?
A:
The problem: Using an indexer with a single argument on a sequence will yield a single object from the sequence. The object picked from your sequence is of type Group, and that type is not iterable.
The solution: Use the slice construct to get a new sequence of items from a specific index:
for idx, group in enumerate(self.groups[1:]):
# do some stuff
A:
you're not starting at the second, you're trying to iterate only over the second. To start at the second item do:
for idx, group in enumerate(self.groups[1:]):
# process
A:
If your sequence is large enough than consider using islice function from itertools module, because it's more memory efficient for large sequences than slicing:
import itertools
for idx, group in enumerate(itertools.islice(self.groups, 1, None)):
# process
|
Python enumerate built-in error when using the start parameter
|
I'm modifying some code that calls enumerate on a list declared via a list comprehension e.g.
self.groups = [Groups(self, idx) for idx in range(n_groups)]
then later:
for idx, group in enumerate(self.groups):
# do some stuff
but when I change the enumerate call to start at the 2nd list element via the start parameter e.g.
for idx, group in enumerate(self.groups[1]):
I get an exception:
exceptions.TypeError: 'Group' object is not iterable
Could someone explain why this is?
|
[
"The problem: Using an indexer with a single argument on a sequence will yield a single object from the sequence. The object picked from your sequence is of type Group, and that type is not iterable.\nThe solution: Use the slice construct to get a new sequence of items from a specific index:\nfor idx, group in enumerate(self.groups[1:]):\n # do some stuff\n\n",
"you're not starting at the second, you're trying to iterate only over the second. To start at the second item do:\nfor idx, group in enumerate(self.groups[1:]):\n # process\n\n",
"If your sequence is large enough than consider using islice function from itertools module, because it's more memory efficient for large sequences than slicing:\nimport itertools\n\nfor idx, group in enumerate(itertools.islice(self.groups, 1, None)):\n # process\n\n"
] |
[
3,
1,
1
] |
[] |
[] |
[
"iterable",
"python"
] |
stackoverflow_0002552287_iterable_python.txt
|
Q:
python mongokit Connection() AssertionError
just installed mongokit and can't figure out why I get AssertionError
python console:
>>> from mongokit import Connection
>>> c = Connection()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/mongokit-0.5.3-py2.6.egg/mongokit/connection.py", line 35, in __init__
super(Connection, self).__init__(*args, **kwargs)
File "build/bdist.linux-i686/egg/pymongo/connection.py", line 169, in __init__
File "build/bdist.linux-i686/egg/pymongo/connection.py", line 338, in __find_master
File "build/bdist.linux-i686/egg/pymongo/connection.py", line 226, in __master
File "build/bdist.linux-i686/egg/pymongo/database.py", line 220, in command
File "build/bdist.linux-i686/egg/pymongo/collection.py", line 356, in find_one
File "build/bdist.linux-i686/egg/pymongo/cursor.py", line 485, in next
File "build/bdist.linux-i686/egg/pymongo/cursor.py", line 461, in _refresh
File "build/bdist.linux-i686/egg/pymongo/cursor.py", line 429, in __send_message
File "build/bdist.linux-i686/egg/pymongo/helpers.py", line 98, in _unpack_response
AssertionError
>>>
mongodb console:
Wed Mar 31 10:27:34 connection accepted from 127.0.0.1:60480 #30
Wed Mar 31 10:27:34 end connection 127.0.0.1:60480
db 1.5
pymongo 1.5 (tested also on 1.4.)
mongokit 0.5.3 (also 0.5.2)
A:
This is a known issue in PyMongo working against devel (>1.4.0) versions of MongoDB. Just released PyMongo 1.5.2 w/ a fix - try upgrading to that.
|
python mongokit Connection() AssertionError
|
just installed mongokit and can't figure out why I get AssertionError
python console:
>>> from mongokit import Connection
>>> c = Connection()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/mongokit-0.5.3-py2.6.egg/mongokit/connection.py", line 35, in __init__
super(Connection, self).__init__(*args, **kwargs)
File "build/bdist.linux-i686/egg/pymongo/connection.py", line 169, in __init__
File "build/bdist.linux-i686/egg/pymongo/connection.py", line 338, in __find_master
File "build/bdist.linux-i686/egg/pymongo/connection.py", line 226, in __master
File "build/bdist.linux-i686/egg/pymongo/database.py", line 220, in command
File "build/bdist.linux-i686/egg/pymongo/collection.py", line 356, in find_one
File "build/bdist.linux-i686/egg/pymongo/cursor.py", line 485, in next
File "build/bdist.linux-i686/egg/pymongo/cursor.py", line 461, in _refresh
File "build/bdist.linux-i686/egg/pymongo/cursor.py", line 429, in __send_message
File "build/bdist.linux-i686/egg/pymongo/helpers.py", line 98, in _unpack_response
AssertionError
>>>
mongodb console:
Wed Mar 31 10:27:34 connection accepted from 127.0.0.1:60480 #30
Wed Mar 31 10:27:34 end connection 127.0.0.1:60480
db 1.5
pymongo 1.5 (tested also on 1.4.)
mongokit 0.5.3 (also 0.5.2)
|
[
"This is a known issue in PyMongo working against devel (>1.4.0) versions of MongoDB. Just released PyMongo 1.5.2 w/ a fix - try upgrading to that.\n"
] |
[
1
] |
[] |
[] |
[
"mongodb",
"pymongo",
"python"
] |
stackoverflow_0002551530_mongodb_pymongo_python.txt
|
Q:
long-index arrays in python
I'm attempting to shorten the memory footprint of 10B sequential integers by referencing them as indexes in a boolean array. In other words, I need to create an array of 10,000,000,000 elements, but that's well into the "Long" range. When I try to reference an array index greater than sys.maxint the array blows up:
x = [False] * 10000000000
Traceback (most recent call last):
File "", line 1, in
x = [0] * 10000000000
OverflowError: cannot fit 'long' into an index-sized integer
Anything I can do? I can't seem to find anyone on the net having this problem... Presumably the answer is "python can't handle arrays bigger than 2B."
A:
With a 32-bit address space, any language is going to be struggling to be able to address such an array. Then there's the problem of how much real memory you have on your computer.
If you want 10B array elements, each element representing either true or false, use an array.array('I', ...) ...
container = array.array('I', [0]) * ((10000000000 + 31) // 32)
Then you can set and clear bits using the usual masking and shifting operations.
Alternative:
If only a small number of elements are true, or only a small number of elements are false, you could use a set for the best memory saving, or a dict for programming convenience.
A:
The bitarray package looks like it might be another useful option.
A:
A dense bit vector is plausible but it won't be optimal unless you know you won't have more than about 10**10 elements, all clustered near each other, with a reasonably randomized distribution. If you have a different distribution, then a different structure will be better.
For instance, if you know that in that range, [0,10**10), only a few members are present, use a set(), or if the reverse is true, with nearly every element present except for a fraction, use a negated set, ie element not in mySet.
If the elements tend to cluster around small ranges, you could use a run length encoding, something like [xrange(0,10),xrange(10,15),xrange(15,100)], which you lookup into by bisecting until you find a matching range, and if the index is even, then the element is in the set. inserts and removals involve shuffling the ranges a bit.
If your distribution really is dense, but you need a little more than what fits in memory (seems to be typical in practice) then you can manage memory by using mmap and wrapping the mapped file with an adaptor that uses a similar mechanism to the suggested array('I') solution already suggested.
To get an idea of just how compressible you can possibly get, try building a plain file with a reasonable corpus of data in packed form and then apply a general compression algorithm (such as gzip) to see how much reduction you see. If there is much reduction, then you can probably use some sort of space optimization in your code as well.
A:
10B booleans (1.25MB of memory, assuming Python is sane)
I think you have your arithmetic wrong -- stored supercompactly, 10B booleans would be 1.25 GIGA, _not__ MEGA, bytes.
A list takes at least 4 bytes per item, so you'd need 40GB to do it the way you want.
You can store an array (see the array module in the standard library) in much less memory than that, so it might possibly fit.
A:
Another option for very large bit arrays would be to use bitstring. It uses a bytearray (or array.array on older Python versions) to store the data but its interface is just an array of bits. For your case you could use:
>>> from bitstring import BitString
>>> s = BitString(10000000000) # zero initialised
>>> s.set([9, 999999999, 253]) # set 3 bits to '1'
>>> s[66] = True # set another bit
>>> s.allset([9, 66]) # check if bits are set to '1'
True
I think it's preferable to doing all the bit masking and shifting yourself!
A:
From googling around some , e.g. PEP 353 (assuming I'm understanding it) and this exchange it looks like the real issue is probably platform/system dependent. Do you have enough memory to handle 10,000,000,000 entries?
|
long-index arrays in python
|
I'm attempting to shorten the memory footprint of 10B sequential integers by referencing them as indexes in a boolean array. In other words, I need to create an array of 10,000,000,000 elements, but that's well into the "Long" range. When I try to reference an array index greater than sys.maxint the array blows up:
x = [False] * 10000000000
Traceback (most recent call last):
File "", line 1, in
x = [0] * 10000000000
OverflowError: cannot fit 'long' into an index-sized integer
Anything I can do? I can't seem to find anyone on the net having this problem... Presumably the answer is "python can't handle arrays bigger than 2B."
|
[
"With a 32-bit address space, any language is going to be struggling to be able to address such an array. Then there's the problem of how much real memory you have on your computer.\nIf you want 10B array elements, each element representing either true or false, use an array.array('I', ...) ...\ncontainer = array.array('I', [0]) * ((10000000000 + 31) // 32)\n\nThen you can set and clear bits using the usual masking and shifting operations.\nAlternative:\nIf only a small number of elements are true, or only a small number of elements are false, you could use a set for the best memory saving, or a dict for programming convenience.\n",
"The bitarray package looks like it might be another useful option.\n",
"A dense bit vector is plausible but it won't be optimal unless you know you won't have more than about 10**10 elements, all clustered near each other, with a reasonably randomized distribution. If you have a different distribution, then a different structure will be better. \nFor instance, if you know that in that range, [0,10**10), only a few members are present, use a set(), or if the reverse is true, with nearly every element present except for a fraction, use a negated set, ie element not in mySet. \nIf the elements tend to cluster around small ranges, you could use a run length encoding, something like [xrange(0,10),xrange(10,15),xrange(15,100)], which you lookup into by bisecting until you find a matching range, and if the index is even, then the element is in the set. inserts and removals involve shuffling the ranges a bit.\nIf your distribution really is dense, but you need a little more than what fits in memory (seems to be typical in practice) then you can manage memory by using mmap and wrapping the mapped file with an adaptor that uses a similar mechanism to the suggested array('I') solution already suggested.\nTo get an idea of just how compressible you can possibly get, try building a plain file with a reasonable corpus of data in packed form and then apply a general compression algorithm (such as gzip) to see how much reduction you see. If there is much reduction, then you can probably use some sort of space optimization in your code as well.\n",
"\n10B booleans (1.25MB of memory, assuming Python is sane)\n\nI think you have your arithmetic wrong -- stored supercompactly, 10B booleans would be 1.25 GIGA, _not__ MEGA, bytes.\nA list takes at least 4 bytes per item, so you'd need 40GB to do it the way you want.\nYou can store an array (see the array module in the standard library) in much less memory than that, so it might possibly fit.\n",
"Another option for very large bit arrays would be to use bitstring. It uses a bytearray (or array.array on older Python versions) to store the data but its interface is just an array of bits. For your case you could use:\n>>> from bitstring import BitString\n>>> s = BitString(10000000000) # zero initialised\n>>> s.set([9, 999999999, 253]) # set 3 bits to '1'\n>>> s[66] = True # set another bit\n>>> s.allset([9, 66]) # check if bits are set to '1'\nTrue\n\nI think it's preferable to doing all the bit masking and shifting yourself!\n",
"From googling around some , e.g. PEP 353 (assuming I'm understanding it) and this exchange it looks like the real issue is probably platform/system dependent. Do you have enough memory to handle 10,000,000,000 entries?\n"
] |
[
5,
4,
3,
2,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001436411_python.txt
|
Q:
python sqlite3 syntax error when copying a row
I'm having trouble copying a row from one table to another using sqlite3 in python (2.6.1 don't ask). I can specify one column, but if I add a second, it gives me an error.
import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
#this works: cursor.execute("insert into table2 (name) select (name) from table1")
cursor.execute("insert into table2 (name, title) select (name, title) from table1") #this doesn't
conn.commit()
cursor.close()
Results in:
sqlite3.OperationalError: near ",": syntax error
What gives? I know the SQLite syntax is right, but sqlite3 won't take it. Forgive me if this has been asked before, commas tend to get filtered out of results, so it's hard to search for.
A:
You shouldn't have the parentheses after select. It should be:
insert into table2 (name, title) select name, title from table1
|
python sqlite3 syntax error when copying a row
|
I'm having trouble copying a row from one table to another using sqlite3 in python (2.6.1 don't ask). I can specify one column, but if I add a second, it gives me an error.
import sqlite3
conn = sqlite3.connect("database.db")
cursor = conn.cursor()
#this works: cursor.execute("insert into table2 (name) select (name) from table1")
cursor.execute("insert into table2 (name, title) select (name, title) from table1") #this doesn't
conn.commit()
cursor.close()
Results in:
sqlite3.OperationalError: near ",": syntax error
What gives? I know the SQLite syntax is right, but sqlite3 won't take it. Forgive me if this has been asked before, commas tend to get filtered out of results, so it's hard to search for.
|
[
"You shouldn't have the parentheses after select. It should be:\ninsert into table2 (name, title) select name, title from table1\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"sqlite"
] |
stackoverflow_0002555302_python_sqlite.txt
|
Q:
custom format specifications in python
in python, how can a custom format-specification be added, to a class ? for example, if i write a matrix class, i would like to
define a '%M' (or some such) which would then dump the entire contents of the matrix...
thanks
A:
Defining the __str__()/__unicode__() and/or __repr__() methods will let you use the existing %s and %r format specifiers as you like.
A:
I don't believe that it's possible to define a new format specifier for print. You might be able to add a method to your class that sets a format that you use, and define the str method of the class to adjust it's output according to how it was set. Then the main print statement would still use a '%s' specifier, and call your custom str.
A:
If you really want to use custom specifiers you cannot do this in way that compatible with the rest of the Python language and standard library. Take advantage of what Python already supplies (%s and %r) and customise it for your needs by overriding __str__() or __repr__()
class Matrix(object):
def __str__(self):
return convert_to_pretty_matrix_string(self)
def __repr__(self):
return convert_to_textual_matrix_format(self)
|
custom format specifications in python
|
in python, how can a custom format-specification be added, to a class ? for example, if i write a matrix class, i would like to
define a '%M' (or some such) which would then dump the entire contents of the matrix...
thanks
|
[
"Defining the __str__()/__unicode__() and/or __repr__() methods will let you use the existing %s and %r format specifiers as you like.\n",
"I don't believe that it's possible to define a new format specifier for print. You might be able to add a method to your class that sets a format that you use, and define the str method of the class to adjust it's output according to how it was set. Then the main print statement would still use a '%s' specifier, and call your custom str.\n",
"If you really want to use custom specifiers you cannot do this in way that compatible with the rest of the Python language and standard library. Take advantage of what Python already supplies (%s and %r) and customise it for your needs by overriding __str__() or __repr__()\nclass Matrix(object):\n def __str__(self):\n return convert_to_pretty_matrix_string(self)\n def __repr__(self):\n return convert_to_textual_matrix_format(self)\n\n"
] |
[
5,
0,
0
] |
[] |
[] |
[
"format",
"python",
"specifications"
] |
stackoverflow_0002554758_format_python_specifications.txt
|
Q:
How can I have my python file show its mercurial tag or revision as the module version?
I'd like to add a --version command line option to my python application that will show the right version depending on the tagged status of the command:
If the file comes from a version whose short hex ID was abcdef01 that was tagged TAG, --version should show this:
MyApp Version TAG (abcdef01)
If the file comes from the tip, --version should show this:
MyApp (tip)
If the file comes from an arbitrary, untagged revision abcdef02, --version should show this:
MyApp (development, abcdef02)
Is this possible? If so, how?
A:
Once you activate the keyword extension, you can have it in a variable which can be carved up for the hash.
A:
Someone pointed out the KeywordExtension, and that's definitely one route to go.
For a little more control you can create an 'update' writes what you want into a version file which you don't add to the repository itself. Something like this in your repo's hgrc:
[hooks]
update = hg id > version.txt
Where version.txt exists in your .hgignore because you don't want to track changes to it. Then you have your version code read that file.
The advantage to using a hook vs. the KeywordExtension is the ability to use more complex tag trolling logic.
In fact the nearest extension might get you pretty much exactly what you want:
The goal of the nearest mercurial
extension is to find the nearest
tag(s) from a given changeset, either
backward or forward in the changesets
history tree.
By default, tags are searched backward
in history, but using the --contains
option will make it search forward. It
answers the following questions:
On which tag this changeset is based
on ? (without --contains) Which tag
will include / contain this changeset
? (with --contains) The tags are
searched by date, so that the nearest
tag in time will be reported. However,
the --all option will make the
extension search the first tag on all
possible branches.
|
How can I have my python file show its mercurial tag or revision as the module version?
|
I'd like to add a --version command line option to my python application that will show the right version depending on the tagged status of the command:
If the file comes from a version whose short hex ID was abcdef01 that was tagged TAG, --version should show this:
MyApp Version TAG (abcdef01)
If the file comes from the tip, --version should show this:
MyApp (tip)
If the file comes from an arbitrary, untagged revision abcdef02, --version should show this:
MyApp (development, abcdef02)
Is this possible? If so, how?
|
[
"Once you activate the keyword extension, you can have it in a variable which can be carved up for the hash.\n",
"Someone pointed out the KeywordExtension, and that's definitely one route to go.\nFor a little more control you can create an 'update' writes what you want into a version file which you don't add to the repository itself. Something like this in your repo's hgrc:\n[hooks]\nupdate = hg id > version.txt\n\nWhere version.txt exists in your .hgignore because you don't want to track changes to it. Then you have your version code read that file.\nThe advantage to using a hook vs. the KeywordExtension is the ability to use more complex tag trolling logic.\nIn fact the nearest extension might get you pretty much exactly what you want:\n\nThe goal of the nearest mercurial\n extension is to find the nearest\n tag(s) from a given changeset, either\n backward or forward in the changesets\n history tree.\nBy default, tags are searched backward\n in history, but using the --contains\n option will make it search forward. It\n answers the following questions:\nOn which tag this changeset is based\n on ? (without --contains) Which tag\n will include / contain this changeset\n ? (with --contains) The tags are\n searched by date, so that the nearest\n tag in time will be reported. However,\n the --all option will make the\n extension search the first tag on all\n possible branches.\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"keyword",
"mercurial",
"python"
] |
stackoverflow_0002554990_keyword_mercurial_python.txt
|
Q:
good __eq__, __lt__, ..., __hash__ methods for image class?
I create the following class:
class Image(object):
def __init__(self, extension, data, urls=None, user_data=None):
self._extension = extension
self._data = data
self._urls = urls
self._user_data = user_data
self._hex_digest = hashlib.sha1(self._data).hexDigest()
Images should be equal when all values are equal. Therefore I wrote:
def __eq__(self, other):
if isinstance(other, Image) and self.__dict__ == other.__dict__:
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.__dict__ < other.__dict__
...
But how should the __hash__ method look like? Equal Images should return equal hashes...
def __hash__(self):
# won't work !?!
return hash(self.__dict__)
Is the way I try to use __eq__, __ne__, __lt__, __hash__, ... recommend?
A:
Do you really need the images to be ordered? If not, I would drop the __lt__ method. For __hash__, remember that two unequal objects can have the same hash value, so you can just pick one of your attributes (or use a tuple of multiple attributes) to derive the hash code. Ex:
def __hash__(self):
return hash(self._hex_digest)
A:
Have you looked the rules for dictionary comparison?
Check here: http://docs.python.org/reference/expressions.html#notin
This is not well-defined (yet). It may be defined in a "What's New" document.
However, small tests seem to indicate that this is workable.
>>> a= { 'a':1, 'b':2 }
>>> b= { 'a':2, 'b':2 }
>>> a == a
True
>>> a == b
False
>>> a < b
True
>>> a > b
False
>>> a >= b
False
|
good __eq__, __lt__, ..., __hash__ methods for image class?
|
I create the following class:
class Image(object):
def __init__(self, extension, data, urls=None, user_data=None):
self._extension = extension
self._data = data
self._urls = urls
self._user_data = user_data
self._hex_digest = hashlib.sha1(self._data).hexDigest()
Images should be equal when all values are equal. Therefore I wrote:
def __eq__(self, other):
if isinstance(other, Image) and self.__dict__ == other.__dict__:
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.__dict__ < other.__dict__
...
But how should the __hash__ method look like? Equal Images should return equal hashes...
def __hash__(self):
# won't work !?!
return hash(self.__dict__)
Is the way I try to use __eq__, __ne__, __lt__, __hash__, ... recommend?
|
[
"Do you really need the images to be ordered? If not, I would drop the __lt__ method. For __hash__, remember that two unequal objects can have the same hash value, so you can just pick one of your attributes (or use a tuple of multiple attributes) to derive the hash code. Ex:\ndef __hash__(self):\n return hash(self._hex_digest)\n\n",
"Have you looked the rules for dictionary comparison? \nCheck here: http://docs.python.org/reference/expressions.html#notin \nThis is not well-defined (yet). It may be defined in a \"What's New\" document.\nHowever, small tests seem to indicate that this is workable.\n>>> a= { 'a':1, 'b':2 }\n>>> b= { 'a':2, 'b':2 }\n>>> a == a\nTrue\n>>> a == b\nFalse\n>>> a < b\nTrue\n>>> a > b\nFalse\n>>> a >= b\nFalse\n\n"
] |
[
5,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002555338_python.txt
|
Q:
Including libraries in project. Best practice
I'm writing a Python open-source app. My app uses some open source Python libraries. These libraries in turn use other open-source libraries.
I intend to release my code at Sourceforge or Google Code but do I need to include the sources of the other libraries? Is this a good practice? ...or should I simply write this information into a README file informing the use about the other required libraries.
I've placed all these libraries into a libs sub folder in my source directory. When checking my code into SVN, should I use something called svn:externals to link to other sources?
Is there a way to dynamically update my libraries to the latest version or is this something I have to do manually when I release a new version.
My sincerest apologies if my question sounds vague but I'm pretty lost in this matter and I don't know what to Google for.
Thanks all.
A:
Use the pip requirements text file.
Just name the packages [and optionally version]
Ask the users to execute the following command in the README. (If you provide an install script, then you should call this within that; In that case you should also use Virtualenv)
pip install -r requirements.txt
and all the libraries you included in the requirements will be installed in that environment.
You can also include svn path, git path, mercurial path, or bzr path in the pip requirements.
Refer to the documentation: http://pip.openplans.org/requirement-format.html
If all your libraries are available from svn, and all your package users install it from the svn, you can also use svn externals; But pip is a lot more cleaner.
A:
As others say, do not include the libraries, state the requirements in documentation. This way your project can use the libraries users already have, sometimes provided by their operating system distribution.
But then, keep in mind those external dependencies, that may exist in different versions or even configurations. Choose a stable branch (not the bleeding edge development snapshots) of the libraries whenever possible. When you really need a specific snapshot of the library, then including it in your package may be a better choice then forcing users to install something non-standard in their systems.
A:
Normally you would just include the libraries in the final released version, but not necessarily include them in the source releases.
A:
I think the most common practice is to inform your user which libraries and version numbers your code uses in something like a README.txt file. You can create a Python Egg package for you code that includes the library dependencies (if they have eggs as well), that can be download with your package upon installation. Use the setuptools package to create python eggs.
A:
In general (for Python): don't ship the source of other libraries which you depend upon in your code.
Just state the required dependencies (complete with minimum required version, installation instructions etc) on a website and in instructions shipped with the source.
|
Including libraries in project. Best practice
|
I'm writing a Python open-source app. My app uses some open source Python libraries. These libraries in turn use other open-source libraries.
I intend to release my code at Sourceforge or Google Code but do I need to include the sources of the other libraries? Is this a good practice? ...or should I simply write this information into a README file informing the use about the other required libraries.
I've placed all these libraries into a libs sub folder in my source directory. When checking my code into SVN, should I use something called svn:externals to link to other sources?
Is there a way to dynamically update my libraries to the latest version or is this something I have to do manually when I release a new version.
My sincerest apologies if my question sounds vague but I'm pretty lost in this matter and I don't know what to Google for.
Thanks all.
|
[
"Use the pip requirements text file.\nJust name the packages [and optionally version]\nAsk the users to execute the following command in the README. (If you provide an install script, then you should call this within that; In that case you should also use Virtualenv)\npip install -r requirements.txt\n\nand all the libraries you included in the requirements will be installed in that environment.\nYou can also include svn path, git path, mercurial path, or bzr path in the pip requirements.\nRefer to the documentation: http://pip.openplans.org/requirement-format.html\nIf all your libraries are available from svn, and all your package users install it from the svn, you can also use svn externals; But pip is a lot more cleaner.\n",
"As others say, do not include the libraries, state the requirements in documentation. This way your project can use the libraries users already have, sometimes provided by their operating system distribution.\nBut then, keep in mind those external dependencies, that may exist in different versions or even configurations. Choose a stable branch (not the bleeding edge development snapshots) of the libraries whenever possible. When you really need a specific snapshot of the library, then including it in your package may be a better choice then forcing users to install something non-standard in their systems. \n",
"Normally you would just include the libraries in the final released version, but not necessarily include them in the source releases.\n",
"I think the most common practice is to inform your user which libraries and version numbers your code uses in something like a README.txt file. You can create a Python Egg package for you code that includes the library dependencies (if they have eggs as well), that can be download with your package upon installation. Use the setuptools package to create python eggs.\n",
"In general (for Python): don't ship the source of other libraries which you depend upon in your code. \nJust state the required dependencies (complete with minimum required version, installation instructions etc) on a website and in instructions shipped with the source.\n"
] |
[
3,
3,
1,
1,
1
] |
[] |
[] |
[
"distribution",
"python"
] |
stackoverflow_0002555393_distribution_python.txt
|
Q:
Web framework for an application utilizing existing database?
A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.
I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Java.
According to many sources it might be challenging to utilize rails effectively with existing database. Also I have not found a way to automatically generate models out of the database.
With Django it's very easy to generate models automatically. However I'd appreciate first hand experience on its suitability to work with legacy DBs. The database in question contains all kinds of primary keys, including lots of composite keys.
Also I appreciate suggestions of other frameworks worth considering.
A:
Use sqlalchemy. On any framework you choose. It can reflect your database as ORM.
A:
I’m currently rebuilding a legacy PHP web application with a MySQL database my self.
The PHP code was kind of spaghetti and is now rewritten in Java as it type safe, promotes well-structured code, has excellent tooling and has superior unit testing capabilities. For database to Java mapping I use Hibernate/JPA.
The web application is incrementally delivered to production. Meaning we run both Java and large parts of the old PHP code together until the application is fully converted.
But in order to use hibernate effectively we needs the database to be logical correct (something MySQL MyIsam does not enforce). So with each production release I run an refactoring scripts for the database (also used to build the development environment and do unit testing) and update the PHP code with a new version that works with the schema changes.
As a web framework I use Stripes as it’s simple, elegant and easy to learn.
A:
I suppose that any PHP Framework (I'm a PHP guy, so I will only talk about PHP) could be OK for you ; but you should use one that's well-supported, has a large community, ...
To make things short, I'm thinking about one off this list :
Symfony
Zend Framework
CakePHP
Kohana
Code Igniter
Now, if you're asking "which framework is the best", it's a question that doesn't really have an answer : it's mainly a matter of personnal preferences...
Still, here's a couple of questions+answers that could bring you some interesting informations :
Best PHP framework for an experienced PHP developer?
What PHP framework would you choose for a new application and why?
To use a PHP framework or not?
PHP Framework Decision - Analysis paralysis!
PHP - MVC framework?
Which PHP Framework is right for this project?
Also, note that choosing a Framework is an important decision -- which means you should take some time to evaluate each framework and how it'll answer your specific need.
Really : you should definitely not rush that decision.
A:
I have very good experience with Django. Every time I needed it was up to the task for interfacing with existing database.
Autogenerated models are the start, as MySQL is not the strictest with its schema. Not that it will not work only that usually some of the db restrictions are held in app itself.
A:
My first thought would be to use Hibernate and Java, but I may be biased because that is what my experience is in. You generally map your Model classes via Hibernate after you create the database anyway, so it might not be a bad choice.
I'll let it explain itself to you: Hibernate's website
A:
You know, there's a whole Ruby web dev world away from Rails, e.g.:
Sinatra
Ramaze
Webby
With such a general question it's always a bit hard to help...
A:
Try web2py, extremely easy to prototype any webapp, and IMO a bit easier to grasp (overall) than other similar web frameworks, HTH
A:
There are no clear cut winners when picking a web framework. Each platform you mentioned has its benefits and drawbacks (cost of hardware, professional support, community support, etc.). Depending on your time table, project requirements, and available hardware resources you are probably going to need some different answers.Personally, I would start your investigation with a platform where you and your team are most experienced.
Like many of the other posters I can only speak to what I'm actively using now, and in my case it is Java. If Java seems to match your projects requirements, you probably want to go with one of the newer frameworks with an active community. Currently Spring Web MVC, Struts2, and Stripes seem to be fairly popular. These frameworks are mostly, if not totally, independent of the persistence layer, but all integrate well with technologies like hibernate and jpa; although you have to do most, if not all, of the wiring yourself.
If you want to take the Java road there are also pre-built application stacks that take care of most of wiring issues for you. For an example you might want to look at Matt Raible's AppFuse. He has built an extensible starter application with many permutations of popular java technologies.
If you are interested in the JVM as a platform, you may also want to look at complete stack solutions like Grails, or tools that help you build your stack quickly like Spring Roo.
Almost all of the full stack solutions I've seen allow for integration with a legacy database schema. As long as your database is well designed, you should be able to map your tables. The mention of composite keys kind of scares me, but depending on your persistence technology this may or may not be an issue. Hibernate in Java/.NET supports mapping to composite keys, as does GORM in grails (built on hibernate). In almost all cases these mappings are discouraged, but people who build persistence frameworks know you can't always scorch earth and completely recreate your model.
|
Web framework for an application utilizing existing database?
|
A legacy web application written using PHP and utilizing MySql database needs to be rewritten completely. However, the existing database structure must not be changed at all.
I'm looking for suggestions on which framework would be most suitable for this task? Language candidates are Python, PHP, Ruby and Java.
According to many sources it might be challenging to utilize rails effectively with existing database. Also I have not found a way to automatically generate models out of the database.
With Django it's very easy to generate models automatically. However I'd appreciate first hand experience on its suitability to work with legacy DBs. The database in question contains all kinds of primary keys, including lots of composite keys.
Also I appreciate suggestions of other frameworks worth considering.
|
[
"Use sqlalchemy. On any framework you choose. It can reflect your database as ORM.\n",
"I’m currently rebuilding a legacy PHP web application with a MySQL database my self. \nThe PHP code was kind of spaghetti and is now rewritten in Java as it type safe, promotes well-structured code, has excellent tooling and has superior unit testing capabilities. For database to Java mapping I use Hibernate/JPA. \nThe web application is incrementally delivered to production. Meaning we run both Java and large parts of the old PHP code together until the application is fully converted.\nBut in order to use hibernate effectively we needs the database to be logical correct (something MySQL MyIsam does not enforce). So with each production release I run an refactoring scripts for the database (also used to build the development environment and do unit testing) and update the PHP code with a new version that works with the schema changes. \nAs a web framework I use Stripes as it’s simple, elegant and easy to learn.\n",
"I suppose that any PHP Framework (I'm a PHP guy, so I will only talk about PHP) could be OK for you ; but you should use one that's well-supported, has a large community, ...\nTo make things short, I'm thinking about one off this list :\n\nSymfony\nZend Framework\nCakePHP\nKohana\nCode Igniter\n\n\nNow, if you're asking \"which framework is the best\", it's a question that doesn't really have an answer : it's mainly a matter of personnal preferences...\nStill, here's a couple of questions+answers that could bring you some interesting informations :\n\nBest PHP framework for an experienced PHP developer?\nWhat PHP framework would you choose for a new application and why?\nTo use a PHP framework or not?\nPHP Framework Decision - Analysis paralysis!\nPHP - MVC framework?\nWhich PHP Framework is right for this project?\n\nAlso, note that choosing a Framework is an important decision -- which means you should take some time to evaluate each framework and how it'll answer your specific need.\nReally : you should definitely not rush that decision.\n",
"I have very good experience with Django. Every time I needed it was up to the task for interfacing with existing database. \nAutogenerated models are the start, as MySQL is not the strictest with its schema. Not that it will not work only that usually some of the db restrictions are held in app itself.\n",
"My first thought would be to use Hibernate and Java, but I may be biased because that is what my experience is in. You generally map your Model classes via Hibernate after you create the database anyway, so it might not be a bad choice.\nI'll let it explain itself to you: Hibernate's website\n",
"You know, there's a whole Ruby web dev world away from Rails, e.g.:\n\nSinatra\nRamaze\nWebby\n\nWith such a general question it's always a bit hard to help...\n",
"Try web2py, extremely easy to prototype any webapp, and IMO a bit easier to grasp (overall) than other similar web frameworks, HTH\n",
"There are no clear cut winners when picking a web framework. Each platform you mentioned has its benefits and drawbacks (cost of hardware, professional support, community support, etc.). Depending on your time table, project requirements, and available hardware resources you are probably going to need some different answers.Personally, I would start your investigation with a platform where you and your team are most experienced. \nLike many of the other posters I can only speak to what I'm actively using now, and in my case it is Java. If Java seems to match your projects requirements, you probably want to go with one of the newer frameworks with an active community. Currently Spring Web MVC, Struts2, and Stripes seem to be fairly popular. These frameworks are mostly, if not totally, independent of the persistence layer, but all integrate well with technologies like hibernate and jpa; although you have to do most, if not all, of the wiring yourself. \nIf you want to take the Java road there are also pre-built application stacks that take care of most of wiring issues for you. For an example you might want to look at Matt Raible's AppFuse. He has built an extensible starter application with many permutations of popular java technologies.\nIf you are interested in the JVM as a platform, you may also want to look at complete stack solutions like Grails, or tools that help you build your stack quickly like Spring Roo. \nAlmost all of the full stack solutions I've seen allow for integration with a legacy database schema. As long as your database is well designed, you should be able to map your tables. The mention of composite keys kind of scares me, but depending on your persistence technology this may or may not be an issue. Hibernate in Java/.NET supports mapping to composite keys, as does GORM in grails (built on hibernate). In almost all cases these mappings are discouraged, but people who build persistence frameworks know you can't always scorch earth and completely recreate your model. \n"
] |
[
5,
3,
2,
2,
2,
0,
0,
0
] |
[] |
[] |
[
"java",
"php",
"python",
"ruby"
] |
stackoverflow_0002507463_java_php_python_ruby.txt
|
Q:
Why does setting this member in C fail?
I'm writing a Python wrapper for a C++ library, and I'm getting a really weird when trying to set a struct's field in C. If I have a struct like this:
struct Thing
{
PyOBJECT_HEAD
unsigned int val;
};
And have two functions like this:
static PyObject* Thing_GetBit(Thing* self, PyObject* args)
{
unsigned int mask;
if(!PyArg_ParseTuple(args, "I", &mask))
Py_RETURN_FALSE;
if((self->val & mask) != 0)
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
static PyObject* Thing_SetBit(Thing* self, PyObject* args)
{
unsigned int mask;
bool on;
if(!PyArg_ParseTuple(args, "Ii", &mask, &on))
Py_RETURN_FALSE;
if(on)
self->val |= mask;
else
self->val &= ~mask;
Py_RETURN_TRUE;
}
Python code that calls the first method works just fine, giving back the value of the struct member. Calls to the SetBit method give an error about an object at address foo accessing memory at address bar, which couldn't be "written".
I've poked around the code, and it's like I can look at the value all I want, both from C and Python, but the instant I try to set it, it blows up in my face. Am I missing something fundamental here?
A:
Is it possible that passing the address of a bool PyArg_ParseTuple is causing your trouble? The "i" format will write an int sized thing.
What kind of machine are you running on?
A:
Shouldn't it be:
if (on)
self->val |= mask;
else
self->val &= ~mask;
|
Why does setting this member in C fail?
|
I'm writing a Python wrapper for a C++ library, and I'm getting a really weird when trying to set a struct's field in C. If I have a struct like this:
struct Thing
{
PyOBJECT_HEAD
unsigned int val;
};
And have two functions like this:
static PyObject* Thing_GetBit(Thing* self, PyObject* args)
{
unsigned int mask;
if(!PyArg_ParseTuple(args, "I", &mask))
Py_RETURN_FALSE;
if((self->val & mask) != 0)
Py_RETURN_TRUE;
Py_RETURN_FALSE;
}
static PyObject* Thing_SetBit(Thing* self, PyObject* args)
{
unsigned int mask;
bool on;
if(!PyArg_ParseTuple(args, "Ii", &mask, &on))
Py_RETURN_FALSE;
if(on)
self->val |= mask;
else
self->val &= ~mask;
Py_RETURN_TRUE;
}
Python code that calls the first method works just fine, giving back the value of the struct member. Calls to the SetBit method give an error about an object at address foo accessing memory at address bar, which couldn't be "written".
I've poked around the code, and it's like I can look at the value all I want, both from C and Python, but the instant I try to set it, it blows up in my face. Am I missing something fundamental here?
|
[
"Is it possible that passing the address of a bool PyArg_ParseTuple is causing your trouble? The \"i\" format will write an int sized thing.\nWhat kind of machine are you running on?\n",
"Shouldn't it be:\nif (on)\n self->val |= mask;\nelse\n self->val &= ~mask;\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"c",
"python"
] |
stackoverflow_0002556172_c_python.txt
|
Q:
python list mysteriously getting set to something within my django/piston handler
Note: (I've updated this since the first two suggestions... you can view the old post in txt form here: http://bennyland.com/old-2554127.txt). The update I made was to better understand what was going wrong - and now I at least sort of know what's happening but I have no clue how to fix it.
Anyway, using Django and Piston, I've set up a new BaseHandler class named BaseApiHandler which does most of the work I was doing across all of my handlers. This worked great until I added the ability to limit the filters being applied to my results (for instance 'give me the first result only').
Examples (had to remove ":" because i can't submit more urls):
- http//localhost/api/hours_detail/empid/22 gives me all hours_detail rows from employee # 22
- http//localhost/api/hours_detail/empid/22/limit/first gives me the first hours_detail row from employee # 22
What's happening is that when I run /limit/first several times in succession, the first example is then broken, pretending it's a /limit/ url when it isn't.
Right now I'm storing whether or not it's a limit and what the limit is in a new class - prior to this stackoverflow edit, I was just using a list with two entries (limit = [] when initialized, limit = [0,1] when set). Prior to this stackoverflow edit, once you spammed /limit/first, when going to the first example 'limit' would be pre-set to [0,1] and the handler would then limit the query because of this. With the debug data I've added, I can say for certain that the list was pre-set and not getting set during the execution of the code.
I'm adding debug info into my response so I can see what's happening. Right now when you first ask for Example 1's url, you get this CORRECT statusmsg response:
"statusmsg": "2 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',}",
When you ask for Example 2's url, you get this CORRECT statusmsg response:
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02','limit','first',with limit[0,1](limit,None... limit set 1 times),}",
However, if you refresh a bunch of times, the limit set value starts increasing (incrementing this value was something a friend of mine suggested to see if this variable was somehow getting kept around)
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02','limit','first',with limit[0,1](limit,None... limit set 10 times),}",
Once that number goes above '1 times', you can start trying to get Example 1's url. Each time I now refresh example 1, i get odd results. Here are 3 different status messages from different refreshes (Notice that from each one, 'limit':'first' is CORRECTLY missing from the kwarg's debug output while the actual value of islimit is hovering between 8 and 10):
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',with limit[0,1](limit,None... limit set 10 times),}",
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',with limit[0,1](limit,None... limit set 8 times),}",
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',with limit[0,1](limit,None... limit set 9 times),}",
So it would appear that this object is getting cached. Prior to changing 'limit' form a list to a class, it also appeared that the list version of 'limit' was getting cached as after going to Example 2's url, i would sometimes have [0,1] as the limit.
Here are the updated snippets of the code (remember, you can view the first post here: bennyland.com/old-2554127.txt)
URLS.PY - inside 'urlpatterns = patterns('
#hours_detail/id/{id}/empid/{empid}/projid/{projid}/datestamp/{datestamp}/daterange/{fromdate}to{todate}
#empid is required
url(r'^api/hours_detail/(?:' + \
r'(?:[/]?id/(?P<id>\d+))?' + \
r'(?:[/]?empid/(?P<empid>\d+))?' + \
r'(?:[/]?projid/(?P<projid>\d+))?' + \
r'(?:[/]?datestamp/(?P<datestamp>\d{4,}[-/\.]\d{2,}[-/\.]\d{2,}))?' + \
r'(?:[/]?daterange/(?P<daterange>(?:\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})(?:to|/-)(?:\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})))?' + \
r')+' + \
r'(?:/limit/(?P<limit>(?:first|last)))?' + \
r'(?:/(?P<exact>exact))?$', hours_detail_resource),
HANDLERS.PY
class ResponseLimit(object):
def __init__(self):
self._min = 0
self._max = 0
self._islimit = 0
@property
def min(self):
if self.islimit == 0:
raise LookupError("trying to access min when no limit has been set")
return self._min
@property
def max(self):
if self.islimit == 0:
raise LookupError("trying to access max when no limit has been set")
return self._max
@property
def islimit(self):
return self._islimit
def setlimit(self, min, max):
self._min = min
self._max = max
# incrementing _islimit instead of using a bool so I can try and see why it's broken
self._islimit += 1
class BaseApiHandler(BaseHandler):
limit = ResponseLimit()
def __init__(self):
self._post_name = 'base'
@property
def post_name(self):
return self._post_name
@post_name.setter
def post_name(self, value):
self._post_name = value
def process_kwarg_read(self, key, value, d_post, b_exact):
"""
this should be overridden in the derived classes to process kwargs
"""
pass
# override 'read' so we can better handle our api's searching capabilities
def read(self, request, *args, **kwargs):
d_post = {'status':0,'statusmsg':'Nothing Happened'}
try:
# setup the named response object
# select all employees then filter - querysets are lazy in django
# the actual query is only done once data is needed, so this may
# seem like some memory hog slow beast, but it's actually not.
d_post[self.post_name] = self.queryset(request)
s_query = ''
b_exact = False
if 'exact' in kwargs and kwargs['exact'] <> None:
b_exact = True
s_query = '\'exact\':True,'
for key,value in kwargs.iteritems():
# the regex url possibilities will push None into the kwargs dictionary
# if not specified, so just continue looping through if that's the case
if value is None or key == 'exact':
continue
# write to the s_query string so we have a nice error message
s_query = '%s\'%s\':\'%s\',' % (s_query, key, value)
# now process this key/value kwarg
self.process_kwarg_read(key=key, value=value, d_post=d_post, b_exact=b_exact)
# end of the kwargs for loop
else:
if self.limit.islimit > 0:
s_query = '%swith limit[%s,%s](limit,%s... limit set %s times),' % (s_query, self.limit.min, self.limit.max, kwargs['limit'],self.limit.islimit)
d_post[self.post_name] = d_post[self.post_name][self.limit.min:self.limit.max]
if d_post[self.post_name].count() == 0:
d_post['status'] = 0
d_post['statusmsg'] = '%s not found with query: {%s}' % (self.post_name, s_query)
else:
d_post['status'] = 1
d_post['statusmsg'] = '%s %s found with query: {%s}' % (d_post[self.post_name].count(), self.post_name, s_query)
except:
e = sys.exc_info()[1]
d_post['status'] = 0
d_post['statusmsg'] = 'error: %s %s' % (e, traceback.format_exc())
d_post[self.post_name] = []
return d_post
class HoursDetailHandler(BaseApiHandler):
#allowed_methods = ('GET', 'PUT', 'POST', 'DELETE',)
model = HoursDetail
exclude = ()
def __init__(self):
BaseApiHandler.__init__(self)
self._post_name = 'hours_detail'
def process_kwarg_read(self, key, value, d_post, b_exact):
# each query is handled slightly differently... when keys are added
# handle them in here. python doesn't have switch statements, this
# could theoretically be performed using a dictionary with lambda
# expressions, however I was affraid it would mess with the way the
# filters on the queryset work so I went for the less exciting
# if/elif block instead
# querying on a specific row
if key == 'id':
d_post[self.post_name] = d_post[self.post_name].filter(pk=value)
# filter based on employee id - this is guaranteed to happen once
# per query (see read(...))
elif key == 'empid':
d_post[self.post_name] = d_post[self.post_name].filter(emp__id__exact=value)
# look for a specific project by id
elif key == 'projid':
d_post[self.post_name] = d_post[self.post_name].filter(proj__id__exact=value)
elif key == 'datestamp' or key == 'daterange':
d_from = None
d_to = None
# first, regex out the times in the case of range vs stamp
if key == 'daterange':
m = re.match('(?P<daterangefrom>\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})(?:to|/-)(?P<daterangeto>\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})', \
value)
d_from = datetime.strptime(m.group('daterangefrom'), '%Y-%m-%d')
d_to = datetime.strptime(m.group('daterangeto'), '%Y-%m-%d')
else:
d_from = datetime.strptime(value, '%Y-%m-%d')
d_to = datetime.strptime(value, '%Y-%m-%d')
# now min/max to get midnight on day1 through just before midnight on day2
# note: this is a hack because as of the writing of this app,
# __date doesn't yet exist as a queryable field thus any
# timestamps not at midnight were incorrectly left out
d_from = datetime.combine(d_from, time.min)
d_to = datetime.combine(d_to, time.max)
d_post[self.post_name] = d_post[self.post_name].filter(clock_time__gte=d_from)
d_post[self.post_name] = d_post[self.post_name].filter(clock_time__lte=d_to)
elif key == 'limit':
order_by = 'clock_time'
if value == 'last':
order_by = '-clock_time'
d_post[self.post_name] = d_post[self.post_name].order_by(order_by)
self.limit.setlimit(0, 1)
else:
raise NameError
def read(self, request, *args, **kwargs):
# empid is required, so make sure it exists before running BaseApiHandler's read method
if not('empid' in kwargs and kwargs['empid'] <> None and kwargs['empid'] >= 0):
return {'status':0,'statusmsg':'empid cannot be empty'}
else:
return BaseApiHandler.read(self, request, *args, **kwargs)
A:
I would say that there is a basic flaw in your code, if has_limit() can return True when limit is a list of length 2, but this line will fail if limit is shorter than 3 elements long:
s_query = '%swith limit[%s,%s](limit,%s > traceback:%s),' %
(s_query, self.limit[0], self.limit[1], kwargs['limit'],
self.limit[2])
Why are you initializing self.limit to an invalid length list? You could also make this code a little more defensive:
if self.has_limit():
s_query += 'with limit[%s,%s]' % self.limit[0:1]
if 'limit' in kwargs and len(self.limit) > 2:
s_query += '(limit,%s > traceback:%s),' %
(kwargs['limit'], self.limit[2])
A:
I think you may be creating an alias to your internal limit list, via the get_limit property accessor. Try removing (or at least adding a print statement) inside this accessor. If you have code externally that binds a local list to get_limit, then it can update the contents using append, del, or assignment to slices, such as [:]. Or try this:
def get_limit(self):
return self._limit[:]
Instead of binding your internal list to an external name, it will make a copy of your internal list.
|
python list mysteriously getting set to something within my django/piston handler
|
Note: (I've updated this since the first two suggestions... you can view the old post in txt form here: http://bennyland.com/old-2554127.txt). The update I made was to better understand what was going wrong - and now I at least sort of know what's happening but I have no clue how to fix it.
Anyway, using Django and Piston, I've set up a new BaseHandler class named BaseApiHandler which does most of the work I was doing across all of my handlers. This worked great until I added the ability to limit the filters being applied to my results (for instance 'give me the first result only').
Examples (had to remove ":" because i can't submit more urls):
- http//localhost/api/hours_detail/empid/22 gives me all hours_detail rows from employee # 22
- http//localhost/api/hours_detail/empid/22/limit/first gives me the first hours_detail row from employee # 22
What's happening is that when I run /limit/first several times in succession, the first example is then broken, pretending it's a /limit/ url when it isn't.
Right now I'm storing whether or not it's a limit and what the limit is in a new class - prior to this stackoverflow edit, I was just using a list with two entries (limit = [] when initialized, limit = [0,1] when set). Prior to this stackoverflow edit, once you spammed /limit/first, when going to the first example 'limit' would be pre-set to [0,1] and the handler would then limit the query because of this. With the debug data I've added, I can say for certain that the list was pre-set and not getting set during the execution of the code.
I'm adding debug info into my response so I can see what's happening. Right now when you first ask for Example 1's url, you get this CORRECT statusmsg response:
"statusmsg": "2 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',}",
When you ask for Example 2's url, you get this CORRECT statusmsg response:
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02','limit','first',with limit[0,1](limit,None... limit set 1 times),}",
However, if you refresh a bunch of times, the limit set value starts increasing (incrementing this value was something a friend of mine suggested to see if this variable was somehow getting kept around)
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02','limit','first',with limit[0,1](limit,None... limit set 10 times),}",
Once that number goes above '1 times', you can start trying to get Example 1's url. Each time I now refresh example 1, i get odd results. Here are 3 different status messages from different refreshes (Notice that from each one, 'limit':'first' is CORRECTLY missing from the kwarg's debug output while the actual value of islimit is hovering between 8 and 10):
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',with limit[0,1](limit,None... limit set 10 times),}",
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',with limit[0,1](limit,None... limit set 8 times),}",
"statusmsg": "1 hours_detail found with query: {'empid':'22','datestamp':'2009-03-02',with limit[0,1](limit,None... limit set 9 times),}",
So it would appear that this object is getting cached. Prior to changing 'limit' form a list to a class, it also appeared that the list version of 'limit' was getting cached as after going to Example 2's url, i would sometimes have [0,1] as the limit.
Here are the updated snippets of the code (remember, you can view the first post here: bennyland.com/old-2554127.txt)
URLS.PY - inside 'urlpatterns = patterns('
#hours_detail/id/{id}/empid/{empid}/projid/{projid}/datestamp/{datestamp}/daterange/{fromdate}to{todate}
#empid is required
url(r'^api/hours_detail/(?:' + \
r'(?:[/]?id/(?P<id>\d+))?' + \
r'(?:[/]?empid/(?P<empid>\d+))?' + \
r'(?:[/]?projid/(?P<projid>\d+))?' + \
r'(?:[/]?datestamp/(?P<datestamp>\d{4,}[-/\.]\d{2,}[-/\.]\d{2,}))?' + \
r'(?:[/]?daterange/(?P<daterange>(?:\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})(?:to|/-)(?:\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})))?' + \
r')+' + \
r'(?:/limit/(?P<limit>(?:first|last)))?' + \
r'(?:/(?P<exact>exact))?$', hours_detail_resource),
HANDLERS.PY
class ResponseLimit(object):
def __init__(self):
self._min = 0
self._max = 0
self._islimit = 0
@property
def min(self):
if self.islimit == 0:
raise LookupError("trying to access min when no limit has been set")
return self._min
@property
def max(self):
if self.islimit == 0:
raise LookupError("trying to access max when no limit has been set")
return self._max
@property
def islimit(self):
return self._islimit
def setlimit(self, min, max):
self._min = min
self._max = max
# incrementing _islimit instead of using a bool so I can try and see why it's broken
self._islimit += 1
class BaseApiHandler(BaseHandler):
limit = ResponseLimit()
def __init__(self):
self._post_name = 'base'
@property
def post_name(self):
return self._post_name
@post_name.setter
def post_name(self, value):
self._post_name = value
def process_kwarg_read(self, key, value, d_post, b_exact):
"""
this should be overridden in the derived classes to process kwargs
"""
pass
# override 'read' so we can better handle our api's searching capabilities
def read(self, request, *args, **kwargs):
d_post = {'status':0,'statusmsg':'Nothing Happened'}
try:
# setup the named response object
# select all employees then filter - querysets are lazy in django
# the actual query is only done once data is needed, so this may
# seem like some memory hog slow beast, but it's actually not.
d_post[self.post_name] = self.queryset(request)
s_query = ''
b_exact = False
if 'exact' in kwargs and kwargs['exact'] <> None:
b_exact = True
s_query = '\'exact\':True,'
for key,value in kwargs.iteritems():
# the regex url possibilities will push None into the kwargs dictionary
# if not specified, so just continue looping through if that's the case
if value is None or key == 'exact':
continue
# write to the s_query string so we have a nice error message
s_query = '%s\'%s\':\'%s\',' % (s_query, key, value)
# now process this key/value kwarg
self.process_kwarg_read(key=key, value=value, d_post=d_post, b_exact=b_exact)
# end of the kwargs for loop
else:
if self.limit.islimit > 0:
s_query = '%swith limit[%s,%s](limit,%s... limit set %s times),' % (s_query, self.limit.min, self.limit.max, kwargs['limit'],self.limit.islimit)
d_post[self.post_name] = d_post[self.post_name][self.limit.min:self.limit.max]
if d_post[self.post_name].count() == 0:
d_post['status'] = 0
d_post['statusmsg'] = '%s not found with query: {%s}' % (self.post_name, s_query)
else:
d_post['status'] = 1
d_post['statusmsg'] = '%s %s found with query: {%s}' % (d_post[self.post_name].count(), self.post_name, s_query)
except:
e = sys.exc_info()[1]
d_post['status'] = 0
d_post['statusmsg'] = 'error: %s %s' % (e, traceback.format_exc())
d_post[self.post_name] = []
return d_post
class HoursDetailHandler(BaseApiHandler):
#allowed_methods = ('GET', 'PUT', 'POST', 'DELETE',)
model = HoursDetail
exclude = ()
def __init__(self):
BaseApiHandler.__init__(self)
self._post_name = 'hours_detail'
def process_kwarg_read(self, key, value, d_post, b_exact):
# each query is handled slightly differently... when keys are added
# handle them in here. python doesn't have switch statements, this
# could theoretically be performed using a dictionary with lambda
# expressions, however I was affraid it would mess with the way the
# filters on the queryset work so I went for the less exciting
# if/elif block instead
# querying on a specific row
if key == 'id':
d_post[self.post_name] = d_post[self.post_name].filter(pk=value)
# filter based on employee id - this is guaranteed to happen once
# per query (see read(...))
elif key == 'empid':
d_post[self.post_name] = d_post[self.post_name].filter(emp__id__exact=value)
# look for a specific project by id
elif key == 'projid':
d_post[self.post_name] = d_post[self.post_name].filter(proj__id__exact=value)
elif key == 'datestamp' or key == 'daterange':
d_from = None
d_to = None
# first, regex out the times in the case of range vs stamp
if key == 'daterange':
m = re.match('(?P<daterangefrom>\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})(?:to|/-)(?P<daterangeto>\d{4,}[-/\.]\d{2,}[-/\.]\d{2,})', \
value)
d_from = datetime.strptime(m.group('daterangefrom'), '%Y-%m-%d')
d_to = datetime.strptime(m.group('daterangeto'), '%Y-%m-%d')
else:
d_from = datetime.strptime(value, '%Y-%m-%d')
d_to = datetime.strptime(value, '%Y-%m-%d')
# now min/max to get midnight on day1 through just before midnight on day2
# note: this is a hack because as of the writing of this app,
# __date doesn't yet exist as a queryable field thus any
# timestamps not at midnight were incorrectly left out
d_from = datetime.combine(d_from, time.min)
d_to = datetime.combine(d_to, time.max)
d_post[self.post_name] = d_post[self.post_name].filter(clock_time__gte=d_from)
d_post[self.post_name] = d_post[self.post_name].filter(clock_time__lte=d_to)
elif key == 'limit':
order_by = 'clock_time'
if value == 'last':
order_by = '-clock_time'
d_post[self.post_name] = d_post[self.post_name].order_by(order_by)
self.limit.setlimit(0, 1)
else:
raise NameError
def read(self, request, *args, **kwargs):
# empid is required, so make sure it exists before running BaseApiHandler's read method
if not('empid' in kwargs and kwargs['empid'] <> None and kwargs['empid'] >= 0):
return {'status':0,'statusmsg':'empid cannot be empty'}
else:
return BaseApiHandler.read(self, request, *args, **kwargs)
|
[
"I would say that there is a basic flaw in your code, if has_limit() can return True when limit is a list of length 2, but this line will fail if limit is shorter than 3 elements long:\ns_query = '%swith limit[%s,%s](limit,%s > traceback:%s),' % \n (s_query, self.limit[0], self.limit[1], kwargs['limit'], \n self.limit[2])\n\nWhy are you initializing self.limit to an invalid length list? You could also make this code a little more defensive:\nif self.has_limit():\n s_query += 'with limit[%s,%s]' % self.limit[0:1]\n if 'limit' in kwargs and len(self.limit) > 2:\n s_query += '(limit,%s > traceback:%s),' % \n (kwargs['limit'], self.limit[2])\n\n",
"I think you may be creating an alias to your internal limit list, via the get_limit property accessor. Try removing (or at least adding a print statement) inside this accessor. If you have code externally that binds a local list to get_limit, then it can update the contents using append, del, or assignment to slices, such as [:]. Or try this:\ndef get_limit(self): \n return self._limit[:]\n\nInstead of binding your internal list to an external name, it will make a copy of your internal list.\n"
] |
[
0,
0
] |
[] |
[] |
[
"django",
"django_piston",
"python"
] |
stackoverflow_0002554127_django_django_piston_python.txt
|
Q:
Right way to create [self]respawning app in python
I am using jabber bot written in python to log some MUC talks. Sometimes it drops on some network or XMPP problems. In this case I have to start it again by myself. The goal is to make it "self-respawning".
I have some variants about how to do it.
Bot is one process. Another process
monitors its activity and starts it
if bot died.
Main process spawns bot
subprocess and controls it.
Also I think daemonizing bot process is useful here.
Platform is Linux, as you could guess.
What is the right way to solve this problem?
A:
If you're using something like ubuntu, try looking into upstart and its automatic daemonization and "respawn" feature. Here's a good general blogpost about running vs. starting processes.
I've also heard good things about supervisdord.
|
Right way to create [self]respawning app in python
|
I am using jabber bot written in python to log some MUC talks. Sometimes it drops on some network or XMPP problems. In this case I have to start it again by myself. The goal is to make it "self-respawning".
I have some variants about how to do it.
Bot is one process. Another process
monitors its activity and starts it
if bot died.
Main process spawns bot
subprocess and controls it.
Also I think daemonizing bot process is useful here.
Platform is Linux, as you could guess.
What is the right way to solve this problem?
|
[
"If you're using something like ubuntu, try looking into upstart and its automatic daemonization and \"respawn\" feature. Here's a good general blogpost about running vs. starting processes. \nI've also heard good things about supervisdord.\n"
] |
[
4
] |
[] |
[] |
[
"daemon",
"python",
"spawn",
"xmpp"
] |
stackoverflow_0002555857_daemon_python_spawn_xmpp.txt
|
Q:
Forwarding keypresses in GTK
I'm writing a bit of code for a Gedit plugin. I'm using Python and the interface (obviously) is GTK.
So, the issue I'm having is quite simple: I have a search box (a gtk.Entry) and right below I have a results box (a gtk.TreeView). Right after you type something in the search box you are presented a bunch of results, and I would like the user to be able to press the Up/Down keys to select one, Enter to choose it, and be done. Thing is, I can't seem to find a way to forward the Up/Down keypress to the TreeView. Currently I have this piece of code:
def __onSearchKeyPress(self, widget, event):
"""
Forward up and down keys to the tree.
"""
if event.keyval in [gtk.keysyms.Up, gtk.keysyms.Down]:
print "pressed up or down"
e = gtk.gdk.Event(gtk.gdk.KEY_PRESS)
e.keyval = event.keyval
e.window = self.browser.window
e.send_event = True
self.browser.emit("key-press-event", e)
return True
I can clearly see I'm receiving the right kind of event, but the event I'm sending gets ignored by the TreeView. Any ideas?
Thanks in advance people.
A:
Not a proper answer to the question (I don't know how to forward key presses), but there's an alternative solution to your problem.
Manipulate the TreeView cursor/selection directly, for example:
path, column = browser.get_cursor()
browser.set_cursor((path[0] + 1,)) # Down
A:
Did you include the key-press-event in the list of events the widget is allowed to receive? You can do that by calling
browser.add_events(gtk.gdk.KEY_PRESS_MASK)
|
Forwarding keypresses in GTK
|
I'm writing a bit of code for a Gedit plugin. I'm using Python and the interface (obviously) is GTK.
So, the issue I'm having is quite simple: I have a search box (a gtk.Entry) and right below I have a results box (a gtk.TreeView). Right after you type something in the search box you are presented a bunch of results, and I would like the user to be able to press the Up/Down keys to select one, Enter to choose it, and be done. Thing is, I can't seem to find a way to forward the Up/Down keypress to the TreeView. Currently I have this piece of code:
def __onSearchKeyPress(self, widget, event):
"""
Forward up and down keys to the tree.
"""
if event.keyval in [gtk.keysyms.Up, gtk.keysyms.Down]:
print "pressed up or down"
e = gtk.gdk.Event(gtk.gdk.KEY_PRESS)
e.keyval = event.keyval
e.window = self.browser.window
e.send_event = True
self.browser.emit("key-press-event", e)
return True
I can clearly see I'm receiving the right kind of event, but the event I'm sending gets ignored by the TreeView. Any ideas?
Thanks in advance people.
|
[
"Not a proper answer to the question (I don't know how to forward key presses), but there's an alternative solution to your problem.\nManipulate the TreeView cursor/selection directly, for example:\npath, column = browser.get_cursor()\nbrowser.set_cursor((path[0] + 1,)) # Down\n\n",
"Did you include the key-press-event in the list of events the widget is allowed to receive? You can do that by calling\nbrowser.add_events(gtk.gdk.KEY_PRESS_MASK)\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"forwarding",
"gtk",
"keypress",
"python"
] |
stackoverflow_0002526589_forwarding_gtk_keypress_python.txt
|
Q:
Can I use XPCOM to create and manipulate a Firefox window as I would use win32 COM with IE?
With win32 COM I create an Internet Explorer instance and control it almost fully from my python code (manipulate windows, DOM elements, etc). More specifically, using DispatchEx('InternetExplorer.Application'). Can I do the same using XPCOM and C++/python?
I need to automate certain actions taken on the html ui of some websites, so no I can't use urllib and I can't use selenium, because it doesn't work with cross-domain urls. I've wrote a wrapper class for Internet Explore where I can create a browser window and do anything with it, but I would like to do the same with firefox as well. I've thought about creating a XUL application that exposes the DOM functionality through a tcp server written in XUL/js. I'm not even sure that's possible, but if I can do everything from my python code without running xulrunner externally, much better.
A:
I don't know about programmatically creating and controlling full Firefox instances, but Mozilla can definitely be embedded using XPCOM.
The Mozilla embedding FAQ, embedding how-to and the embedding APIs overview should get you started. There are also other means for embedding.
A:
I have used the nsIDOMXULElement to attach event listeners in my XPCOM C++ code. I haven't tried modifying the UI, but it will probably work as well.
For an example on how to get an nsIDOMXULElement look at the call "SetVideoWindow" in Songbird's code here.
|
Can I use XPCOM to create and manipulate a Firefox window as I would use win32 COM with IE?
|
With win32 COM I create an Internet Explorer instance and control it almost fully from my python code (manipulate windows, DOM elements, etc). More specifically, using DispatchEx('InternetExplorer.Application'). Can I do the same using XPCOM and C++/python?
I need to automate certain actions taken on the html ui of some websites, so no I can't use urllib and I can't use selenium, because it doesn't work with cross-domain urls. I've wrote a wrapper class for Internet Explore where I can create a browser window and do anything with it, but I would like to do the same with firefox as well. I've thought about creating a XUL application that exposes the DOM functionality through a tcp server written in XUL/js. I'm not even sure that's possible, but if I can do everything from my python code without running xulrunner externally, much better.
|
[
"I don't know about programmatically creating and controlling full Firefox instances, but Mozilla can definitely be embedded using XPCOM.\nThe Mozilla embedding FAQ, embedding how-to and the embedding APIs overview should get you started. There are also other means for embedding.\n",
"I have used the nsIDOMXULElement to attach event listeners in my XPCOM C++ code. I haven't tried modifying the UI, but it will probably work as well.\nFor an example on how to get an nsIDOMXULElement look at the call \"SetVideoWindow\" in Songbird's code here.\n"
] |
[
1,
1
] |
[] |
[] |
[
"browser_automation",
"c++",
"python",
"xpcom",
"xul"
] |
stackoverflow_0002291034_browser_automation_c++_python_xpcom_xul.txt
|
Q:
How to send mail in hotmail using Python?
Is there a way to login my hotmail account and send mails with a Python program?
A:
You can try using their SMTP server:
User name: Your Windows Live ID, for example yourname@hotmail.com
Password: The password you usually use to sign in to Hotmail or Windows Live
SMTP server: smtp.live.com (Port 25) {Note: If port 25 has been blocked in your network or by your ISP, you can set SMTP port to 587 with TLS or SSL Encryption depending on the client in use}
Authentication required? Yes (this matches your POP username and password)
TLS/SSL required? Yes
Use smtplib to send mail. You can find some examples here.
|
How to send mail in hotmail using Python?
|
Is there a way to login my hotmail account and send mails with a Python program?
|
[
"You can try using their SMTP server:\n\nUser name: Your Windows Live ID, for example yourname@hotmail.com\nPassword: The password you usually use to sign in to Hotmail or Windows Live\nSMTP server: smtp.live.com (Port 25) {Note: If port 25 has been blocked in your network or by your ISP, you can set SMTP port to 587 with TLS or SSL Encryption depending on the client in use}\nAuthentication required? Yes (this matches your POP username and password)\nTLS/SSL required? Yes\n\nUse smtplib to send mail. You can find some examples here.\n"
] |
[
2
] |
[] |
[] |
[
"hotmail",
"python"
] |
stackoverflow_0002556533_hotmail_python.txt
|
Q:
What does represent the hexadecimal integer showed on print/repr in Python?
In an interactive session like the following one:
>>> f=open('test.txt','w')
>>> f
<open file 'test.txt', mode 'w' at 0x6e610>
what does 0x6e610 represent and what could I do with that hexadecimal number in Python?
A:
>>> f=open('test.txt')
>>> f
<open file 'test.txt', mode 'r' at 0x10047c938>
>>> hex(id(f))
'0x10047c938'
Have a look at id in the official documentation:
Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
A:
It's the ID of the object, which (in standard Python) is its address in memory.
You can also get it via the id(obj) function.
You can use IDs to tell whether two references refer to the same object - when you say if x is y in Python, you're comparing IDs.
|
What does represent the hexadecimal integer showed on print/repr in Python?
|
In an interactive session like the following one:
>>> f=open('test.txt','w')
>>> f
<open file 'test.txt', mode 'w' at 0x6e610>
what does 0x6e610 represent and what could I do with that hexadecimal number in Python?
|
[
">>> f=open('test.txt')\n>>> f\n<open file 'test.txt', mode 'r' at 0x10047c938>\n>>> hex(id(f))\n'0x10047c938'\n\nHave a look at id in the official documentation:\nReturn the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.\n",
"It's the ID of the object, which (in standard Python) is its address in memory.\nYou can also get it via the id(obj) function.\nYou can use IDs to tell whether two references refer to the same object - when you say if x is y in Python, you're comparing IDs.\n"
] |
[
5,
3
] |
[] |
[] |
[
"core",
"python"
] |
stackoverflow_0002556799_core_python.txt
|
Q:
Distance by sea calculator, intermediate coordinates?
How do I calculate distance between 2 coordinates by sea? I also want to be able to draw a route between the two coordinates.
Only solution I found so far is to split a map into pixels, identify each pixel as LAND or SEA and then try to find the path using A* algorithm. Then transform pixels to relative coordinates.
There are some software packages I could buy but none have online extensions. A service that calculates distances between sea ports and plots the path on a map is searates.com
A:
Beware of the fact that maps can distort distances. For example, in a Mercator projections segments far away from the equator represent less actual distance than segments near the equator of equal length. If you just assign uniform cost to your pixels/squares/etc, you will end up with non-optimal routing and erroneous distance calculations.
If you project a grid on your map (pixels being just one particular grid out of many possible ones) and search for the optimal path using A*, all you need to do to get the search algorithm to behave properly is set the edge weight according to the real distance along the surface of the sphere (earth) and not the distance on the map.
Beware that simply saying "sea or not-sea" is not enough to determine navigability. There are also issues of depth, traffic routing (e.g. shipping traffic thought the English Channel is split into lanes) and political considerations (territorial waters etc). You also want to add routes manually for channels that are too small to show up on the map (Panama, Suez) and adjust their cost to cover for any overhead incurred.
A:
Pretty much you'll need to split the sea into pixels and do something like A*. You could optimize it a bit by coalescing contiguous pixels into larger areas, but if you keep everything squares it'll probably make the search easier. The search would no longer be Manhattan-style, but if you had large enough squares, the additional connection decision time would be more than made up for.
Alternatively, you could iteratively "grow" polygons from all of your ports, building up convex polygons (so that any point within the polygon is reachable from any other without going outside, you want to avoid the PacMan shape, for instance), although this is a refinement/complication/optimization of the "squares" approach I first mentioned. The key is that you know once you're in an area that you can get to anywhere else in that area.
I don't know if this helps, sorry. It's been a long day. Good luck, though. It sounds like a fun problem!
Edit: Forgot to mention, you could also preprocess your area into a quadtree. That is, take your entire map and split it in half vertically and horizontally (you don't need to do both splits at the same time, and if you want to spend some time making "better" splits, you can do that later), and do that recursively until each node is entirely land or sea. From this you can trivially make a network of connections (just connect neighboring leaves), and the A* should be easy enough to implement from there. This'll probably be the easiest way to implement my first suggestion anyway. :)
A:
I reached a satisfactory solution. It is along the lines of what you suggested and what I had in mind initially but it took me a while to figure out the software and GIS concepts, I am a GIS newbie. If someone bumps into something similar again here's my setup: PostGIS for PostgreSQL, maps from Natural Earth, GIS editing software qGis and OpenJUmp, routing algorithms pgRouting.
The Natural Earth maps needed some processing to be useful, I joined the marine polys and the rivers to be able to get some accurate paths to the most inland points. Then I used the 1 degree graticules to get paths from one continent to another (I need to find a more elegant solution than this because some paths look like chess cubes). All these operations can be done from command line by using PostGIS, I found it easier to use the desktop software (next, next). An alternative to Natural Earth maps might be the OpenStreetMap but the planet.osm dump is aroung 200Gb and that discouraged me.
I think this setup also solves the distance accuracy problem, PostGIS takes into account the Earth's actual form and distances should be pretty accurate.
I still need to do some testing and fine tunings but I can say it can calculate and draw a route from any 2 points on the world's coastlines (no small isolated islands yet) and display the routing points names (channels, seas, rivers, oceans).
|
Distance by sea calculator, intermediate coordinates?
|
How do I calculate distance between 2 coordinates by sea? I also want to be able to draw a route between the two coordinates.
Only solution I found so far is to split a map into pixels, identify each pixel as LAND or SEA and then try to find the path using A* algorithm. Then transform pixels to relative coordinates.
There are some software packages I could buy but none have online extensions. A service that calculates distances between sea ports and plots the path on a map is searates.com
|
[
"Beware of the fact that maps can distort distances. For example, in a Mercator projections segments far away from the equator represent less actual distance than segments near the equator of equal length. If you just assign uniform cost to your pixels/squares/etc, you will end up with non-optimal routing and erroneous distance calculations.\nIf you project a grid on your map (pixels being just one particular grid out of many possible ones) and search for the optimal path using A*, all you need to do to get the search algorithm to behave properly is set the edge weight according to the real distance along the surface of the sphere (earth) and not the distance on the map.\nBeware that simply saying \"sea or not-sea\" is not enough to determine navigability. There are also issues of depth, traffic routing (e.g. shipping traffic thought the English Channel is split into lanes) and political considerations (territorial waters etc). You also want to add routes manually for channels that are too small to show up on the map (Panama, Suez) and adjust their cost to cover for any overhead incurred. \n",
"Pretty much you'll need to split the sea into pixels and do something like A*. You could optimize it a bit by coalescing contiguous pixels into larger areas, but if you keep everything squares it'll probably make the search easier. The search would no longer be Manhattan-style, but if you had large enough squares, the additional connection decision time would be more than made up for.\nAlternatively, you could iteratively \"grow\" polygons from all of your ports, building up convex polygons (so that any point within the polygon is reachable from any other without going outside, you want to avoid the PacMan shape, for instance), although this is a refinement/complication/optimization of the \"squares\" approach I first mentioned. The key is that you know once you're in an area that you can get to anywhere else in that area.\nI don't know if this helps, sorry. It's been a long day. Good luck, though. It sounds like a fun problem!\nEdit: Forgot to mention, you could also preprocess your area into a quadtree. That is, take your entire map and split it in half vertically and horizontally (you don't need to do both splits at the same time, and if you want to spend some time making \"better\" splits, you can do that later), and do that recursively until each node is entirely land or sea. From this you can trivially make a network of connections (just connect neighboring leaves), and the A* should be easy enough to implement from there. This'll probably be the easiest way to implement my first suggestion anyway. :)\n",
"I reached a satisfactory solution. It is along the lines of what you suggested and what I had in mind initially but it took me a while to figure out the software and GIS concepts, I am a GIS newbie. If someone bumps into something similar again here's my setup: PostGIS for PostgreSQL, maps from Natural Earth, GIS editing software qGis and OpenJUmp, routing algorithms pgRouting.\nThe Natural Earth maps needed some processing to be useful, I joined the marine polys and the rivers to be able to get some accurate paths to the most inland points. Then I used the 1 degree graticules to get paths from one continent to another (I need to find a more elegant solution than this because some paths look like chess cubes). All these operations can be done from command line by using PostGIS, I found it easier to use the desktop software (next, next). An alternative to Natural Earth maps might be the OpenStreetMap but the planet.osm dump is aroung 200Gb and that discouraged me.\nI think this setup also solves the distance accuracy problem, PostGIS takes into account the Earth's actual form and distances should be pretty accurate.\nI still need to do some testing and fine tunings but I can say it can calculate and draw a route from any 2 points on the world's coastlines (no small isolated islands yet) and display the routing points names (channels, seas, rivers, oceans).\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"distance",
"geo",
"maps",
"python"
] |
stackoverflow_0002512322_distance_geo_maps_python.txt
|
Q:
How to synchronize a python dict with multiprocessing
I am using Python 2.6 and the multiprocessing module for multi-threading. Now I would like to have a synchronized dict (where the only atomic operation I really need is the += operator on a value).
Should I wrap the dict with a multiprocessing.sharedctypes.synchronized() call? Or is another way the way to go?
A:
Intro
There seems to be a lot of arm-chair suggestions and no working examples. None of the answers listed here even suggest using multiprocessing and this is quite a bit disappointing and disturbing. As python lovers we should support our built-in libraries, and while parallel processing and synchronization is never a trivial matter, I believe it can be made trivial with proper design. This is becoming extremely important in modern multi-core architectures and cannot be stressed enough! That said, I am far from satisfied with the multiprocessing library, as it is still in its infancy stages with quite a few pitfalls, bugs, and being geared towards functional programming (which I detest). Currently I still prefer the Pyro module (which is way ahead of its time) over multiprocessing due to multiprocessing's severe limitation in being unable to share newly created objects while the server is running. The "register" class-method of the manager objects will only actually register an object BEFORE the manager (or its server) is started. Enough chatter, more code:
Server.py
from multiprocessing.managers import SyncManager
class MyManager(SyncManager):
pass
syncdict = {}
def get_dict():
return syncdict
if __name__ == "__main__":
MyManager.register("syncdict", get_dict)
manager = MyManager(("127.0.0.1", 5000), authkey="password")
manager.start()
raw_input("Press any key to kill server".center(50, "-"))
manager.shutdown()
In the above code example, Server.py makes use of multiprocessing's SyncManager which can supply synchronized shared objects. This code will not work running in the interpreter because the multiprocessing library is quite touchy on how to find the "callable" for each registered object. Running Server.py will start a customized SyncManager that shares the syncdict dictionary for use of multiple processes and can be connected to clients either on the same machine, or if run on an IP address other than loopback, other machines. In this case the server is run on loopback (127.0.0.1) on port 5000. Using the authkey parameter uses secure connections when manipulating syncdict. When any key is pressed the manager is shutdown.
Client.py
from multiprocessing.managers import SyncManager
import sys, time
class MyManager(SyncManager):
pass
MyManager.register("syncdict")
if __name__ == "__main__":
manager = MyManager(("127.0.0.1", 5000), authkey="password")
manager.connect()
syncdict = manager.syncdict()
print "dict = %s" % (dir(syncdict))
key = raw_input("Enter key to update: ")
inc = float(raw_input("Enter increment: "))
sleep = float(raw_input("Enter sleep time (sec): "))
try:
#if the key doesn't exist create it
if not syncdict.has_key(key):
syncdict.update([(key, 0)])
#increment key value every sleep seconds
#then print syncdict
while True:
syncdict.update([(key, syncdict.get(key) + inc)])
time.sleep(sleep)
print "%s" % (syncdict)
except KeyboardInterrupt:
print "Killed client"
The client must also create a customized SyncManager, registering "syncdict", this time without passing in a callable to retrieve the shared dict. It then uses the customized SycnManager to connect using the loopback IP address (127.0.0.1) on port 5000 and an authkey establishing a secure connection to the manager started in Server.py. It retrieves the shared dict syncdict by calling the registered callable on the manager. It prompts the user for the following:
The key in syncdict to operate on
The amount to increment the value accessed by the key every cycle
The amount of time to sleep per cycle in seconds
The client then checks to see if the key exists. If it doesn't it creates the key on the syncdict. The client then enters an "endless" loop where it updates the key's value by the increment, sleeps the amount specified, and prints the syncdict only to repeat this process until a KeyboardInterrupt occurs (Ctrl+C).
Annoying problems
The Manager's register methods MUST be called before the manager is started otherwise you will get exceptions even though a dir call on the Manager will reveal that it indeed does have the method that was registered.
All manipulations of the dict must be done with methods and not dict assignments (syncdict["blast"] = 2 will fail miserably because of the way multiprocessing shares custom objects)
Using SyncManager's dict method would alleviate annoying problem #2 except that annoying problem #1 prevents the proxy returned by SyncManager.dict() being registered and shared. (SyncManager.dict() can only be called AFTER the manager is started, and register will only work BEFORE the manager is started so SyncManager.dict() is only useful when doing functional programming and passing the proxy to Processes as an argument like the doc examples do)
The server AND the client both have to register even though intuitively it would seem like the client would just be able to figure it out after connecting to the manager (Please add this to your wish-list multiprocessing developers)
Closing
I hope you enjoyed this quite thorough and slightly time-consuming answer as much as I have. I was having a great deal of trouble getting straight in my mind why I was struggling so much with the multiprocessing module where Pyro makes it a breeze and now thanks to this answer I have hit the nail on the head. I hope this is useful to the python community on how to improve the multiprocessing module as I do believe it has a great deal of promise but in its infancy falls short of what is possible. Despite the annoying problems described I think this is still quite a viable alternative and is pretty simple. You could also use SyncManager.dict() and pass it to Processes as an argument the way the docs show and it would probably be an even simpler solution depending on your requirements it just feels unnatural to me.
A:
I would dedicate a separate process to maintaining the "shared dict": just use e.g. xmlrpclib to make that tiny amount of code available to the other processes, exposing via xmlrpclib e.g. a function taking key, increment to perform the increment and one taking just the key and returning the value, with semantic details (is there a default value for missing keys, etc, etc) depending on your app's needs.
Then you can use any approach you like to implement the shared-dict dedicated process: all the way from a single-threaded server with a simple dict in memory, to a simple sqlite DB, etc, etc. I suggest you start with code "as simple as you can get away with" (depending on whether you need a persistent shared dict, or persistence is not necessary to you), then measure and optimize as and if needed.
A:
In response to an appropriate solution to the concurrent-write issue. I did very quick research and found that this article is suggesting a lock/semaphore solution. (http://effbot.org/zone/thread-synchronization.htm)
While the example isn't specificity on a dictionary, I'm pretty sure you could code a class-based wrapper object to help you work with dictionaries based on this idea.
If I had a requirement to implement something like this in a thread safe manner, I'd probably use the Python Semaphore solution. (Assuming my earlier merge technique wouldn't work.) I believe that semaphores generally slow down thread efficiencies due to their blocking nature.
From the site:
A semaphore is a more advanced lock mechanism. A semaphore has an internal counter rather than a lock flag, and it only blocks if more than a given number of threads have attempted to hold the semaphore. Depending on how the semaphore is initialized, this allows multiple threads to access the same code section simultaneously.
semaphore = threading.BoundedSemaphore()
semaphore.acquire() # decrements the counter
... access the shared resource; work with dictionary, add item or whatever.
semaphore.release() # increments the counter
A:
Is there a reason that the dictionary needs to be shared in the first place? Could you have each thread maintain their own instance of a dictionary and either merge at the end of the thread processing or periodically use a call-back to merge copies of the individual thread dictionaries together?
I don't know exactly what you are doing, so keep in my that my written plan may not work verbatim. What I'm suggesting is more of a high-level design idea.
|
How to synchronize a python dict with multiprocessing
|
I am using Python 2.6 and the multiprocessing module for multi-threading. Now I would like to have a synchronized dict (where the only atomic operation I really need is the += operator on a value).
Should I wrap the dict with a multiprocessing.sharedctypes.synchronized() call? Or is another way the way to go?
|
[
"Intro\nThere seems to be a lot of arm-chair suggestions and no working examples. None of the answers listed here even suggest using multiprocessing and this is quite a bit disappointing and disturbing. As python lovers we should support our built-in libraries, and while parallel processing and synchronization is never a trivial matter, I believe it can be made trivial with proper design. This is becoming extremely important in modern multi-core architectures and cannot be stressed enough! That said, I am far from satisfied with the multiprocessing library, as it is still in its infancy stages with quite a few pitfalls, bugs, and being geared towards functional programming (which I detest). Currently I still prefer the Pyro module (which is way ahead of its time) over multiprocessing due to multiprocessing's severe limitation in being unable to share newly created objects while the server is running. The \"register\" class-method of the manager objects will only actually register an object BEFORE the manager (or its server) is started. Enough chatter, more code:\nServer.py\nfrom multiprocessing.managers import SyncManager\n\n\nclass MyManager(SyncManager):\n pass\n\n\nsyncdict = {}\ndef get_dict():\n return syncdict\n\nif __name__ == \"__main__\":\n MyManager.register(\"syncdict\", get_dict)\n manager = MyManager((\"127.0.0.1\", 5000), authkey=\"password\")\n manager.start()\n raw_input(\"Press any key to kill server\".center(50, \"-\"))\n manager.shutdown()\n\nIn the above code example, Server.py makes use of multiprocessing's SyncManager which can supply synchronized shared objects. This code will not work running in the interpreter because the multiprocessing library is quite touchy on how to find the \"callable\" for each registered object. Running Server.py will start a customized SyncManager that shares the syncdict dictionary for use of multiple processes and can be connected to clients either on the same machine, or if run on an IP address other than loopback, other machines. In this case the server is run on loopback (127.0.0.1) on port 5000. Using the authkey parameter uses secure connections when manipulating syncdict. When any key is pressed the manager is shutdown.\nClient.py\nfrom multiprocessing.managers import SyncManager\nimport sys, time\n\nclass MyManager(SyncManager):\n pass\n\nMyManager.register(\"syncdict\")\n\nif __name__ == \"__main__\":\n manager = MyManager((\"127.0.0.1\", 5000), authkey=\"password\")\n manager.connect()\n syncdict = manager.syncdict()\n\n print \"dict = %s\" % (dir(syncdict))\n key = raw_input(\"Enter key to update: \")\n inc = float(raw_input(\"Enter increment: \"))\n sleep = float(raw_input(\"Enter sleep time (sec): \"))\n\n try:\n #if the key doesn't exist create it\n if not syncdict.has_key(key):\n syncdict.update([(key, 0)])\n #increment key value every sleep seconds\n #then print syncdict\n while True:\n syncdict.update([(key, syncdict.get(key) + inc)])\n time.sleep(sleep)\n print \"%s\" % (syncdict)\n except KeyboardInterrupt:\n print \"Killed client\"\n\nThe client must also create a customized SyncManager, registering \"syncdict\", this time without passing in a callable to retrieve the shared dict. It then uses the customized SycnManager to connect using the loopback IP address (127.0.0.1) on port 5000 and an authkey establishing a secure connection to the manager started in Server.py. It retrieves the shared dict syncdict by calling the registered callable on the manager. It prompts the user for the following:\n\nThe key in syncdict to operate on\nThe amount to increment the value accessed by the key every cycle\nThe amount of time to sleep per cycle in seconds\n\nThe client then checks to see if the key exists. If it doesn't it creates the key on the syncdict. The client then enters an \"endless\" loop where it updates the key's value by the increment, sleeps the amount specified, and prints the syncdict only to repeat this process until a KeyboardInterrupt occurs (Ctrl+C).\nAnnoying problems\n\nThe Manager's register methods MUST be called before the manager is started otherwise you will get exceptions even though a dir call on the Manager will reveal that it indeed does have the method that was registered.\nAll manipulations of the dict must be done with methods and not dict assignments (syncdict[\"blast\"] = 2 will fail miserably because of the way multiprocessing shares custom objects)\nUsing SyncManager's dict method would alleviate annoying problem #2 except that annoying problem #1 prevents the proxy returned by SyncManager.dict() being registered and shared. (SyncManager.dict() can only be called AFTER the manager is started, and register will only work BEFORE the manager is started so SyncManager.dict() is only useful when doing functional programming and passing the proxy to Processes as an argument like the doc examples do)\nThe server AND the client both have to register even though intuitively it would seem like the client would just be able to figure it out after connecting to the manager (Please add this to your wish-list multiprocessing developers)\n\nClosing\nI hope you enjoyed this quite thorough and slightly time-consuming answer as much as I have. I was having a great deal of trouble getting straight in my mind why I was struggling so much with the multiprocessing module where Pyro makes it a breeze and now thanks to this answer I have hit the nail on the head. I hope this is useful to the python community on how to improve the multiprocessing module as I do believe it has a great deal of promise but in its infancy falls short of what is possible. Despite the annoying problems described I think this is still quite a viable alternative and is pretty simple. You could also use SyncManager.dict() and pass it to Processes as an argument the way the docs show and it would probably be an even simpler solution depending on your requirements it just feels unnatural to me.\n",
"I would dedicate a separate process to maintaining the \"shared dict\": just use e.g. xmlrpclib to make that tiny amount of code available to the other processes, exposing via xmlrpclib e.g. a function taking key, increment to perform the increment and one taking just the key and returning the value, with semantic details (is there a default value for missing keys, etc, etc) depending on your app's needs.\nThen you can use any approach you like to implement the shared-dict dedicated process: all the way from a single-threaded server with a simple dict in memory, to a simple sqlite DB, etc, etc. I suggest you start with code \"as simple as you can get away with\" (depending on whether you need a persistent shared dict, or persistence is not necessary to you), then measure and optimize as and if needed.\n",
"In response to an appropriate solution to the concurrent-write issue. I did very quick research and found that this article is suggesting a lock/semaphore solution. (http://effbot.org/zone/thread-synchronization.htm)\nWhile the example isn't specificity on a dictionary, I'm pretty sure you could code a class-based wrapper object to help you work with dictionaries based on this idea. \nIf I had a requirement to implement something like this in a thread safe manner, I'd probably use the Python Semaphore solution. (Assuming my earlier merge technique wouldn't work.) I believe that semaphores generally slow down thread efficiencies due to their blocking nature.\nFrom the site:\n\nA semaphore is a more advanced lock mechanism. A semaphore has an internal counter rather than a lock flag, and it only blocks if more than a given number of threads have attempted to hold the semaphore. Depending on how the semaphore is initialized, this allows multiple threads to access the same code section simultaneously.\n\nsemaphore = threading.BoundedSemaphore()\nsemaphore.acquire() # decrements the counter\n... access the shared resource; work with dictionary, add item or whatever.\nsemaphore.release() # increments the counter\n\n",
"Is there a reason that the dictionary needs to be shared in the first place? Could you have each thread maintain their own instance of a dictionary and either merge at the end of the thread processing or periodically use a call-back to merge copies of the individual thread dictionaries together? \nI don't know exactly what you are doing, so keep in my that my written plan may not work verbatim. What I'm suggesting is more of a high-level design idea. \n"
] |
[
65,
3,
3,
2
] |
[] |
[] |
[
"dictionary",
"multiprocessing",
"python"
] |
stackoverflow_0002545961_dictionary_multiprocessing_python.txt
|
Q:
python dict.fromkeys() returns empty
I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.
def enter_users_into_dict(userlist):
newusr = {}
newusr.fromkeys(userlist, 0)
return newusr
ul = ['john', 'mabel']
nd = enter_users_into_dict(ul)
print nd
It returns an empty dict {} where I would expect {'john': 0, 'mabel': 0}.
It is probably very simply but I don't see the solution.
A:
fromkeys is a class method, meaning
newusr.fromkeys(userlist, 0)
is exactly the same as calling
dict.fromkeys(userlist, 0)
Both which return a dictionary of the keys in userlist. You need to assign it to something. Try this instead.
newusr = dict.fromkeys(userlist, 0)
return newusr
A:
You need to collapse the function's body to
def enter_users_into_dict(userlist):
return dict.fromkeys(userlist, 0)
fromkeys is a class method, thus doesn't affect any instance it may be called on (it's best to call it on the class -- that's clearer!), rather it returns the new dictionary it builds... and that's exactly the very dictionary you want to return, to!-)
A:
It should be:
def enter_users_into_dict(userlist):
return dict.fromkeys(userlist, 0)
From the documentation:
fromkeys() is a class method that returns a new dictionary.
|
python dict.fromkeys() returns empty
|
I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.
def enter_users_into_dict(userlist):
newusr = {}
newusr.fromkeys(userlist, 0)
return newusr
ul = ['john', 'mabel']
nd = enter_users_into_dict(ul)
print nd
It returns an empty dict {} where I would expect {'john': 0, 'mabel': 0}.
It is probably very simply but I don't see the solution.
|
[
"fromkeys is a class method, meaning\nnewusr.fromkeys(userlist, 0)\n\nis exactly the same as calling\ndict.fromkeys(userlist, 0)\n\nBoth which return a dictionary of the keys in userlist. You need to assign it to something. Try this instead.\nnewusr = dict.fromkeys(userlist, 0)\nreturn newusr\n\n",
"You need to collapse the function's body to\ndef enter_users_into_dict(userlist):\n return dict.fromkeys(userlist, 0)\n\nfromkeys is a class method, thus doesn't affect any instance it may be called on (it's best to call it on the class -- that's clearer!), rather it returns the new dictionary it builds... and that's exactly the very dictionary you want to return, to!-)\n",
"It should be:\ndef enter_users_into_dict(userlist):\n return dict.fromkeys(userlist, 0)\n\nFrom the documentation:\n\nfromkeys() is a class method that returns a new dictionary.\n\n"
] |
[
10,
3,
2
] |
[] |
[] |
[
"dictionary",
"fromkeys",
"python"
] |
stackoverflow_0002557193_dictionary_fromkeys_python.txt
|
Q:
Cheetah pre-compiled template usage
For performance reason as suggested here, I am studying how to used the pr-compiled template.
I edit hello.tmpl in template directory as
#attr title = "This is my Template"
<html>
<head>
<title>\${title}</title>
</head>
<body>
Hello \${who}!
</body>
</html>
then issued cheetah-compile.exe .\hello.tmpl and get the hello.py
In another python file runner.py, I have:
#!/usr/bin/env python
from Cheetah.Template import Template
from template import hello
def myMethod():
tmpl = hello.hello(searchList=[{'who' : 'world'}])
results = tmpl.respond()
print tmpl
if __name__ == '__main__':
myMethod()
But the outcome is
<html>
<head>
<title>${title}</title>
</head>
<body>
Hello ${who}!
</body>
</html>
Debugging for a while, I found that inside hello.py:
def respond(self, trans=None):
## CHEETAH: main method generated for this template
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
it looks like the trans is None, so it goes to DummyTransaction, what did I miss here?
Any suggestions to how to fix it?
A:
Your main problem is that in runner.py inside myMethod() instead of
print tmpl
You need
print results
Additionally, your code has some formatting problems:
don't escape the ${title} with a backslash
you need if __name__ == '__main__': instead of if name == 'main':
|
Cheetah pre-compiled template usage
|
For performance reason as suggested here, I am studying how to used the pr-compiled template.
I edit hello.tmpl in template directory as
#attr title = "This is my Template"
<html>
<head>
<title>\${title}</title>
</head>
<body>
Hello \${who}!
</body>
</html>
then issued cheetah-compile.exe .\hello.tmpl and get the hello.py
In another python file runner.py, I have:
#!/usr/bin/env python
from Cheetah.Template import Template
from template import hello
def myMethod():
tmpl = hello.hello(searchList=[{'who' : 'world'}])
results = tmpl.respond()
print tmpl
if __name__ == '__main__':
myMethod()
But the outcome is
<html>
<head>
<title>${title}</title>
</head>
<body>
Hello ${who}!
</body>
</html>
Debugging for a while, I found that inside hello.py:
def respond(self, trans=None):
## CHEETAH: main method generated for this template
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
it looks like the trans is None, so it goes to DummyTransaction, what did I miss here?
Any suggestions to how to fix it?
|
[
"Your main problem is that in runner.py inside myMethod() instead of\nprint tmpl\n\nYou need\nprint results\n\nAdditionally, your code has some formatting problems:\n\ndon't escape the ${title} with a backslash\nyou need if __name__ == '__main__': instead of if name == 'main':\n\n"
] |
[
0
] |
[] |
[] |
[
"cheetah",
"python",
"templates"
] |
stackoverflow_0002550323_cheetah_python_templates.txt
|
Q:
Exposing python api over the network for an iphone application
I have functionality built in python on a central server. I wish to expose this api over the network to an iphone application. What would be the best way to do that?
Is it possible to create web services in python and have the iphone app use those? If so could anyone give me pointers as to how to create web services in python.
If someone has a better idea on how to go about doing this let me know =)
A:
Simplest is xmlrpclib, if the app you want to consume this service can speak XML-RPC.
According to this SO question, the iPhone can indeed support XML-RPC without too much trouble.
A:
Look at using a REST style web service for that. I am currently working on an iPhone app that uses a Pylons based web service that the app uses to fetch JSON encoded data. So far it works like a charm.
I'm not sure what library or framework you are using, but here is a little information on Pylons REST controllers. http://pylonshq.com/docs/en/0.9.7/controllers/#using-the-rest-controller-with-a-restful-api
|
Exposing python api over the network for an iphone application
|
I have functionality built in python on a central server. I wish to expose this api over the network to an iphone application. What would be the best way to do that?
Is it possible to create web services in python and have the iphone app use those? If so could anyone give me pointers as to how to create web services in python.
If someone has a better idea on how to go about doing this let me know =)
|
[
"Simplest is xmlrpclib, if the app you want to consume this service can speak XML-RPC.\nAccording to this SO question, the iPhone can indeed support XML-RPC without too much trouble.\n",
"Look at using a REST style web service for that. I am currently working on an iPhone app that uses a Pylons based web service that the app uses to fetch JSON encoded data. So far it works like a charm.\nI'm not sure what library or framework you are using, but here is a little information on Pylons REST controllers. http://pylonshq.com/docs/en/0.9.7/controllers/#using-the-rest-controller-with-a-restful-api\n"
] |
[
2,
1
] |
[] |
[] |
[
"iphone",
"python",
"web_services"
] |
stackoverflow_0002557179_iphone_python_web_services.txt
|
Q:
When I run Django on Dreamhost using SQLite, why do I get an OperationalError telling me that a table doesn’t exist?
I had a Django site running on Dreamhost. Although I used SQLite when developing locally, I initially used MySQL on Dreamhost, because that’s what the wiki page said to do, and because if I’m using an ORM, I might as well take advantage of it by running against a different database.
After a while, I switched the settings on the server to use SQLite, to make it easier to keep my development database in sync with the server one. python manage.py syncdb worked on the server, but when I tried to access the site, I got an OperationalError. The Django error page said that one of my tables didn’t exist.
I checked the database using sqlite on the command line on the server, and using python manage.py shell, and both worked fine.
A:
It turned out that on the server, the DATABASE_NAME setting required a full path, e.g.
DATABASE_NAME = '/home/USERNAME/SITE/DJANGOPROJECT/DATABASE.db'
Locally (and I guess for manage.py on the server), just a filename was fine, e.g.
DATABASE_NAME = 'DATABASE.db'
|
When I run Django on Dreamhost using SQLite, why do I get an OperationalError telling me that a table doesn’t exist?
|
I had a Django site running on Dreamhost. Although I used SQLite when developing locally, I initially used MySQL on Dreamhost, because that’s what the wiki page said to do, and because if I’m using an ORM, I might as well take advantage of it by running against a different database.
After a while, I switched the settings on the server to use SQLite, to make it easier to keep my development database in sync with the server one. python manage.py syncdb worked on the server, but when I tried to access the site, I got an OperationalError. The Django error page said that one of my tables didn’t exist.
I checked the database using sqlite on the command line on the server, and using python manage.py shell, and both worked fine.
|
[
"It turned out that on the server, the DATABASE_NAME setting required a full path, e.g.\nDATABASE_NAME = '/home/USERNAME/SITE/DJANGOPROJECT/DATABASE.db'\n\nLocally (and I guess for manage.py on the server), just a filename was fine, e.g.\nDATABASE_NAME = 'DATABASE.db'\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"dreamhost",
"python",
"sqlite"
] |
stackoverflow_0002557710_django_dreamhost_python_sqlite.txt
|
Q:
Python dealing with dates and times
I'm looking for a solution to the following:
Given today's date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January.
Then based on that, I need to be able to iterate through a directory and find all files that were created that month.
Bonus points would include finding the most current file created for the previous month.
A:
Simplest, where adate is an instance of datetime.date:
def previousmonth(adate):
m = adate.month - 1
return m if m else 12
There's no real way in most Unix filesystems to determine when a file was created, as they just don't keep that information around. Maybe you want the "latest inode change time" (could be creation, could be some other inode change):
import os, datetime
def cmonth(filename):
ts = os.stat(filename).st_ctime
return datetime.date.fromtimestamp(ts).month
Of course, this could mean that month in any year -- you sure, in both questions, you don't want the year as well as the month? That would be the .year attribute.
Anyway, sticking with month only, as per your question, for a single directory (which is the letter of your question), to get all files you can use os.listdir (for a tree rooted in the directory you'd use os.walk instead). Then to keep only those with latest-inode-change in a given month:
def fileswithcmonth(dirname, whatmonth):
results = []
for f in os.listdir(dirname):
fullname = os.path.join(dirname, f)
if whatmonth == cmonth(fullname):
results.append(fullname)
return results
You could code this as a list comprehension, but there's just too much code there for a listcomp to be elegant and concise.
To get the "latest" time, you can either repeat the os.stat call (slower but probably simpler), or change cmonth to return the timestamp as well. Taking the simple route:
def filetimestamp(fullname):
return os.stat(fullname).st_ctime
Now, the "most recent file" given a list files of files' full names (i.e. inc. path) is
max(files, key=filetimestamp)
Of course there are many degrees of freedom in how you put this all together, depending on your exact specs -- given that the specs don't appear to be necessarily precise or complete I've chosen to show the building blocks that you can easily tweak and put together towards your exact needs, rather than a full-blown solution that would likely solve a problem somewhat different from your actual one;-).
Edit: since the OP clarified that they need both year and month, let's see what changes would be needed, using tuples ym for (year, month) in lieu of the bare month:
def previousym(adate):
y = adate.year
m = adate.month - 1
return (y, m) if m else (y - 1, 12)
import os, datetime
def cym(filename):
ts = os.stat(filename).st_ctime
dt datetime.date.fromtimestamp(ts)
return cym.year, cym.month
def fileswithcym(dirname, whatym):
results = []
for f in os.listdir(dirname):
fullname = os.path.join(dirname, f)
# if you need to avoid subdirs, uncomment the following line
# if not os.path.isfile(fullname): continue
if whatym == cym(fullname):
results.append(fullname)
return results
Nothing deep or difficult, as you can see (I also added comments to show how to skip subdirectories if you're worried about those). And btw, if what you actually need is to walk a subtree, rather than just a directory, that change, too, is pretty localized:
def fileswithcymintree(treeroot_dirname, whatym):
results = []
for dp, dirs, files in os.walk(treeroot_dirname):
for f in files:
fullname = os.path.join(dp, f)
if whatym == cym(fullname):
results.append(fullname)
return results
A:
It's fairly easy to find the previous month - see, for example, Alex Martelli's answer - but to find the most recently created file in that month is a bit harder:
from datetime import date
import os
def filesLastMonth(directory):
"""
Given a directory, returns a tuple containing
1. A list with all files made in the previous month (disregards year...)
2. The file most recently created in the previous month
"""
def fileCreationTime(filePath):
return os.path.getctime(filePath)
today = date.today()
lastMonth = today.month-1 if today.month != 1 else 12
# gets each item in the directory that was created last month
createdLastMonth = [item for item in os.listdir(directory) if
date.fromtimestamp(os.path.getctime(item)).month == lastMonth]
# and this is the most recent of the above
mostRecentlyLastMonth = max(createdLastMonth, key=fileCreationTime)
return (createdLastMonth, mostRecentlyLastMonth)
You can use os.path.getctime on Windows to get the creation time of a path, but this doesn't work on Unix - the creation time is not stored in that case (you'll just get the time of the last change).
A:
There are several parts being asked about here...
You can get the current month by using datetime as so: datetime.datetime.now().month. From there you can just subtract one and turn 0 into 12. Python datetime doc: http://docs.python.org/library/datetime.html
Next you can iterate a disk folder by using os.walk Python os.walk doc: http://docs.python.org/library/os.html#os.walk
Lastly, you can check the creation/modified time of the file by using os.stat Python os.stat doc: http://docs.python.org/library/os.html#os.stat
A:
http://docs.python.org/library/datetime.html
First of the previous month from a date
def first_of( today )
yr_mn = today.year*12 + (today.month-1) - 1
return datetime.date( year= yr_mn//12, month= yr_mn%12+1, day=1 )
You can then use this with os.walk to locate the files in question.
A:
Date manipulation is made trivial with a library like Labix's python-dateutil.
You want to do something like this:
In [8]: from dateutil.relativedelta import relativedelta
In [9]: from datetime import date
In [10]: d = date(2010,2,12)
In [11]: print (d-relativedelta(months=1)).month
1
In [12]: print (date(2010,1,4)-relativedelta(months=1)).month
12
|
Python dealing with dates and times
|
I'm looking for a solution to the following:
Given today's date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January.
Then based on that, I need to be able to iterate through a directory and find all files that were created that month.
Bonus points would include finding the most current file created for the previous month.
|
[
"Simplest, where adate is an instance of datetime.date:\ndef previousmonth(adate):\n m = adate.month - 1\n return m if m else 12\n\nThere's no real way in most Unix filesystems to determine when a file was created, as they just don't keep that information around. Maybe you want the \"latest inode change time\" (could be creation, could be some other inode change):\nimport os, datetime\ndef cmonth(filename):\n ts = os.stat(filename).st_ctime\n return datetime.date.fromtimestamp(ts).month\n\nOf course, this could mean that month in any year -- you sure, in both questions, you don't want the year as well as the month? That would be the .year attribute.\nAnyway, sticking with month only, as per your question, for a single directory (which is the letter of your question), to get all files you can use os.listdir (for a tree rooted in the directory you'd use os.walk instead). Then to keep only those with latest-inode-change in a given month:\ndef fileswithcmonth(dirname, whatmonth):\n results = []\n for f in os.listdir(dirname):\n fullname = os.path.join(dirname, f)\n if whatmonth == cmonth(fullname):\n results.append(fullname)\n return results\n\nYou could code this as a list comprehension, but there's just too much code there for a listcomp to be elegant and concise.\nTo get the \"latest\" time, you can either repeat the os.stat call (slower but probably simpler), or change cmonth to return the timestamp as well. Taking the simple route:\ndef filetimestamp(fullname):\n return os.stat(fullname).st_ctime\n\nNow, the \"most recent file\" given a list files of files' full names (i.e. inc. path) is\nmax(files, key=filetimestamp)\n\nOf course there are many degrees of freedom in how you put this all together, depending on your exact specs -- given that the specs don't appear to be necessarily precise or complete I've chosen to show the building blocks that you can easily tweak and put together towards your exact needs, rather than a full-blown solution that would likely solve a problem somewhat different from your actual one;-).\nEdit: since the OP clarified that they need both year and month, let's see what changes would be needed, using tuples ym for (year, month) in lieu of the bare month:\ndef previousym(adate):\n y = adate.year\n m = adate.month - 1\n return (y, m) if m else (y - 1, 12)\n\nimport os, datetime\ndef cym(filename):\n ts = os.stat(filename).st_ctime\n dt datetime.date.fromtimestamp(ts)\n return cym.year, cym.month\n\ndef fileswithcym(dirname, whatym):\n results = []\n for f in os.listdir(dirname):\n fullname = os.path.join(dirname, f)\n # if you need to avoid subdirs, uncomment the following line\n # if not os.path.isfile(fullname): continue\n if whatym == cym(fullname):\n results.append(fullname)\n return results\n\nNothing deep or difficult, as you can see (I also added comments to show how to skip subdirectories if you're worried about those). And btw, if what you actually need is to walk a subtree, rather than just a directory, that change, too, is pretty localized:\ndef fileswithcymintree(treeroot_dirname, whatym):\n results = []\n for dp, dirs, files in os.walk(treeroot_dirname):\n for f in files:\n fullname = os.path.join(dp, f)\n if whatym == cym(fullname):\n results.append(fullname)\n return results\n\n",
"It's fairly easy to find the previous month - see, for example, Alex Martelli's answer - but to find the most recently created file in that month is a bit harder:\nfrom datetime import date\nimport os\n\ndef filesLastMonth(directory):\n \"\"\"\n Given a directory, returns a tuple containing\n 1. A list with all files made in the previous month (disregards year...)\n 2. The file most recently created in the previous month\n \"\"\"\n def fileCreationTime(filePath):\n return os.path.getctime(filePath)\n today = date.today()\n lastMonth = today.month-1 if today.month != 1 else 12\n # gets each item in the directory that was created last month\n createdLastMonth = [item for item in os.listdir(directory) if\n date.fromtimestamp(os.path.getctime(item)).month == lastMonth]\n # and this is the most recent of the above\n mostRecentlyLastMonth = max(createdLastMonth, key=fileCreationTime)\n return (createdLastMonth, mostRecentlyLastMonth)\n\nYou can use os.path.getctime on Windows to get the creation time of a path, but this doesn't work on Unix - the creation time is not stored in that case (you'll just get the time of the last change).\n",
"There are several parts being asked about here...\n\nYou can get the current month by using datetime as so: datetime.datetime.now().month. From there you can just subtract one and turn 0 into 12. Python datetime doc: http://docs.python.org/library/datetime.html\nNext you can iterate a disk folder by using os.walk Python os.walk doc: http://docs.python.org/library/os.html#os.walk\nLastly, you can check the creation/modified time of the file by using os.stat Python os.stat doc: http://docs.python.org/library/os.html#os.stat\n\n",
"http://docs.python.org/library/datetime.html\nFirst of the previous month from a date\ndef first_of( today )\n yr_mn = today.year*12 + (today.month-1) - 1\n return datetime.date( year= yr_mn//12, month= yr_mn%12+1, day=1 )\n\nYou can then use this with os.walk to locate the files in question.\n",
"Date manipulation is made trivial with a library like Labix's python-dateutil.\nYou want to do something like this:\nIn [8]: from dateutil.relativedelta import relativedelta\n\nIn [9]: from datetime import date\n\nIn [10]: d = date(2010,2,12)\n\nIn [11]: print (d-relativedelta(months=1)).month\n1\n\nIn [12]: print (date(2010,1,4)-relativedelta(months=1)).month\n12\n\n"
] |
[
3,
2,
1,
0,
0
] |
[] |
[] |
[
"datetime",
"python"
] |
stackoverflow_0002555904_datetime_python.txt
|
Q:
Please explain this python behavior
class SomeClass(object):
def __init__(self, key_text_pairs = None):
.....
for key, text in key_text_pairs:
......
......
x = SomeClass([(1, "abc",), (2, "fff",)])
The value of key_text_pairs inside the init is None even if I pass a list as in the above statement. Why is it so??
I want to write a generic init which can take all iterator objects...
Thanks
Edit: oops.. I wanted to pass key value pair in the form of tuple... I was just trying to create a toy example.. I am still seeing the same behavior
A:
First of all, when you say for key, text in key_text_pairs, you are implying that the list has tuples. I tested your code exactly the way it is and that's what happened.
Change x = SomeClass([1, 2, 3]) to x = SomeClass([(1, 1.0), (2, 2.0), (3, 3.0)]) and see if that helps
Cheers
A:
So just looking at that code, is what you posted exactly what you want? Specifically, if you're passing in a list that looks like:
[1, 2, 3]
Then I don't think you want to try to extract it like this:
for key, text in key_text_pairs
You can extract a list of individual integers into a pair of values like key/text.
If I run that code as you posted it, I get a stack trace:
Traceback (most recent call last):
File "test.py", line 6, in <module>
x = SomeClass([1, 2, 3])
File "test.py", line 3, in __init__
for key, text in key_text_pairs:
TypeError: 'int' object is not iterable
You either need to do something like this (extract one value at a time):
class SomeClass(object):
def __init__(self, key_text_pairs = None):
for key in key_text_pairs:
....
x = SomeClass([1, 2, 3])
Or your original list needs to change to be holding pairs of values if you're going to keep that code the same:
x = SomeClass([('a',1),('b',2),('c',3)])
A:
Could you post a traceback?
This is what I get when I run the code:
In [1]: class SomeClass(object):
...: def __init__(self, key_text_pairs = None):
...: for key, text in key_text_pairs:
...: print "key:", key, "text", text
...:
...:
In [2]: x = SomeClass([1,2,3])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/ryan/<ipython console> in <module>()
/home/ryan/<ipython console> in __init__(self, key_text_pairs)
TypeError: 'int' object is not iterable
In [3]: x = SomeClass(zip('abc', [1,2,3]))
key: a text 1
key: b text 2
key: c text 3
|
Please explain this python behavior
|
class SomeClass(object):
def __init__(self, key_text_pairs = None):
.....
for key, text in key_text_pairs:
......
......
x = SomeClass([(1, "abc",), (2, "fff",)])
The value of key_text_pairs inside the init is None even if I pass a list as in the above statement. Why is it so??
I want to write a generic init which can take all iterator objects...
Thanks
Edit: oops.. I wanted to pass key value pair in the form of tuple... I was just trying to create a toy example.. I am still seeing the same behavior
|
[
"First of all, when you say for key, text in key_text_pairs, you are implying that the list has tuples. I tested your code exactly the way it is and that's what happened.\nChange x = SomeClass([1, 2, 3]) to x = SomeClass([(1, 1.0), (2, 2.0), (3, 3.0)]) and see if that helps\nCheers\n",
"So just looking at that code, is what you posted exactly what you want? Specifically, if you're passing in a list that looks like:\n[1, 2, 3]\nThen I don't think you want to try to extract it like this:\nfor key, text in key_text_pairs\nYou can extract a list of individual integers into a pair of values like key/text.\nIf I run that code as you posted it, I get a stack trace:\nTraceback (most recent call last):\n File \"test.py\", line 6, in <module>\n x = SomeClass([1, 2, 3])\n File \"test.py\", line 3, in __init__\n for key, text in key_text_pairs:\nTypeError: 'int' object is not iterable\n\nYou either need to do something like this (extract one value at a time):\nclass SomeClass(object):\n def __init__(self, key_text_pairs = None):\n for key in key_text_pairs:\n ....\n\nx = SomeClass([1, 2, 3])\n\nOr your original list needs to change to be holding pairs of values if you're going to keep that code the same:\nx = SomeClass([('a',1),('b',2),('c',3)])\n",
"Could you post a traceback?\nThis is what I get when I run the code:\nIn [1]: class SomeClass(object):\n ...: def __init__(self, key_text_pairs = None):\n ...: for key, text in key_text_pairs:\n ...: print \"key:\", key, \"text\", text\n ...: \n ...: \n\nIn [2]: x = SomeClass([1,2,3])\n---------------------------------------------------------------------------\nTypeError Traceback (most recent call last)\n\n/home/ryan/<ipython console> in <module>()\n\n/home/ryan/<ipython console> in __init__(self, key_text_pairs)\n\nTypeError: 'int' object is not iterable\n\nIn [3]: x = SomeClass(zip('abc', [1,2,3]))\nkey: a text 1\nkey: b text 2\nkey: c text 3\n\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"initialization",
"python"
] |
stackoverflow_0002557891_initialization_python.txt
|
Q:
Sorting and indexing into a list in a Django template?
How can you perform complex sorting on an object before passing it to the template? For example, here is my view:
@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all():
physician.service_patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
return render_to_response('hospitalists/overview.html', RequestContext(request, {'physicians': physicians,}))
The physicians object is not ordered correctly in the template. Why not?
Additionally, how do you index into a list inside the template? For example, (this doesn't work):
{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3>
{% for notes in note_sets.index(parent.forloop.counter0) %}
#only want to display the notes of this note_type!
{% for note in notes %}
<p>{{ note }}</p>
{% endfor %}
{% endfor %}
</div>
{% endfor %}
Thanks a bunch, Pete
A:
As others have indicated, both of your problems are best solved outside the template -- either in the models, or in the view. One strategy would be to add helper methods to the relevant classes.
Getting a sorted list of a physician's patients:
class Physician(Model):
...
def sorted_patients(self):
return self.patients.order_by('bed__room__unit',
'bed__room__order',
'bed__order')
And in the template, use physician.sorted_patients rather than physician.patients.
For the "display the notes of this note_type", it sounds like you might want a notes method for the note_type class. From your description I'm not sure if this is a model class or not, but the principle is the same:
class NoteType:
...
def notes(self):
return <calculate note set>
And then the template:
{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3></div>
{% for note in note_type.notes %}
<p>{{ note }}</p>
{% endfor %}
</div>
{% endfor %}
A:
"I'd like to do this from within a template:"
Don't. Do it in the view function where it belongs.
Since the question is incomplete, it's impossible to guess at the data model and provide the exact solution.
results= physician.patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
Should be sufficient. Provide results to the template for rendering. It's in the proper order.
If this isn't sorting properly (perhaps because of some model subtletly) then you always have this kind of alternative.
def by_unit_room_bed( patient ):
return patient.bed.room.unit, patient.bed.room.order, patient.bed.order
patient_list = list( physician.patients )
patient_list.sort( key=by_unit_room_bed )
Provide patient_list to the template for rendering. It's in the proper order.
"how do you index into a list inside the template"
I'm not sure what you're trying to do, but most of the time, the answer is "Don't". Do it in the view function.
The template just iterate through simple lists filling in simple HTML templates.
If it seems too complex for a template, it is. Keep the template simple -- it's only presentation. The processing goes in the view function
A:
You should be able to construct the ordered query set in your view and pass it to your template:
def myview(request):
patients = Physician.patients.order_by('bed__room__unit',
'bed__room__order',
'bed__order')
return render_to_response('some_template.html',
dict(patients=patients),
mimetype='text/html')
Your template can then loop over patients which will contain the ordered results. Does this not work for you?
EDIT: For indexing, just use the dot syntax: mylist.3 in a template becomes mylist[3] in python. See http://docs.djangoproject.com/en/dev/ref/templates/api/#rendering-a-context for more information.
A:
This is one way of doing it, although very ugly :
{% for note in note_sets|slice:"forloop.counter0"|first %}
|
Sorting and indexing into a list in a Django template?
|
How can you perform complex sorting on an object before passing it to the template? For example, here is my view:
@login_required
def overview(request):
physicians = PhysicianGroup.objects.get(pk=physician_group).physicians
for physician in physicians.all():
physician.service_patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')
return render_to_response('hospitalists/overview.html', RequestContext(request, {'physicians': physicians,}))
The physicians object is not ordered correctly in the template. Why not?
Additionally, how do you index into a list inside the template? For example, (this doesn't work):
{% for note_type in note_types %}
<div><h3>{{ note_type }}</h3>
{% for notes in note_sets.index(parent.forloop.counter0) %}
#only want to display the notes of this note_type!
{% for note in notes %}
<p>{{ note }}</p>
{% endfor %}
{% endfor %}
</div>
{% endfor %}
Thanks a bunch, Pete
|
[
"As others have indicated, both of your problems are best solved outside the template -- either in the models, or in the view. One strategy would be to add helper methods to the relevant classes.\nGetting a sorted list of a physician's patients:\nclass Physician(Model):\n ...\n def sorted_patients(self):\n return self.patients.order_by('bed__room__unit',\n 'bed__room__order',\n 'bed__order')\n\nAnd in the template, use physician.sorted_patients rather than physician.patients.\nFor the \"display the notes of this note_type\", it sounds like you might want a notes method for the note_type class. From your description I'm not sure if this is a model class or not, but the principle is the same:\nclass NoteType:\n ...\n def notes(self):\n return <calculate note set>\n\nAnd then the template:\n{% for note_type in note_types %}\n <div><h3>{{ note_type }}</h3></div>\n {% for note in note_type.notes %}\n <p>{{ note }}</p>\n {% endfor %}\n </div>\n{% endfor %}\n\n",
"\"I'd like to do this from within a template:\"\nDon't. Do it in the view function where it belongs.\nSince the question is incomplete, it's impossible to guess at the data model and provide the exact solution. \nresults= physician.patients.order_by('bed__room__unit', 'bed__room__order', 'bed__order')\n\nShould be sufficient. Provide results to the template for rendering. It's in the proper order.\nIf this isn't sorting properly (perhaps because of some model subtletly) then you always have this kind of alternative.\ndef by_unit_room_bed( patient ):\n return patient.bed.room.unit, patient.bed.room.order, patient.bed.order\n\npatient_list = list( physician.patients )\npatient_list.sort( key=by_unit_room_bed )\n\nProvide patient_list to the template for rendering. It's in the proper order.\n\"how do you index into a list inside the template\"\nI'm not sure what you're trying to do, but most of the time, the answer is \"Don't\". Do it in the view function.\nThe template just iterate through simple lists filling in simple HTML templates. \nIf it seems too complex for a template, it is. Keep the template simple -- it's only presentation. The processing goes in the view function\n",
"You should be able to construct the ordered query set in your view and pass it to your template:\ndef myview(request):\n patients = Physician.patients.order_by('bed__room__unit', \n 'bed__room__order', \n 'bed__order')\n return render_to_response('some_template.html',\n dict(patients=patients), \n mimetype='text/html')\n\nYour template can then loop over patients which will contain the ordered results. Does this not work for you?\nEDIT: For indexing, just use the dot syntax: mylist.3 in a template becomes mylist[3] in python. See http://docs.djangoproject.com/en/dev/ref/templates/api/#rendering-a-context for more information.\n",
"This is one way of doing it, although very ugly :\n{% for note in note_sets|slice:\"forloop.counter0\"|first %}\n"
] |
[
11,
4,
1,
0
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0001191439_django_django_templates_python.txt
|
Q:
delete Task / PeriodicTask in celery
How can I delete a regular Task or PeriodicTask in celery?
A:
You revoke the task: See documentation:
Control.revoke(task_id, destination=None, terminate=False, signal='SIGTERM', **kwargs)
Tell all (or specific) workers to revoke a task by id.
If a task is revoked, the workers will ignore the task and not execute it after all.
Parameters:
task_id – Id of the task to revoke.
terminate – Also terminate the process currently working on the task (if any).
signal – Name of signal to send to process if terminate. Default is TERM.
|
delete Task / PeriodicTask in celery
|
How can I delete a regular Task or PeriodicTask in celery?
|
[
"You revoke the task: See documentation:\nControl.revoke(task_id, destination=None, terminate=False, signal='SIGTERM', **kwargs)\n Tell all (or specific) workers to revoke a task by id.\n\n If a task is revoked, the workers will ignore the task and not execute it after all.\n\n Parameters: \n task_id – Id of the task to revoke.\n terminate – Also terminate the process currently working on the task (if any).\n signal – Name of signal to send to process if terminate. Default is TERM.\n\n"
] |
[
16
] |
[] |
[] |
[
"celery",
"python",
"rabbitmq"
] |
stackoverflow_0002557424_celery_python_rabbitmq.txt
|
Q:
Django serializer gives 'str' object has no attribute '_meta' error
I am trying to make Django view that will give JSON responce with earliest and latest objects. But unfotunately it fails to work with this error.
'str' object has no attribute '_meta'
I have other serialization and it works.
Here is the code.
def get_calendar_limits(request):
result = serializers.serialize("json", Session.objects.aggregate(Max('date'), Min('date')), ensure_ascii=False)
return HttpResponse(result, mimetype="application/javascript")
Thanks a lot beforehand.
A:
I get the same error when trying to serialize an object that is not derived from Django's Model
A:
Python has "json" module. It can 'dumps' and 'loads' function. They can serialize and deserialize accordingly.
A:
Take a look at the following:
objects= Session.objects.aggregate(Max('date'), Min('date'))
print [ type[o] for o in objects ]
result = serializers.serialize("json", objects, ensure_ascii=False)
You might want to just run the above in interactive Python as an experiment.
What type are your objects? Is that type serializable?
|
Django serializer gives 'str' object has no attribute '_meta' error
|
I am trying to make Django view that will give JSON responce with earliest and latest objects. But unfotunately it fails to work with this error.
'str' object has no attribute '_meta'
I have other serialization and it works.
Here is the code.
def get_calendar_limits(request):
result = serializers.serialize("json", Session.objects.aggregate(Max('date'), Min('date')), ensure_ascii=False)
return HttpResponse(result, mimetype="application/javascript")
Thanks a lot beforehand.
|
[
"I get the same error when trying to serialize an object that is not derived from Django's Model\n",
"Python has \"json\" module. It can 'dumps' and 'loads' function. They can serialize and deserialize accordingly.\n",
"Take a look at the following:\nobjects= Session.objects.aggregate(Max('date'), Min('date'))\nprint [ type[o] for o in objects ]\nresult = serializers.serialize(\"json\", objects, ensure_ascii=False)\n\nYou might want to just run the above in interactive Python as an experiment.\nWhat type are your objects? Is that type serializable?\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"django",
"json",
"python"
] |
stackoverflow_0000793095_django_json_python.txt
|
Q:
how to get internet explorer address bar for python
i need grab to internet explorer address bar. how to get address bar url for python ? (i need second part other browsers grabbing address bar but internet explorer is urgently).
Thanks.
A:
The following works for me.
from win32com.client import Dispatch
SHELL = Dispatch("Shell.Application")
def get_ie(shell):
for win in shell.Windows():
if win.Name == "Windows Internet Explorer":
return win
return None
def main():
ie = get_ie(SHELL)
if ie:
print ie.LocationURL
else:
print "no ie window"
if __name__ == '__main__':
main()
I tried to use Dispatch('InternetExplorer.Application') to connect to current IE window, but it would always create a new window. The code would have been simpler.
# This doesn't work
from win32com.client import Dispatch
# This line will always create a new window
ie = Dispatch("InternetExplorer.Application")
print ie.LocationURL
A:
Would something like this not work?
import win32gui
def get_current_window_title():
cur_hwnd = win32gui.GetForegroundWindow()
win_title = win32gui.GetWindowText(cur_hwnd)
return win_title
|
how to get internet explorer address bar for python
|
i need grab to internet explorer address bar. how to get address bar url for python ? (i need second part other browsers grabbing address bar but internet explorer is urgently).
Thanks.
|
[
"The following works for me.\nfrom win32com.client import Dispatch\n\nSHELL = Dispatch(\"Shell.Application\")\n\ndef get_ie(shell):\n for win in shell.Windows():\n if win.Name == \"Windows Internet Explorer\":\n return win\n return None\n\ndef main():\n ie = get_ie(SHELL)\n if ie:\n print ie.LocationURL\n else:\n print \"no ie window\"\n\nif __name__ == '__main__':\n main()\n\nI tried to use Dispatch('InternetExplorer.Application') to connect to current IE window, but it would always create a new window. The code would have been simpler.\n# This doesn't work\nfrom win32com.client import Dispatch\n\n# This line will always create a new window\nie = Dispatch(\"InternetExplorer.Application\")\n\nprint ie.LocationURL\n\n",
"Would something like this not work?\nimport win32gui\n\ndef get_current_window_title():\n cur_hwnd = win32gui.GetForegroundWindow()\n win_title = win32gui.GetWindowText(cur_hwnd)\n return win_title\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"internet_explorer",
"python",
"pywin32"
] |
stackoverflow_0002555905_internet_explorer_python_pywin32.txt
|
Q:
Supported Audio Formats of Qt4 Phonon?
I am making a music player in PyQt4, and I am using Phonon to play the music itself. This application is aimed primarily at Windows, but I plan on also supporting Mac and Linux versions. What I want to know is which audio formats are supported by Phonon so that I can ensure that the user only enters those files.
A:
You need to call availableMimeTypes() to check what formats the backend supports.
|
Supported Audio Formats of Qt4 Phonon?
|
I am making a music player in PyQt4, and I am using Phonon to play the music itself. This application is aimed primarily at Windows, but I plan on also supporting Mac and Linux versions. What I want to know is which audio formats are supported by Phonon so that I can ensure that the user only enters those files.
|
[
"You need to call availableMimeTypes() to check what formats the backend supports.\n"
] |
[
6
] |
[] |
[] |
[
"phonon",
"pyqt4",
"python",
"qt4"
] |
stackoverflow_0002551873_phonon_pyqt4_python_qt4.txt
|
Q:
(Python/Django): How do I keep my production db in sync (scheme and data) and with dev pc db?
I have a local Postgres database which will be filled with data (daily) on my local development machine. What is a good solution to transfer/sync/mirror this data to a production Postgres database.
For what it's worth I'm developing in Python using Django.
Thanks!
A:
This seems like a strange workflow for me. Wouldn't it be much better to import the data in the production database and then just sync it with your development db from time to time?
IMO, the development machine shouldn't be included in the production data workflow.
That's the way I do it using fabric. I've written a simple function which copies part of the production db onto the local development machine.
A:
South is a great tool for dealing with database migrations in Django projects. The latest release now supports both schema and data migrations
http://south.aeracode.org/docs/tutorial/part3.html#data-migrations
The app provides a number of management commands which allow you to dump executable files which when run can alter the database schema or insert records. It's great for automating changes to a production environment or when working on a team. You could then use something like fabric (or do it manually if you must) to push up the migration files and run the migrate command to populate your database
|
(Python/Django): How do I keep my production db in sync (scheme and data) and with dev pc db?
|
I have a local Postgres database which will be filled with data (daily) on my local development machine. What is a good solution to transfer/sync/mirror this data to a production Postgres database.
For what it's worth I'm developing in Python using Django.
Thanks!
|
[
"This seems like a strange workflow for me. Wouldn't it be much better to import the data in the production database and then just sync it with your development db from time to time?\nIMO, the development machine shouldn't be included in the production data workflow.\nThat's the way I do it using fabric. I've written a simple function which copies part of the production db onto the local development machine.\n",
"South is a great tool for dealing with database migrations in Django projects. The latest release now supports both schema and data migrations\nhttp://south.aeracode.org/docs/tutorial/part3.html#data-migrations\nThe app provides a number of management commands which allow you to dump executable files which when run can alter the database schema or insert records. It's great for automating changes to a production environment or when working on a team. You could then use something like fabric (or do it manually if you must) to push up the migration files and run the migrate command to populate your database\n"
] |
[
3,
2
] |
[] |
[] |
[
"django",
"postgresql",
"python"
] |
stackoverflow_0002537253_django_postgresql_python.txt
|
Q:
Simulate Network Presence in dbus
Is there a way using Python to simulate the presence of an active network connection using dbus? If I call getstate() on the dbus, I'm able to get the current network state. I want to set the current state to 4 (Connection Present). This is because Network Manager is not able to connect using my modem and I use other tools to connect. Pidgin, Empathy and other software are not able to detect the network.
A:
I'm pretty sure that both Pidgin and Empathy assume you're online if you disable NM by right-clicking the Network Manager tray icon and untick Enable Networking. So you can do this when you're connecting via a non-NM mechanism. No code necessary!
(You could write an application which implements the same D-Bus interface as NetworkManager, sits on the system bus, and pretends to be online, and then when you want to use your network kill the real NetworkManager program and start your fake one, but that smells like overkill to me...)
A:
Your options are to write something that mocks NetworkManager's D-Bus interface, or to write a module for NetworkManager that supports the tools you use.
|
Simulate Network Presence in dbus
|
Is there a way using Python to simulate the presence of an active network connection using dbus? If I call getstate() on the dbus, I'm able to get the current network state. I want to set the current state to 4 (Connection Present). This is because Network Manager is not able to connect using my modem and I use other tools to connect. Pidgin, Empathy and other software are not able to detect the network.
|
[
"I'm pretty sure that both Pidgin and Empathy assume you're online if you disable NM by right-clicking the Network Manager tray icon and untick Enable Networking. So you can do this when you're connecting via a non-NM mechanism. No code necessary!\n(You could write an application which implements the same D-Bus interface as NetworkManager, sits on the system bus, and pretends to be online, and then when you want to use your network kill the real NetworkManager program and start your fake one, but that smells like overkill to me...)\n",
"Your options are to write something that mocks NetworkManager's D-Bus interface, or to write a module for NetworkManager that supports the tools you use.\n"
] |
[
1,
0
] |
[] |
[] |
[
"dbus",
"linux",
"python"
] |
stackoverflow_0002550523_dbus_linux_python.txt
|
Q:
How do I do a semijoin using SQLAlchemy?
http://en.wikipedia.org/wiki/Relational_algebra#Semijoin
Let's say that I have two tables: A and B. I want to make a query that would work similarly to the following SQL statement using the SQLAlchemy orm:
SELECT A.*
FROM A, B
WHERE A.id = B.id
AND B.type = 'some type';
The thing is that I'm trying to separate out A and B's logic into different places. So I'd like to make two queries that I can define in separate places: one where A uses B as a subquery, but only returns rows from A. I'm sure this is fairly easy to do, but an example would be nice if someone could show me.
A:
Let's assume you have models classes A and B mapped to corresponding tables.
The simplest case is when you have relation in A pointing to B, let's name it A.b. Then you just use either A.b.has(type='some type') or A.b.any(type='some type') (depending on whether A.b is scalar or represent a collection) as condition when querying A model.
But you say you are trying to separate login. Does this mean there is no such relation? If so, you have to define join condition explicitly:
session.query(A).join((B, A.id==B.id)).filter(B.type=='some type')
|
How do I do a semijoin using SQLAlchemy?
|
http://en.wikipedia.org/wiki/Relational_algebra#Semijoin
Let's say that I have two tables: A and B. I want to make a query that would work similarly to the following SQL statement using the SQLAlchemy orm:
SELECT A.*
FROM A, B
WHERE A.id = B.id
AND B.type = 'some type';
The thing is that I'm trying to separate out A and B's logic into different places. So I'd like to make two queries that I can define in separate places: one where A uses B as a subquery, but only returns rows from A. I'm sure this is fairly easy to do, but an example would be nice if someone could show me.
|
[
"Let's assume you have models classes A and B mapped to corresponding tables. \nThe simplest case is when you have relation in A pointing to B, let's name it A.b. Then you just use either A.b.has(type='some type') or A.b.any(type='some type') (depending on whether A.b is scalar or represent a collection) as condition when querying A model.\nBut you say you are trying to separate login. Does this mean there is no such relation? If so, you have to define join condition explicitly:\nsession.query(A).join((B, A.id==B.id)).filter(B.type=='some type')\n\n"
] |
[
2
] |
[] |
[] |
[
"orm",
"python",
"sql",
"sqlalchemy"
] |
stackoverflow_0002554132_orm_python_sql_sqlalchemy.txt
|
Q:
Django unable to update model
i have the following function to override the default save function in a model match
def save(self, *args, **kwargs):
if self.Match_Status == "F":
Team.objects.filter(pk=self.Team_one.id).update(Played=F('Played')+1)
Team.objects.filter(pk=self.Team_two.id).update(Played=F('Played')+1)
if self.Winner !="":
Team.objects.filter(pk=self.Winner.id).update(Win=F('Win')+1, Points=F('Points')+3)
else:
return
if self.Match_Status == "D":
Team.objects.filter(pk=self.Team_one.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1)
Team.objects.filter(pk=self.Team_two.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1)
super(Match, self).save(*args, **kwargs)
I am able to save the match model just fine but Team model does not seem to be updating at all and no error is being thrown. am i missing some thing here ?
A:
add this in ur admin.py
def save_model(self, request ,obj ,form,change):
if obj.Match_Status == "F":
Team.objects.filter(pk=obj.Team_one.id).update(Played=F('Played')+1)
Team.objects.filter(pk=obj.Team_two.id).update(Played=F('Played')+1)
if obj.Winner !="":
Team.objects.filter(pk=obj.Winner.id).update(Win=F('Win')+1, Points=F('Points')+3)
else:
return
if obj.Match_Status == "D":
Team.objects.filter(pk=obj.Team_one.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1)
Team.objects.filter(pk=obj.Team_two.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1)
obj.save()
A:
There's nothing obviously wrong with your method. So usual debugging tricks apply: are you sure the method is actually being called? Are you sure the Match object has a Match_Status of either F or D? Put in some print statements to be sure.
|
Django unable to update model
|
i have the following function to override the default save function in a model match
def save(self, *args, **kwargs):
if self.Match_Status == "F":
Team.objects.filter(pk=self.Team_one.id).update(Played=F('Played')+1)
Team.objects.filter(pk=self.Team_two.id).update(Played=F('Played')+1)
if self.Winner !="":
Team.objects.filter(pk=self.Winner.id).update(Win=F('Win')+1, Points=F('Points')+3)
else:
return
if self.Match_Status == "D":
Team.objects.filter(pk=self.Team_one.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1)
Team.objects.filter(pk=self.Team_two.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1)
super(Match, self).save(*args, **kwargs)
I am able to save the match model just fine but Team model does not seem to be updating at all and no error is being thrown. am i missing some thing here ?
|
[
"add this in ur admin.py \ndef save_model(self, request ,obj ,form,change):\n if obj.Match_Status == \"F\":\n Team.objects.filter(pk=obj.Team_one.id).update(Played=F('Played')+1)\n Team.objects.filter(pk=obj.Team_two.id).update(Played=F('Played')+1)\n if obj.Winner !=\"\": \n Team.objects.filter(pk=obj.Winner.id).update(Win=F('Win')+1, Points=F('Points')+3)\n else:\n return\n if obj.Match_Status == \"D\":\n Team.objects.filter(pk=obj.Team_one.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1)\n Team.objects.filter(pk=obj.Team_two.id).update(Played=F('Played')+1, Draw = F('Draw')+1, Points=F('Points')+1)\n obj.save()\n\n",
"There's nothing obviously wrong with your method. So usual debugging tricks apply: are you sure the method is actually being called? Are you sure the Match object has a Match_Status of either F or D? Put in some print statements to be sure.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"django_admin",
"django_models",
"python"
] |
stackoverflow_0002437526_django_django_admin_django_models_python.txt
|
Q:
Why is it that I cannot insert this into Django correctly?
new_thing = MyTable(last_updated=datetime.datetime.now())
new_thing.save()
>>>>select * from MyTable\G;
last_updated: 2010-04-01 05:26:21
However, in my Python console...this is what it says...
>>> print datetime.datetime.now()
2010-04-01 10:26:21.643041
So obviously it's off by 5 hours.
By the way, the database uses "SYSTEM" as its time, so they should match perfectly.
mysql> SELECT current_time;
+--------------+
| current_time |
+--------------+
| 10:30:16 |
+--------------+
>>> print datetime.datetime.now()
2010-04-01 10:30:17.793040
A:
Difference is between your timezone and whatever is set in Django settings.py TIME_ZONE. By default it's 'America/Chicago'.
A:
I suspect that Django save the time in DB according to GMT and the ORM give it back to you according to your locale.
Tell use what does this code say :
print MyTable.objects.all().order_by("-last_updated")[0].get()
|
Why is it that I cannot insert this into Django correctly?
|
new_thing = MyTable(last_updated=datetime.datetime.now())
new_thing.save()
>>>>select * from MyTable\G;
last_updated: 2010-04-01 05:26:21
However, in my Python console...this is what it says...
>>> print datetime.datetime.now()
2010-04-01 10:26:21.643041
So obviously it's off by 5 hours.
By the way, the database uses "SYSTEM" as its time, so they should match perfectly.
mysql> SELECT current_time;
+--------------+
| current_time |
+--------------+
| 10:30:16 |
+--------------+
>>> print datetime.datetime.now()
2010-04-01 10:30:17.793040
|
[
"Difference is between your timezone and whatever is set in Django settings.py TIME_ZONE. By default it's 'America/Chicago'.\n",
"I suspect that Django save the time in DB according to GMT and the ORM give it back to you according to your locale.\nTell use what does this code say :\nprint MyTable.objects.all().order_by(\"-last_updated\")[0].get()\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"database",
"django",
"mysql",
"python",
"time"
] |
stackoverflow_0002559702_database_django_mysql_python_time.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.