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:
tokenize a string keeping delimiters in Python
Is there any equivalent to str.split in Python that also returns the delimiters?
I need to preserve the whitespace layout for my output after processing some of the tokens.
Example:
>>> s="\tthis is an example"
>>> print s.split()
['this', 'is', 'an', 'example']
>>> print what_I_want(s)
['\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']
Thanks!
A:
How about
import re
splitter = re.compile(r'(\s+|\S+)')
splitter.findall(s)
A:
>>> re.compile(r'(\s+)').split("\tthis is an example")
['', '\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']
A:
the re module provides this functionality:
>>> import re
>>> re.split('(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
(quoted from the Python documentation).
For your example (split on whitespace), use re.split('(\s+)', '\tThis is an example').
The key is to enclose the regex on which to split in capturing parentheses. That way, the delimiters are added to the list of results.
Edit: As pointed out, any preceding/trailing delimiters will of course also be added to the list. To avoid that you can use the .strip() method on your input string first.
A:
Have you looked at pyparsing? Example borrowed from the pyparsing wiki:
>>> from pyparsing import Word, alphas
>>> greet = Word(alphas) + "," + Word(alphas) + "!"
>>> hello1 = 'Hello, World!'
>>> hello2 = 'Greetings, Earthlings!'
>>> for hello in hello1, hello2:
... print (u'%s \u2192 %r' % (hello, greet.parseString(hello))).encode('utf-8')
...
Hello, World! β (['Hello', ',', 'World', '!'], {})
Greetings, Earthlings! β (['Greetings', ',', 'Earthlings', '!'], {})
|
tokenize a string keeping delimiters in Python
|
Is there any equivalent to str.split in Python that also returns the delimiters?
I need to preserve the whitespace layout for my output after processing some of the tokens.
Example:
>>> s="\tthis is an example"
>>> print s.split()
['this', 'is', 'an', 'example']
>>> print what_I_want(s)
['\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']
Thanks!
|
[
"How about\nimport re\nsplitter = re.compile(r'(\\s+|\\S+)')\nsplitter.findall(s)\n\n",
">>> re.compile(r'(\\s+)').split(\"\\tthis is an example\")\n['', '\\t', 'this', ' ', 'is', ' ', 'an', ' ', 'example']\n\n",
"the re module provides this functionality:\n>>> import re\n>>> re.split('(\\W+)', 'Words, words, words.')\n['Words', ', ', 'words', ', ', 'words', '.', '']\n\n(quoted from the Python documentation).\nFor your example (split on whitespace), use re.split('(\\s+)', '\\tThis is an example').\nThe key is to enclose the regex on which to split in capturing parentheses. That way, the delimiters are added to the list of results. \nEdit: As pointed out, any preceding/trailing delimiters will of course also be added to the list. To avoid that you can use the .strip() method on your input string first.\n",
"Have you looked at pyparsing? Example borrowed from the pyparsing wiki:\n>>> from pyparsing import Word, alphas\n>>> greet = Word(alphas) + \",\" + Word(alphas) + \"!\"\n>>> hello1 = 'Hello, World!'\n>>> hello2 = 'Greetings, Earthlings!'\n>>> for hello in hello1, hello2:\n... print (u'%s \\u2192 %r' % (hello, greet.parseString(hello))).encode('utf-8')\n... \nHello, World! β (['Hello', ',', 'World', '!'], {})\nGreetings, Earthlings! β (['Greetings', ',', 'Earthlings', '!'], {})\n\n"
] |
[
19,
6,
4,
3
] |
[
"Thanks guys for pointing for the re module, I'm still trying to decide between that and using my own function that returns a sequence...\ndef split_keep_delimiters(s, delims=\"\\t\\n\\r \"):\n delim_group = s[0] in delims\n start = 0\n for index, char in enumerate(s):\n if delim_group != (char in delims):\n delim_group ^= True\n yield s[start:index]\n start = index\n yield s[start:index+1]\n\nIf I had time I'd benchmark them xD\n"
] |
[
-1
] |
[
"python",
"split",
"string",
"tokenize"
] |
stackoverflow_0001820336_python_split_string_tokenize.txt
|
Q:
Appending lists from files to a single list in Python
I'm trying to write a function that reads files from a "deferred" directory which contains files that contain lists. Here's what the files in the deferred folder contain:
'173378981', '45000', '343434', '3453453', '34534545', '3452342', '234234', '42063008', 'Exempted', '10000'
'1000014833', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'1000009598', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'279483421', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'1000009600', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'389453080', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'1000009602', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
The function used to write the file(s):
def storeDeferredRecords(records):
"""docstring for createFile"""
now = datetime.datetime.now()
filename = deferredDir + '/' + now.strftime("%Y%m%d-%H%M%S")
f = open(filename, 'w')
newlist = map(lambda(x): str(x)[1:-1], records)
for item in newlist:
f.write("%s\n" % item)
f.close
I need help with the function used to read the file. I was only able to write this:
def getDeferredRecords():
"""docstring for getDeferredRecords"""
infiles = [infile for infile in glob.glob(deferredDir + '/*')]
<code to read the contents of each file here>
Can someone help me out? I need to read the lines and insert them into a list. This list will then be merged with records from separate CSV file.
A:
First, the last line in the store function needs to be like this f.close()
Your store function saves the values in a newline-separated manner. To read all the files, should be enough:
def getDeferredRecords():
"""docstring for getDeferredRecords"""
return dict((infile, list(iter(file(infile))))
for infile in glob.glob(deferredDir + '/*'))
Explanation: a file is iterable, so you can do for line in file: print line for example. With list(iter(file)) you have the lines of a file in a list. dict((a, b) for a, b in foo) returns a dictionary with {a: b} pairs. The return value of the function is a dictionary with the format {filename: list_of_lines_in_file}. Keep in mind that the list elements are strings with a trailing newline.
A:
See the csv module:
BigList = []
for filename in glob.glob(deferredDir + '/*'):
PartList = csv.reader(open(filename))
BigList.extend(PartList)
Is that what you had in mind?
A:
The Python cvs module is likely a good answer:
http://docs.python.org/library/csv.html
Question:
glob.glob() returns an iterable already, so I do not see the point here...
[infile for infile in glob.glob(deferredDir + '/*')]
Rather:
BigList = []
for filename in glob.glob(deferredDir + '/*'):
#CVS read code here
#add to BigList
Food for thought.
A:
Incorporating ideas from Tim Pietzcker, here are the re-written functions:
def storeDeferredRecords(records):
"""docstring for createFile"""
now = datetime.datetime.now()
filename = deferredDir + '/' + now.strftime("%Y%m%d-%H%M%S")
f = csv.writer(open(filename, 'w'), delimiter=',')
f.writerows(records)
def getDeferredRecords():
"""docstring for getDeferredRecords"""
for filename in glob.glob(deferredDir + '/*'):
def_records = csv.reader(open(filename,'r'))
records.extend(def_records)
I used csv.writer instead of using the previous code block:
f = open(filename, 'w')
newlist = map(lambda(x): str(x)[1:-1], records)
for item in newlist:
f.write("%s\n" % item)
f.close
Thanks to all those who replied!
|
Appending lists from files to a single list in Python
|
I'm trying to write a function that reads files from a "deferred" directory which contains files that contain lists. Here's what the files in the deferred folder contain:
'173378981', '45000', '343434', '3453453', '34534545', '3452342', '234234', '42063008', 'Exempted', '10000'
'1000014833', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'1000009598', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'279483421', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'1000009600', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'389453080', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
'1000009602', '0', '0', '0', '0', '0', '0', '0', 'Exempted', '0'
The function used to write the file(s):
def storeDeferredRecords(records):
"""docstring for createFile"""
now = datetime.datetime.now()
filename = deferredDir + '/' + now.strftime("%Y%m%d-%H%M%S")
f = open(filename, 'w')
newlist = map(lambda(x): str(x)[1:-1], records)
for item in newlist:
f.write("%s\n" % item)
f.close
I need help with the function used to read the file. I was only able to write this:
def getDeferredRecords():
"""docstring for getDeferredRecords"""
infiles = [infile for infile in glob.glob(deferredDir + '/*')]
<code to read the contents of each file here>
Can someone help me out? I need to read the lines and insert them into a list. This list will then be merged with records from separate CSV file.
|
[
"First, the last line in the store function needs to be like this f.close()\nYour store function saves the values in a newline-separated manner. To read all the files, should be enough:\ndef getDeferredRecords():\n \"\"\"docstring for getDeferredRecords\"\"\"\n return dict((infile, list(iter(file(infile)))) \n for infile in glob.glob(deferredDir + '/*'))\n\nExplanation: a file is iterable, so you can do for line in file: print line for example. With list(iter(file)) you have the lines of a file in a list. dict((a, b) for a, b in foo) returns a dictionary with {a: b} pairs. The return value of the function is a dictionary with the format {filename: list_of_lines_in_file}. Keep in mind that the list elements are strings with a trailing newline.\n",
"See the csv module:\nBigList = []\nfor filename in glob.glob(deferredDir + '/*'):\n PartList = csv.reader(open(filename))\n BigList.extend(PartList)\n\nIs that what you had in mind?\n",
"The Python cvs module is likely a good answer:\nhttp://docs.python.org/library/csv.html\nQuestion:\nglob.glob() returns an iterable already, so I do not see the point here...\n[infile for infile in glob.glob(deferredDir + '/*')]\n\nRather:\nBigList = []\nfor filename in glob.glob(deferredDir + '/*'):\n #CVS read code here\n #add to BigList\n\nFood for thought.\n",
"Incorporating ideas from Tim Pietzcker, here are the re-written functions:\ndef storeDeferredRecords(records):\n \"\"\"docstring for createFile\"\"\"\n now = datetime.datetime.now()\n filename = deferredDir + '/' + now.strftime(\"%Y%m%d-%H%M%S\")\n f = csv.writer(open(filename, 'w'), delimiter=',')\n f.writerows(records)\n\ndef getDeferredRecords():\n \"\"\"docstring for getDeferredRecords\"\"\"\n for filename in glob.glob(deferredDir + '/*'):\n def_records = csv.reader(open(filename,'r'))\n records.extend(def_records)\n\nI used csv.writer instead of using the previous code block:\nf = open(filename, 'w')\nnewlist = map(lambda(x): str(x)[1:-1], records)\nfor item in newlist:\n f.write(\"%s\\n\" % item)\nf.close\n\nThanks to all those who replied!\n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"io",
"list",
"python"
] |
stackoverflow_0001820357_io_list_python.txt
|
Q:
Must Standard libraries for python beginner
Though there can be many but as i am very new to python so which modules or classes within standard libraries i should know when programming in python, especially when i am practicing programming challenges from a C++ book? Libraries which can make my life easier? Since there can be no single correct answer, i am making this question a wiki.
A:
The standard libraries, i.e. the ones considered more or less part of Python. Start with those, there is plenty to learn before starting on 3rd party stuff.
Things like:
os
re
subprocess
struct
A:
Check out the excellent Python Module of the Week blog series.
A:
The re module is a must. itertools also often comes handy.
Generally speaking: Take a deep look at Standard library. Then you might think about wxPython for GUI, numPy for computations, Django for web and Amara for XML, and... there's plenty of Python libs and modules out there. Just suit your needs.
A:
Actually, to work problems from a C++ book using Python, you mainly just need to master Python's built-in types, especially the data structures tuple, list, set, and dict; and the built-in functions, like max, min, sorted, and reversed.
These builtins have a lot of features that aren't obvious at first, such as the in keyword, the optional key= argument to list.sort, list slicing, sequence multiplication, the dict(list_of_pairs) constructor, del, tuple unpacking, and so on. It's fun to learn these, and they make Python a real joy to use.
Also see collections.defaultdict. If you need file I/O, read about open and file objects.
A:
math
Seems too fundamental, but when getting started with python (lets face it, I'm still learning it) I missed some functions in the math module that would have been helpful. I ended up writing my own versions which worked but I could have saved time...
A:
Since you ask about libraries, not specific modules in them, the standard library that comes with Python is the first and most fundamental answer; the programming challenges from a C++ book are unlikely to require anything beyond that (such as GUI toolkits) -- perhaps numpy/scipy if the book is heavily slanted to scientific programming.
A:
The standard library, especially the built-in functions. They seem trivial but can yield impressive results!
It really pays to know the basics of a default python installation. If you doubt that just follow the Stack Overflow python questions. Some answers are just amazing :)
|
Must Standard libraries for python beginner
|
Though there can be many but as i am very new to python so which modules or classes within standard libraries i should know when programming in python, especially when i am practicing programming challenges from a C++ book? Libraries which can make my life easier? Since there can be no single correct answer, i am making this question a wiki.
|
[
"The standard libraries, i.e. the ones considered more or less part of Python. Start with those, there is plenty to learn before starting on 3rd party stuff.\nThings like:\n\nos\nre\nsubprocess\nstruct\n\n",
"Check out the excellent Python Module of the Week blog series.\n",
"The re module is a must. itertools also often comes handy. \nGenerally speaking: Take a deep look at Standard library. Then you might think about wxPython for GUI, numPy for computations, Django for web and Amara for XML, and... there's plenty of Python libs and modules out there. Just suit your needs.\n",
"Actually, to work problems from a C++ book using Python, you mainly just need to master Python's built-in types, especially the data structures tuple, list, set, and dict; and the built-in functions, like max, min, sorted, and reversed.\nThese builtins have a lot of features that aren't obvious at first, such as the in keyword, the optional key= argument to list.sort, list slicing, sequence multiplication, the dict(list_of_pairs) constructor, del, tuple unpacking, and so on. It's fun to learn these, and they make Python a real joy to use.\nAlso see collections.defaultdict. If you need file I/O, read about open and file objects.\n",
"math\nSeems too fundamental, but when getting started with python (lets face it, I'm still learning it) I missed some functions in the math module that would have been helpful. I ended up writing my own versions which worked but I could have saved time...\n",
"Since you ask about libraries, not specific modules in them, the standard library that comes with Python is the first and most fundamental answer; the programming challenges from a C++ book are unlikely to require anything beyond that (such as GUI toolkits) -- perhaps numpy/scipy if the book is heavily slanted to scientific programming.\n",
"The standard library, especially the built-in functions. They seem trivial but can yield impressive results!\nIt really pays to know the basics of a default python installation. If you doubt that just follow the Stack Overflow python questions. Some answers are just amazing :)\n"
] |
[
9,
9,
5,
4,
4,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001820657_python.txt
|
Q:
Django redirect not working
I can see the problem, I attached my code and error page.
In my template, I have:
{% if user.get_profile.is_store %}
<!--DO SOME LOGIC-->
{%endif%}
In my view, I have:
def downloads(request):
"""
Downloads page, a user facing page for the trade members to downloads POS etc
"""
if not authenticated_user(request):
return HttpResponseRedirect("/professional/")
if request.user.get_profile().is_store():
return HttpResponseRedirect("/")
user = request.user
account = user.get_profile()
downloads_list = TradeDownloads.objects.filter(online=1)[:6]
downloads_list[0].get_thumbnail()
data = {}
data['download_list'] = downloads_list
return render_to_response('downloads.html', data, RequestContext(request))
Environment:
Request Method: GET
Request URL: http://localhost:8000/professional/downloads
Django Version: 1.1.1
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'sico.news',
'sico.store_locator',
'sico.css_switch',
'sico.professional',
'sico.contact',
'sico.shop',
'tinymce',
'captcha']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
My error report:
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/var/www/sico/src/sico/../sico/professional/views.py" in downloads
78. if request.user.get_profile().is_store():
File "/var/www/sico/src/sico/../sico/shop/models.py" in is_store
988. return not self.account is None
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py" in __get__
191. rel_obj = self.related.model._base_manager.get(**params)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py" in get
120. return self.get_query_set().get(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in get
305. % self.model._meta.object_name)
Exception Type: DoesNotExist at /professional/downloads
Exception Value: Account matching query does not exist.
My BaseAccount Class
class BaseAccount(models.Model):
user = models.ForeignKey(User, unique=True)
def __unicode__(self):
"""
Return the unicode representation of this customer, which is the user's
full name, if set, otherwise, the user's username
"""
fn = self.user.get_full_name()
if fn:
return fn
return self.user.username
def user_name(self):
"""
Returns the full name of the related user object
"""
return self.user.get_full_name()
def email(self):
"""
Return the email address of the related user object
"""
return self.user.email
def is_store(self):
return not self.account is None
def is_professional(self):
return not self.professional is None
My Account class`
lass Account(BaseAccount):
"""
The account is an extension of the Django user and serves as the profile
object in user.get_profile() for shop purchases and sessions
"""
telephone = models.CharField(max_length=32)
default_address = models.ForeignKey(Address, related_name='billing_account', blank=True, null=True)
security_question = models.ForeignKey(SecurityQuestion)
security_answer = models.CharField(max_length=200)
how_heard = models.CharField("How did you hear about us?", max_length=100)
feedback = models.TextField(blank=True)
opt_in = models.BooleanField("Subscribe to mailing list", help_text="Please tick here if you would like to receive updates from %s" % Site.objects.get_current().name)
temporary = models.BooleanField()
def has_placed_orders(self):
"""
Returns True if the user has placed at least one order, False otherwise
"""
return self.order_set.count() > 0
def get_last_order(self):
"""
Returns the latest order that this customer has placed. If no orders
have been placed, then None is returned
"""
try:
return self.order_set.all().order_by('-date')[0]
except IndexError:
return None
def get_currency(self):
"""
Get the currency for this customer. If global currencies are enabled
(settings.ENABLE_GLOBAL_CURRENCIES) then this function will return
the currency related to their default address, otherwise, it returns
the site default
"""
if settings.ENABLE_GLOBAL_CURRENCIES:
return self.default_address.country.currency
return Currency.get_default_currency()
currency = property(get_currency)
def get_gateway_currency(self):
"""
Get the currency that an order will be put through protx with. If protx
currencies are enabled (settings.ENABLE_PROTX_CURRENCIES), then the
currency will be the same returned by get_currency, otherwise, the
site default is used
"""
if settings.ENABLE_PROTX_CURRENCIES and settings.ENABLE_GLOBAL_CURRENCIES:
return self.currency
return Currency.get_default_currency()
gateway_currency = property(get_gateway_currency)
`
A:
self.account is pointing at a non-existent Account object when it's trying to process is_store(). I would guess you are using a database that doesn't enforce foreign keys *cough*MySQL*cough*, and your data got messed up.
A:
It looks like the user.get_profile() return value is empty, and therefore it fails on the next is_store() call:
return not self.account is None
That fails, because self is empty (i.e. None).
[edit] After reading this (under Profiles) it looks like the profile for that user does not exist and therefore you get the DoesNotExist exception.
A:
It's not redirect that is not working- it's your is_store() procedure or non-existing profile. You should check what exactly is self.account referring.
As far as I can tell from looking at code, you have two tables in your database- one for baseaccount, which only stores user id, and account, which stores all fields associated with account + baseaccount id. You can try to replace is_store with something like this
def is_store(self):
try:
return self.account is None
except Account.DoesNotExist:
return False
I am by no means an Django expert, but I think this could do the trick.
|
Django redirect not working
|
I can see the problem, I attached my code and error page.
In my template, I have:
{% if user.get_profile.is_store %}
<!--DO SOME LOGIC-->
{%endif%}
In my view, I have:
def downloads(request):
"""
Downloads page, a user facing page for the trade members to downloads POS etc
"""
if not authenticated_user(request):
return HttpResponseRedirect("/professional/")
if request.user.get_profile().is_store():
return HttpResponseRedirect("/")
user = request.user
account = user.get_profile()
downloads_list = TradeDownloads.objects.filter(online=1)[:6]
downloads_list[0].get_thumbnail()
data = {}
data['download_list'] = downloads_list
return render_to_response('downloads.html', data, RequestContext(request))
Environment:
Request Method: GET
Request URL: http://localhost:8000/professional/downloads
Django Version: 1.1.1
Python Version: 2.6.2
Installed Applications:
['django.contrib.auth',
'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'sico.news',
'sico.store_locator',
'sico.css_switch',
'sico.professional',
'sico.contact',
'sico.shop',
'tinymce',
'captcha']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
My error report:
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/var/www/sico/src/sico/../sico/professional/views.py" in downloads
78. if request.user.get_profile().is_store():
File "/var/www/sico/src/sico/../sico/shop/models.py" in is_store
988. return not self.account is None
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/related.py" in __get__
191. rel_obj = self.related.model._base_manager.get(**params)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py" in get
120. return self.get_query_set().get(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in get
305. % self.model._meta.object_name)
Exception Type: DoesNotExist at /professional/downloads
Exception Value: Account matching query does not exist.
My BaseAccount Class
class BaseAccount(models.Model):
user = models.ForeignKey(User, unique=True)
def __unicode__(self):
"""
Return the unicode representation of this customer, which is the user's
full name, if set, otherwise, the user's username
"""
fn = self.user.get_full_name()
if fn:
return fn
return self.user.username
def user_name(self):
"""
Returns the full name of the related user object
"""
return self.user.get_full_name()
def email(self):
"""
Return the email address of the related user object
"""
return self.user.email
def is_store(self):
return not self.account is None
def is_professional(self):
return not self.professional is None
My Account class`
lass Account(BaseAccount):
"""
The account is an extension of the Django user and serves as the profile
object in user.get_profile() for shop purchases and sessions
"""
telephone = models.CharField(max_length=32)
default_address = models.ForeignKey(Address, related_name='billing_account', blank=True, null=True)
security_question = models.ForeignKey(SecurityQuestion)
security_answer = models.CharField(max_length=200)
how_heard = models.CharField("How did you hear about us?", max_length=100)
feedback = models.TextField(blank=True)
opt_in = models.BooleanField("Subscribe to mailing list", help_text="Please tick here if you would like to receive updates from %s" % Site.objects.get_current().name)
temporary = models.BooleanField()
def has_placed_orders(self):
"""
Returns True if the user has placed at least one order, False otherwise
"""
return self.order_set.count() > 0
def get_last_order(self):
"""
Returns the latest order that this customer has placed. If no orders
have been placed, then None is returned
"""
try:
return self.order_set.all().order_by('-date')[0]
except IndexError:
return None
def get_currency(self):
"""
Get the currency for this customer. If global currencies are enabled
(settings.ENABLE_GLOBAL_CURRENCIES) then this function will return
the currency related to their default address, otherwise, it returns
the site default
"""
if settings.ENABLE_GLOBAL_CURRENCIES:
return self.default_address.country.currency
return Currency.get_default_currency()
currency = property(get_currency)
def get_gateway_currency(self):
"""
Get the currency that an order will be put through protx with. If protx
currencies are enabled (settings.ENABLE_PROTX_CURRENCIES), then the
currency will be the same returned by get_currency, otherwise, the
site default is used
"""
if settings.ENABLE_PROTX_CURRENCIES and settings.ENABLE_GLOBAL_CURRENCIES:
return self.currency
return Currency.get_default_currency()
gateway_currency = property(get_gateway_currency)
`
|
[
"self.account is pointing at a non-existent Account object when it's trying to process is_store(). I would guess you are using a database that doesn't enforce foreign keys *cough*MySQL*cough*, and your data got messed up.\n",
"It looks like the user.get_profile() return value is empty, and therefore it fails on the next is_store() call:\nreturn not self.account is None\n\nThat fails, because self is empty (i.e. None).\n[edit] After reading this (under Profiles) it looks like the profile for that user does not exist and therefore you get the DoesNotExist exception.\n",
"It's not redirect that is not working- it's your is_store() procedure or non-existing profile. You should check what exactly is self.account referring.\nAs far as I can tell from looking at code, you have two tables in your database- one for baseaccount, which only stores user id, and account, which stores all fields associated with account + baseaccount id. You can try to replace is_store with something like this \ndef is_store(self):\ntry: \n return self.account is None \nexcept Account.DoesNotExist: \n return False\n\nI am by no means an Django expert, but I think this could do the trick.\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"django",
"django_templates",
"django_views",
"python"
] |
stackoverflow_0001820852_django_django_templates_django_views_python.txt
|
Q:
Unique UUIDs from multiple processes on same machine
To tag the data we create, I'm considering using uuids. Security is not an issue, so I was going to use version 1 (date-and-mac-address-based). The only concern is that each user may be creating multiple data files at once from different processes with multiple threads. Assuming Python's uuid library is thread-safe (though it doesn't look it), that still leaves the multiple process issue. I'm considering suffixing the uuid with a dash and the process number.
Since our group has little experience with uuids, are there any issues I need to keep in mind? How is the multiple process issue usually handled?
A:
Just use uuid4 for completely random UUIDs. There is no need to worry about collisions.
edit in response to comment: In my experience, redundant data leads to inconsistencies sooner or later. There is a reason that avoiding redundancy is a dogma of relational database design.
So don't use the UUID as a "redundancy backup" for the actual "originating computer" and "timestamp" data. Either use it as a pure unique ID carrying no other information, or don't use it at all.
|
Unique UUIDs from multiple processes on same machine
|
To tag the data we create, I'm considering using uuids. Security is not an issue, so I was going to use version 1 (date-and-mac-address-based). The only concern is that each user may be creating multiple data files at once from different processes with multiple threads. Assuming Python's uuid library is thread-safe (though it doesn't look it), that still leaves the multiple process issue. I'm considering suffixing the uuid with a dash and the process number.
Since our group has little experience with uuids, are there any issues I need to keep in mind? How is the multiple process issue usually handled?
|
[
"Just use uuid4 for completely random UUIDs. There is no need to worry about collisions.\nedit in response to comment: In my experience, redundant data leads to inconsistencies sooner or later. There is a reason that avoiding redundancy is a dogma of relational database design. \nSo don't use the UUID as a \"redundancy backup\" for the actual \"originating computer\" and \"timestamp\" data. Either use it as a pure unique ID carrying no other information, or don't use it at all.\n"
] |
[
4
] |
[] |
[] |
[
"python",
"uuid"
] |
stackoverflow_0001821399_python_uuid.txt
|
Q:
sqlalchemy does not create my foreign key
SqlAlchemy newbie question:
Base = declarative_base()
class A(Base):
__tablename__ = 'as'
id = Column(Integer, primary_key=True)
class B(Base):
__tablename__ = 'bs'
id = Column(Integer, primary_key=True)
a = relation(A)
When I create my database schema, I have two tables, as and bs, which have one column (id) but there is no a column in table bs that points to A.
What can I be doing wrong? My database is mysql, if it matters.
A:
relation() only tells the mapper how are the two tables related. You still need to add a column with the foreign key information. For example:
class B(Base):
__tablename__ = 'bs'
id = Column(Integer, primary_key=True)
a_id = Column(Integer, ForeignKey('as.id'), name="a")
a = relation(A)
|
sqlalchemy does not create my foreign key
|
SqlAlchemy newbie question:
Base = declarative_base()
class A(Base):
__tablename__ = 'as'
id = Column(Integer, primary_key=True)
class B(Base):
__tablename__ = 'bs'
id = Column(Integer, primary_key=True)
a = relation(A)
When I create my database schema, I have two tables, as and bs, which have one column (id) but there is no a column in table bs that points to A.
What can I be doing wrong? My database is mysql, if it matters.
|
[
"relation() only tells the mapper how are the two tables related. You still need to add a column with the foreign key information. For example:\nclass B(Base):\n __tablename__ = 'bs'\n id = Column(Integer, primary_key=True)\n a_id = Column(Integer, ForeignKey('as.id'), name=\"a\")\n a = relation(A)\n\n"
] |
[
5
] |
[] |
[] |
[
"mysql",
"orm",
"python",
"sqlalchemy"
] |
stackoverflow_0001821527_mysql_orm_python_sqlalchemy.txt
|
Q:
Beautifulsoup get value in table
I am trying to scrape
http://www.co.jefferson.co.us/ats/displaygeneral.do?sch=000104
and get the "owner Name(s)"
What I have works but is really ugly and not the best I am sure, so I am looking for a better way.
Here is what I have:
soup = BeautifulSoup(url_opener.open(url))
x = soup('table', text = re.compile("Owner Name"))
print 'And the owner is', x[0].parent.parent.parent.tr.nextSibling.nextSibling.next.next.next
The relevant HTML is
<td valign="top">
<table border="1" cellpadding="1" cellspacing="0" align="right">
<tbody><tr class="tableheaders">
<td>Owner Name(s)</td>
</tr>
<tr>
<td>PILCHER DONALD L </td>
</tr>
</tbody></table>
</td>
Wow, there are lots of questions about beautifulsoup, I looked through them but didn't find an answer that helped me, hopefully this is not a duplicate question
A:
(Edit: apparently the HTML the OP posted lies -- there is in fact no tbody tag to look for, even though he made it a point of including in that HTML. So, changing to use table instead of tbody).
As there may be several table-rows you want (e.g., see the sibling URL to the one you give, with the last digit, 4, changed into a 5), I suggest a loop such as the following:
# locate the table containing a cell with the given text
owner = re.compile('Owner Name')
cell = soup.find(text=owner).parent
while cell.name != 'table': cell = cell.parent
# print all non-empty strings in the table (except for the given text)
for x in cell.findAll(text=lambda x: x.strip() and not owner.match(x)):
print x
this is reasonably robust to minor changes in page structure: having located the cell of interest, it loops up its parents until it's found the table tag, then over all navigable strings within that table that aren't empty (or just whitespace), excluding the owner header.
A:
This is Aaron DeVore's answer from the Beautifulsoup discussion group, It work well for me.
soup = BeautifulSoup(...)
label = soup.find(text="Owner Name(s)")
Needs Tag.string to get to the actual name string
name = label.findNext('td').string
If you're doing a bunch of them, you can even go for a list comprehension.
names = [unicode(label.findNext('td').string) for label in
soup.findAll(text="Owner Name(s)")]
A:
This is a slight improvement, but I couldn't figure out how to get rid of the three parents.
x[0].parent.parent.parent.findAll('td')[1].string
|
Beautifulsoup get value in table
|
I am trying to scrape
http://www.co.jefferson.co.us/ats/displaygeneral.do?sch=000104
and get the "owner Name(s)"
What I have works but is really ugly and not the best I am sure, so I am looking for a better way.
Here is what I have:
soup = BeautifulSoup(url_opener.open(url))
x = soup('table', text = re.compile("Owner Name"))
print 'And the owner is', x[0].parent.parent.parent.tr.nextSibling.nextSibling.next.next.next
The relevant HTML is
<td valign="top">
<table border="1" cellpadding="1" cellspacing="0" align="right">
<tbody><tr class="tableheaders">
<td>Owner Name(s)</td>
</tr>
<tr>
<td>PILCHER DONALD L </td>
</tr>
</tbody></table>
</td>
Wow, there are lots of questions about beautifulsoup, I looked through them but didn't find an answer that helped me, hopefully this is not a duplicate question
|
[
"(Edit: apparently the HTML the OP posted lies -- there is in fact no tbody tag to look for, even though he made it a point of including in that HTML. So, changing to use table instead of tbody).\nAs there may be several table-rows you want (e.g., see the sibling URL to the one you give, with the last digit, 4, changed into a 5), I suggest a loop such as the following:\n# locate the table containing a cell with the given text\nowner = re.compile('Owner Name')\ncell = soup.find(text=owner).parent\nwhile cell.name != 'table': cell = cell.parent\n# print all non-empty strings in the table (except for the given text)\nfor x in cell.findAll(text=lambda x: x.strip() and not owner.match(x)):\n print x\n\nthis is reasonably robust to minor changes in page structure: having located the cell of interest, it loops up its parents until it's found the table tag, then over all navigable strings within that table that aren't empty (or just whitespace), excluding the owner header.\n",
"This is Aaron DeVore's answer from the Beautifulsoup discussion group, It work well for me.\nsoup = BeautifulSoup(...)\nlabel = soup.find(text=\"Owner Name(s)\")\n\nNeeds Tag.string to get to the actual name string\nname = label.findNext('td').string\n\nIf you're doing a bunch of them, you can even go for a list comprehension.\nnames = [unicode(label.findNext('td').string) for label in\nsoup.findAll(text=\"Owner Name(s)\")]\n\n",
"This is a slight improvement, but I couldn't figure out how to get rid of the three parents.\nx[0].parent.parent.parent.findAll('td')[1].string\n\n"
] |
[
5,
3,
1
] |
[] |
[] |
[
"beautifulsoup",
"html_content_extraction",
"python",
"screen_scraping"
] |
stackoverflow_0001817184_beautifulsoup_html_content_extraction_python_screen_scraping.txt
|
Q:
How to get unicode month name in Python?
I am trying to get a unicode version of calendar.month_abbr[6]. If I don't specify an encoding for the locale, I don't know how to convert the string to unicode. The example code below shows my problem:
>>> import locale
>>> import calendar
>>> locale.setlocale(locale.LC_ALL, ("ru_RU"))
'ru_RU'
>>> print repr(calendar.month_abbr[6])
'\xb8\xee\xdd'
>>> print repr(calendar.month_abbr[6].decode("utf8"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 0: unexpected code byte
>>> locale.setlocale(locale.LC_ALL, ("ru_RU", "utf8"))
'ru_RU.UTF8'
>>> print repr(calendar.month_abbr[6])
'\xd0\x98\xd1\x8e\xd0\xbd'
>>> print repr(calendar.month_abbr[6].decode("utf8"))
u'\u0418\u044e\u043d'
Any ideas how to solve this? The solution doesn't have to look like this. Any solution that gives me the abbreviated month name in unicode is fine.
A:
Change the last line in your code:
>>> print calendar.month_abbr[6].decode("utf8")
ΠΡΠ½
Improperly used repr() hides from you that you already get what you needed.
Also getlocale() can be used to get encoding for current locale:
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.getlocale()
('en_US', 'ISO8859-1')
Another modules that might be useful for you:
PyICU - a better way for internationalization. While locale produce either initial or inflected form of month name depending on locale database in your OS (so you can't rely on it for such languages like Russian!) and uses some encoding, PyICU has different format specifiers for initial and inflected form (so you can select appropriate in your case) and uses unicode.
pytils - a set of tools to work with Russian language, including dates. It has hard-coded month names as workaround for locale limitations.
A:
What you need is:
β¦
myencoding= locale.getpreferredencoding()
print repr(calendar.month_abbr[6].decode(myencoding))
β¦
|
How to get unicode month name in Python?
|
I am trying to get a unicode version of calendar.month_abbr[6]. If I don't specify an encoding for the locale, I don't know how to convert the string to unicode. The example code below shows my problem:
>>> import locale
>>> import calendar
>>> locale.setlocale(locale.LC_ALL, ("ru_RU"))
'ru_RU'
>>> print repr(calendar.month_abbr[6])
'\xb8\xee\xdd'
>>> print repr(calendar.month_abbr[6].decode("utf8"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 0: unexpected code byte
>>> locale.setlocale(locale.LC_ALL, ("ru_RU", "utf8"))
'ru_RU.UTF8'
>>> print repr(calendar.month_abbr[6])
'\xd0\x98\xd1\x8e\xd0\xbd'
>>> print repr(calendar.month_abbr[6].decode("utf8"))
u'\u0418\u044e\u043d'
Any ideas how to solve this? The solution doesn't have to look like this. Any solution that gives me the abbreviated month name in unicode is fine.
|
[
"Change the last line in your code:\n>>> print calendar.month_abbr[6].decode(\"utf8\")\nΠΡΠ½\n\nImproperly used repr() hides from you that you already get what you needed.\nAlso getlocale() can be used to get encoding for current locale:\n>>> locale.setlocale(locale.LC_ALL, 'en_US')\n'en_US'\n>>> locale.getlocale()\n('en_US', 'ISO8859-1')\n\nAnother modules that might be useful for you:\n\nPyICU - a better way for internationalization. While locale produce either initial or inflected form of month name depending on locale database in your OS (so you can't rely on it for such languages like Russian!) and uses some encoding, PyICU has different format specifiers for initial and inflected form (so you can select appropriate in your case) and uses unicode.\npytils - a set of tools to work with Russian language, including dates. It has hard-coded month names as workaround for locale limitations.\n\n",
"What you need is:\nβ¦\nmyencoding= locale.getpreferredencoding()\nprint repr(calendar.month_abbr[6].decode(myencoding))\nβ¦\n\n"
] |
[
12,
0
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0001821204_python_unicode.txt
|
Q:
Simple question about numpy matrix in python
Let's suppose I have a numpy matrix variable called MATRIX with 3 coordinates: (x, y, z).
Is acessing the matrix's value through the following code
myVar = MATRIX[0,0,0]
equal to
myVar = MATRIX[0,0][0]
or
myVar = MATRIX[0][0,0]
?
What about if I have the following code?
myTuple = (0,0)
myScalar = 0
myVar = MATRIX[myTuple, myScalar]
Is the last line equivalent to doing
myVar = MATRIX[myTuple[0], myTuple[1], myScalar]
I have done simple tests and it seems so, but maybe that is not so in all the cases. How do square brackets work in python with numpy matrices? Since day one I felt confused as how they work.
Thanks
A:
I assume you have a array instance rather than a matrix, since the latter only can have two dimensions.
m[0, 0, 0] gets the element at position (0, 0, 0).
m[0, 0] gets a whole subarray (a slice), which is itself a array. You can get the first element of this subarray like this: m[0, 0][0], which is why both syntaxes work (even though m[i, j, k] is preferred because it doesn't have the unnecessary intermediate step).
Take a look at this ipython session:
rbonvall@andy:~$ ipython
Python 2.5.4 (r254:67916, Sep 26 2009, 08:19:36)
[...]
In [1]: import numpy.random
In [2]: m = numpy.random.random(size=(3, 3, 3))
In [3]: m
Out[3]:
array([[[ 0.68853531, 0.8815277 , 0.53613676],
[ 0.9985735 , 0.56409085, 0.03887982],
[ 0.12083102, 0.0301229 , 0.51331851]],
[[ 0.73868543, 0.24904349, 0.24035031],
[ 0.15458694, 0.35570177, 0.22097202],
[ 0.81639051, 0.55742805, 0.5866573 ]],
[[ 0.90302482, 0.29878548, 0.90705737],
[ 0.68582033, 0.1988247 , 0.9308886 ],
[ 0.88956484, 0.25112987, 0.69732309]]])
In [4]: m[0, 0]
Out[4]: array([ 0.68853531, 0.8815277 , 0.53613676])
In [5]: m[0, 0][0]
Out[5]: 0.6885353066709865
It only works like this for numpy arrays. Python built-in tuples and lists are not indexable by tuples, just by integers.
A:
It's not possible to index a tuple with another tuple, so none of that code is valid.
|
Simple question about numpy matrix in python
|
Let's suppose I have a numpy matrix variable called MATRIX with 3 coordinates: (x, y, z).
Is acessing the matrix's value through the following code
myVar = MATRIX[0,0,0]
equal to
myVar = MATRIX[0,0][0]
or
myVar = MATRIX[0][0,0]
?
What about if I have the following code?
myTuple = (0,0)
myScalar = 0
myVar = MATRIX[myTuple, myScalar]
Is the last line equivalent to doing
myVar = MATRIX[myTuple[0], myTuple[1], myScalar]
I have done simple tests and it seems so, but maybe that is not so in all the cases. How do square brackets work in python with numpy matrices? Since day one I felt confused as how they work.
Thanks
|
[
"I assume you have a array instance rather than a matrix, since the latter only can have two dimensions.\nm[0, 0, 0] gets the element at position (0, 0, 0).\nm[0, 0] gets a whole subarray (a slice), which is itself a array. You can get the first element of this subarray like this: m[0, 0][0], which is why both syntaxes work (even though m[i, j, k] is preferred because it doesn't have the unnecessary intermediate step).\nTake a look at this ipython session:\nrbonvall@andy:~$ ipython\nPython 2.5.4 (r254:67916, Sep 26 2009, 08:19:36) \n[...]\n\nIn [1]: import numpy.random\n\nIn [2]: m = numpy.random.random(size=(3, 3, 3))\n\nIn [3]: m\nOut[3]: \narray([[[ 0.68853531, 0.8815277 , 0.53613676],\n [ 0.9985735 , 0.56409085, 0.03887982],\n [ 0.12083102, 0.0301229 , 0.51331851]],\n\n [[ 0.73868543, 0.24904349, 0.24035031],\n [ 0.15458694, 0.35570177, 0.22097202],\n [ 0.81639051, 0.55742805, 0.5866573 ]],\n\n [[ 0.90302482, 0.29878548, 0.90705737],\n [ 0.68582033, 0.1988247 , 0.9308886 ],\n [ 0.88956484, 0.25112987, 0.69732309]]])\n\nIn [4]: m[0, 0]\nOut[4]: array([ 0.68853531, 0.8815277 , 0.53613676])\n\nIn [5]: m[0, 0][0]\nOut[5]: 0.6885353066709865\n\nIt only works like this for numpy arrays. Python built-in tuples and lists are not indexable by tuples, just by integers.\n",
"It's not possible to index a tuple with another tuple, so none of that code is valid.\n"
] |
[
6,
1
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0001822417_numpy_python.txt
|
Q:
Python: Nested Loop
Consider this:
>>> a = [("one","two"), ("bad","good")]
>>> for i in a:
... for x in i:
... print x
...
one
two
bad
good
How can I write this code, but using a syntax like:
for i in a:
print [x for x in i]
Obviously, This does not work, it prints:
['one', 'two']
['bad', 'good']
I want the same output. Can it be done?
A:
List comprehensions and generators are only designed to be used as expressions, while printing is a statement. While you can effect what you're trying to do by doing
from __future__ import print_function
for x in a:
[print(each) for each in x]
doing so is amazingly unpythonic, and results in the generation of a list that you don't actually need. The best thing you could do would simply be to write the nested for loops in your original example.
A:
Given your example you could do something like this:
a = [("one","two"), ("bad","good")]
for x in sum(map(list, a), []):
print x
This can, however, become quite slow once the list gets big.
The better way to do it would be like Tim Pietzcker suggested:
from itertools import chain
for x in chain(*a):
print x
Using the star notation, *a, allows you to have n tuples in your list.
A:
>>> a = [("one","two"), ("bad","good")]
>>> print "\n".join(j for i in a for j in i)
one
two
bad
good
>>> for i in a:
... print "\n".join(i)
...
one
two
bad
good
A:
import itertools
for item in itertools.chain(("one","two"), ("bad","good")):
print item
will produce the desired output with just one for loop.
A:
The print function really is superior, but here is a much more pythonic suggestion inspired by Benjamin Pollack's answer:
from __future__ import print_function
for x in a:
print(*x, sep="\n")
Simply use * to unpack the list x as arguments to the function, and use newline separators.
A:
You'll need to define your own print method (or import __future__.print_function)
def pp(x): print x
for i in a:
_ = [pp(x) for x in i]
Note the _ is used to indicate that the returned list is to be ignored.
A:
This code is straightforward and simpler than other solutions here:
for i in a:
print '\n'.join([x for x in i])
A:
Not the best, but:
for i in a:
some_function([x for x in i])
def some_function(args):
for o in args:
print o
|
Python: Nested Loop
|
Consider this:
>>> a = [("one","two"), ("bad","good")]
>>> for i in a:
... for x in i:
... print x
...
one
two
bad
good
How can I write this code, but using a syntax like:
for i in a:
print [x for x in i]
Obviously, This does not work, it prints:
['one', 'two']
['bad', 'good']
I want the same output. Can it be done?
|
[
"List comprehensions and generators are only designed to be used as expressions, while printing is a statement. While you can effect what you're trying to do by doing\nfrom __future__ import print_function\nfor x in a:\n [print(each) for each in x]\n\ndoing so is amazingly unpythonic, and results in the generation of a list that you don't actually need. The best thing you could do would simply be to write the nested for loops in your original example.\n",
"Given your example you could do something like this:\na = [(\"one\",\"two\"), (\"bad\",\"good\")]\n\nfor x in sum(map(list, a), []):\n print x\n\nThis can, however, become quite slow once the list gets big.\nThe better way to do it would be like Tim Pietzcker suggested:\nfrom itertools import chain\n\nfor x in chain(*a):\n print x\n\nUsing the star notation, *a, allows you to have n tuples in your list.\n",
">>> a = [(\"one\",\"two\"), (\"bad\",\"good\")]\n>>> print \"\\n\".join(j for i in a for j in i)\none\ntwo\nbad\ngood\n\n\n\n>>> for i in a:\n... print \"\\n\".join(i)\n... \none\ntwo\nbad\ngood\n\n",
"import itertools\nfor item in itertools.chain((\"one\",\"two\"), (\"bad\",\"good\")):\n print item\n\nwill produce the desired output with just one for loop.\n",
"The print function really is superior, but here is a much more pythonic suggestion inspired by Benjamin Pollack's answer:\nfrom __future__ import print_function\nfor x in a:\n print(*x, sep=\"\\n\")\n\nSimply use * to unpack the list x as arguments to the function, and use newline separators.\n",
"You'll need to define your own print method (or import __future__.print_function)\ndef pp(x): print x\n\nfor i in a:\n _ = [pp(x) for x in i]\n\nNote the _ is used to indicate that the returned list is to be ignored.\n",
"This code is straightforward and simpler than other solutions here:\nfor i in a:\n print '\\n'.join([x for x in i])\n\n",
"Not the best, but:\nfor i in a:\n some_function([x for x in i])\n\ndef some_function(args):\n for o in args:\n print o\n\n"
] |
[
7,
7,
4,
3,
3,
1,
1,
0
] |
[] |
[] |
[
"loops",
"nested",
"python"
] |
stackoverflow_0001821471_loops_nested_python.txt
|
Q:
Need a Python package suitable for visualizing queue simulations
I am working on a simulation in Queueing Theory, within a wxPython GUI. (Project link.) What would be a good tool for visualizing the simulations? The visualization should consist of simple objects, such as clients, servers, a facility and a population. They should all be represented by simple boxes or something like that. There will be several queues in which clients will wait.
Since this is a visualization of a progressing simulation, objects will move around the screen, and it would be nice if they could move smoothly from one place to another, and not jump abruptly.
What would be a good tool to create that visualization? I could do it in native wxPython graphics. I could also use PyGame. But maybe someone here has something better to recommend?
A:
Have you considered using NS3? It may be a little more than what you're looking for, but it is the standard for open source queue simulations. Here's the documentation on Python bindings for NS3.
A:
Here's a list of some 2D Graphics packages you might consider:
http://www.vrplumber.com/py3d.py?category=graphics
A:
wxPython has the OGL (Object Graphics Library) for doing this sort of thing. I have not used it so I don't know how useful or robust it is, but it should be easier than using raw wx graphics primitives.
It is in wx.lib.ogl.
A:
You could try using one of the Python bindings for GraphViz. I could see something like this http://www.graphviz.org/Gallery/directed/cluster.html being used to illustrate a queue simulation.
I use Pydot and its gret:
http://code.google.com/p/pydot/
The only problem is that Pydot only writes the GraphViz files, you would have to use GraphViz itself or other renderer (such as Canviz http://www.ryandesign.com/canviz/) to obtain the graphics.
The advantage is that you just have to defined the structure of the graph and forget about time-consuming details such as line routing, drawing, etc.
Hope it helps
A:
I would consider using VPython. You could also create a dynamic graphic in Java using Processing, and have the simulation send update messages through your network protocol of choice.
|
Need a Python package suitable for visualizing queue simulations
|
I am working on a simulation in Queueing Theory, within a wxPython GUI. (Project link.) What would be a good tool for visualizing the simulations? The visualization should consist of simple objects, such as clients, servers, a facility and a population. They should all be represented by simple boxes or something like that. There will be several queues in which clients will wait.
Since this is a visualization of a progressing simulation, objects will move around the screen, and it would be nice if they could move smoothly from one place to another, and not jump abruptly.
What would be a good tool to create that visualization? I could do it in native wxPython graphics. I could also use PyGame. But maybe someone here has something better to recommend?
|
[
"Have you considered using NS3? It may be a little more than what you're looking for, but it is the standard for open source queue simulations. Here's the documentation on Python bindings for NS3.\n",
"Here's a list of some 2D Graphics packages you might consider:\nhttp://www.vrplumber.com/py3d.py?category=graphics\n",
"wxPython has the OGL (Object Graphics Library) for doing this sort of thing. I have not used it so I don't know how useful or robust it is, but it should be easier than using raw wx graphics primitives.\nIt is in wx.lib.ogl.\n",
"You could try using one of the Python bindings for GraphViz. I could see something like this http://www.graphviz.org/Gallery/directed/cluster.html being used to illustrate a queue simulation.\nI use Pydot and its gret:\nhttp://code.google.com/p/pydot/\nThe only problem is that Pydot only writes the GraphViz files, you would have to use GraphViz itself or other renderer (such as Canviz http://www.ryandesign.com/canviz/) to obtain the graphics.\nThe advantage is that you just have to defined the structure of the graph and forget about time-consuming details such as line routing, drawing, etc.\nHope it helps\n",
"I would consider using VPython. You could also create a dynamic graphic in Java using Processing, and have the simulation send update messages through your network protocol of choice.\n"
] |
[
1,
0,
0,
0,
0
] |
[] |
[] |
[
"python",
"scientific_computing",
"simulation",
"visualization",
"wxpython"
] |
stackoverflow_0001820939_python_scientific_computing_simulation_visualization_wxpython.txt
|
Q:
Find and replace multiple strings in file then output to new filename python
I am looking to create a python script that will read one source file then produce another file with a string for the name.
for example
macaddress.cnf.xml contains the source file
I need to change '6000' to '6001' in multiple places of macaddress.cnf.xml, then I want to output to newmacaddress.cnf.xl.
This is what I have
#! /usr/bin/python
#read and write to file
f = open(file)
for line in f:
if line.contains('66001'):
newline = line.replace('66001', '60001')
To add I would like to be able to do this with a csv or whatever and have the script run through and do
60002 >> macaddressfromcsv.cnf.xml
60003 >> macaddressfromcsv.cnf.xml
60004 etc.
Sorry I am very new to this any help would be great.
A:
It is unclear from your question what all of your goals are, but I will try to address some of them. If you want to take input from one file, modify it, and then write to another file you could do following:
buffer = "";
with open("input_file") as in:
buffer = in.read();
# do modifications ...
with open("output_file", 'w') as out:
out.write(buffer);
Note: you would need to use from __future__ import with_statement in python version 2.5.
To do multiple replacements you can actually use re.sub() function:
buffer = re.sub('6000', '6001', buffer)
As to the the additional information using csv, please provide a more detailed explanation or an example of what you are trying to achieve.
A:
data=open("input_file").read()
outfile=open("macaddressfromcsv.cnf.xml","w")
for i in range(6001,6010):
outfile.write(data.replace("6000",str(i))
outfile.write("\n") # you may not need this
outfile.close()
Edit. I think you need to clarify the question. Is there only one output file or to you want one file per replacement?
|
Find and replace multiple strings in file then output to new filename python
|
I am looking to create a python script that will read one source file then produce another file with a string for the name.
for example
macaddress.cnf.xml contains the source file
I need to change '6000' to '6001' in multiple places of macaddress.cnf.xml, then I want to output to newmacaddress.cnf.xl.
This is what I have
#! /usr/bin/python
#read and write to file
f = open(file)
for line in f:
if line.contains('66001'):
newline = line.replace('66001', '60001')
To add I would like to be able to do this with a csv or whatever and have the script run through and do
60002 >> macaddressfromcsv.cnf.xml
60003 >> macaddressfromcsv.cnf.xml
60004 etc.
Sorry I am very new to this any help would be great.
|
[
"It is unclear from your question what all of your goals are, but I will try to address some of them. If you want to take input from one file, modify it, and then write to another file you could do following: \nbuffer = \"\";\nwith open(\"input_file\") as in:\n buffer = in.read();\n\n# do modifications ...\n\nwith open(\"output_file\", 'w') as out:\n out.write(buffer);\n\nNote: you would need to use from __future__ import with_statement in python version 2.5.\nTo do multiple replacements you can actually use re.sub() function:\nbuffer = re.sub('6000', '6001', buffer)\n\nAs to the the additional information using csv, please provide a more detailed explanation or an example of what you are trying to achieve.\n",
"data=open(\"input_file\").read()\noutfile=open(\"macaddressfromcsv.cnf.xml\",\"w\")\nfor i in range(6001,6010):\n outfile.write(data.replace(\"6000\",str(i))\n outfile.write(\"\\n\") # you may not need this\noutfile.close()\n\nEdit. I think you need to clarify the question. Is there only one output file or to you want one file per replacement?\n"
] |
[
1,
0
] |
[] |
[] |
[
"full_text_search",
"python",
"replace"
] |
stackoverflow_0001822307_full_text_search_python_replace.txt
|
Q:
Python integer to read-only buffer
I am using cdb for a constant database in python. I would like to associate integer id's with some strings, and I would like to avoid storing each of these integer id's as strings, and instead store them as an integer. cdb though is looking for either a string or a read only buffer. Is there a way that I can store these keys as integers instead of strings?
For example:
cdb = cdb.cdbmake("test.cdb","test.cdb.tmp")
key = 5
value = "some test string"
#this throws an error
maker.add(key,value)
#TypeError: add() argument 1 must be string or read-only buffer, not int
#this would work, but seems inefficient
maker.add(str(key),value)
A:
According to the cdb website the database only takes strings as keys
A cdb is an associative array: it maps strings (keys) to strings (data).
So you will have to convert the integers to strings first. I suggest you wrap the str in a utility function and forget about the overhead.
|
Python integer to read-only buffer
|
I am using cdb for a constant database in python. I would like to associate integer id's with some strings, and I would like to avoid storing each of these integer id's as strings, and instead store them as an integer. cdb though is looking for either a string or a read only buffer. Is there a way that I can store these keys as integers instead of strings?
For example:
cdb = cdb.cdbmake("test.cdb","test.cdb.tmp")
key = 5
value = "some test string"
#this throws an error
maker.add(key,value)
#TypeError: add() argument 1 must be string or read-only buffer, not int
#this would work, but seems inefficient
maker.add(str(key),value)
|
[
"According to the cdb website the database only takes strings as keys\n\nA cdb is an associative array: it maps strings (keys) to strings (data).\n\nSo you will have to convert the integers to strings first. I suggest you wrap the str in a utility function and forget about the overhead.\n"
] |
[
4
] |
[] |
[] |
[
"binary",
"cdb",
"python"
] |
stackoverflow_0001822709_binary_cdb_python.txt
|
Q:
How do I send and receive real-time signals `sigqueue()` in Python?
Python provides a signals module and os.kill; does it have a facility for sigqueue() (real-time signals with attached data)? What are the alternatives?
A:
You could do it with ctypes
>>> from ctypes import *
>>> c = cdll.LoadLibrary("libc.so.6")
>>> c.sigqueue
<_FuncPtr object at 0xb7dbd77c>
>>> c.sigqueue(100, 10, 0)
-1
>>>
You'll have to look up how to make a union in ctypes which I've never done before but I think is possible.
A:
One alternative, if no one has done it yet, would be to wrap the C library yourself - should be pretty quick and painless. Look here for more details.
|
How do I send and receive real-time signals `sigqueue()` in Python?
|
Python provides a signals module and os.kill; does it have a facility for sigqueue() (real-time signals with attached data)? What are the alternatives?
|
[
"You could do it with ctypes\n>>> from ctypes import *\n>>> c = cdll.LoadLibrary(\"libc.so.6\")\n>>> c.sigqueue\n<_FuncPtr object at 0xb7dbd77c>\n>>> c.sigqueue(100, 10, 0)\n-1\n>>>\n\nYou'll have to look up how to make a union in ctypes which I've never done before but I think is possible.\n",
"One alternative, if no one has done it yet, would be to wrap the C library yourself - should be pretty quick and painless. Look here for more details.\n"
] |
[
3,
2
] |
[] |
[] |
[
"ipc",
"python",
"signals",
"sigqueue",
"unix"
] |
stackoverflow_0001822449_ipc_python_signals_sigqueue_unix.txt
|
Q:
Parsing dates from free-text input in Python
I'm about to start working on a simple calendar app for a website I'm working on (using Django, but that fact's probably not relevant).
I'd like users to be able to enter when an event is in a text box like this:
Every Sunday evening at 7pm
Next Friday
Tuesday 1st Dec 2009
and have my application begin to make some guesses as to when they mean. I don't need it to promise to be right, just to be able to present the users with some guesses as to what they mean. Is there a Python library that does some of this? Bonus points if it's extensible to match more formats.
I don't care too much about timezones - for the purposes of my application it's safe to assume any times are in whatever timezone London happens to be in. I'll work that out once I've got some kind of yyyymmddhhiiss representation (or similar).
Apologies if there's a duplicate I've missed - I did have a look.
A:
There is http://code.google.com/p/parsedatetime/
A:
I proposed a pyparsing solution to this question, which seems similar to yours.
|
Parsing dates from free-text input in Python
|
I'm about to start working on a simple calendar app for a website I'm working on (using Django, but that fact's probably not relevant).
I'd like users to be able to enter when an event is in a text box like this:
Every Sunday evening at 7pm
Next Friday
Tuesday 1st Dec 2009
and have my application begin to make some guesses as to when they mean. I don't need it to promise to be right, just to be able to present the users with some guesses as to what they mean. Is there a Python library that does some of this? Bonus points if it's extensible to match more formats.
I don't care too much about timezones - for the purposes of my application it's safe to assume any times are in whatever timezone London happens to be in. I'll work that out once I've got some kind of yyyymmddhhiiss representation (or similar).
Apologies if there's a duplicate I've missed - I did have a look.
|
[
"There is http://code.google.com/p/parsedatetime/ \n",
"I proposed a pyparsing solution to this question, which seems similar to yours.\n"
] |
[
4,
2
] |
[] |
[] |
[
"datetime",
"python"
] |
stackoverflow_0001822787_datetime_python.txt
|
Q:
Set and use flags against a users profile model in Django
I have a simple webapp in Django for an iPhone app.
I want to prompt the user to review our product, but just once. I then don't want to show that prompt again.
So would the best practise way of implementing this to be to add a new entry to the user profile model with a bolean field: "reviewed" - and then set that flag when the user completes the action?
I would then check for that entry in my template and display or not, the prompt.
I've not yet worked with database models, extended the user model, or saved to custom DB fields, so any thoughts or examples on this would be most welcome. I'm a little nervous as my site has live users and I won't want to break the user tables.
A:
If you are using MySQLΒ or PostgreSQL, you can do some ALTERΒ TABLE without loosing any data.
In Django, it is quite easy to add a profile for the user.
Make sure, to create the profile if it doesn't exist :
try:
profile = request.user.get_profile()
except UserProfile.DoesNotExist:
# If DoesNotExists, Create an empty one
profile = UserProfile(user=request.user)
profile.save()
More information here :
http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
http://www.djangobook.com/en/1.0/chapter12/#cn222
A:
There are a variety of ways to do this. I suggest the following:
Django has a messaging framework, built by design to show messages to users only once when the software creates them. Whenever X is created/modified/deleted etc, you can add the message to the user via User.message_set.create(message='Whatever you like'). This will be shown to the user once. This relies on django sessions, which I assume you're using since you're relying on the built-in user model. These messages are stored in auth_message.
HTH
|
Set and use flags against a users profile model in Django
|
I have a simple webapp in Django for an iPhone app.
I want to prompt the user to review our product, but just once. I then don't want to show that prompt again.
So would the best practise way of implementing this to be to add a new entry to the user profile model with a bolean field: "reviewed" - and then set that flag when the user completes the action?
I would then check for that entry in my template and display or not, the prompt.
I've not yet worked with database models, extended the user model, or saved to custom DB fields, so any thoughts or examples on this would be most welcome. I'm a little nervous as my site has live users and I won't want to break the user tables.
|
[
"If you are using MySQLΒ or PostgreSQL, you can do some ALTERΒ TABLE without loosing any data.\nIn Django, it is quite easy to add a profile for the user.\nMake sure, to create the profile if it doesn't exist :\ntry:\n profile = request.user.get_profile()\nexcept UserProfile.DoesNotExist:\n # If DoesNotExists, Create an empty one\n profile = UserProfile(user=request.user)\n profile.save()\n\nMore information here : \n\nhttp://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users \nhttp://www.djangobook.com/en/1.0/chapter12/#cn222\n\n",
"There are a variety of ways to do this. I suggest the following:\nDjango has a messaging framework, built by design to show messages to users only once when the software creates them. Whenever X is created/modified/deleted etc, you can add the message to the user via User.message_set.create(message='Whatever you like'). This will be shown to the user once. This relies on django sessions, which I assume you're using since you're relying on the built-in user model. These messages are stored in auth_message.\nHTH\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0001823372_django_django_models_python.txt
|
Q:
incorrect function being called on multiple fast calls to python's threading.Thread()
I'm having some problems with launching threads from a list of functions. They are in a list because they are configuration-specific functions. I'm wrappering the functions so that I can store the results of the functions in 'self', but something is going wrong in a non-threadsafe way that I get the right number of threads started, but some instances aren't the right function. Here's the example code:
import threading, time
class runParallelTest():
def __init__(self):
pass
def runList(self, functionList):
threadList = []
for functionListIndex in range(0, len(functionList)):
newThread = threading.Thread(target=lambda:self._run_parallel_job(functionList[functionListIndex]))
newThread.start()
threadList.append(newThread)
# sleep delay that makes it all work fine.
#time.sleep(2)
# We wait for all the threads to complete and if any of them
# doesn't we report a failure.
for thread in threadList:
thread.join(3600*24) # 1 day better be enough
if thread.isAlive() == True:
raise Exception("thread.isAlive==True")
def _run_parallel_job(self, function):
results = function()
# store the results in a threadsafe way in self
# (I promise I'm using semaphores)
def f(x):
print "f(%d) run" % x
return x
if __name__ == '__main__':
rp = runParallelTest()
functionList = [
lambda:f(0),
lambda:f(1),
lambda:f(2),
lambda:f(3),
lambda:f(4),
lambda:f(5),
lambda:f(6),
lambda:f(7),
]
rp.runList(functionList)
When I run, I see things like this:
> python thread_problem.py
f(0) run
f(1) run
f(2) run
f(4) run
f(5) run
f(5) run
f(6) run
f(7) run
>
While I expect different orders in the prints, I think I should see the numbers 0-7 with no repeats, but I don't. If I add the time.sleep(2), the problem magically goes away, but I'd really like to understand why it doesn't work the way I think it should.
Thanks a bunch!
A:
The problem is that functionList[functionListIndex] is evaluated only when the lambda it is in is run (within the thread). By then the value of functionListIndex can change.
To fix this, you can pass a parameter to the lambda that will be evaluated at definition time:
newThread = threading.Thread(target=lambda func=functionList[functionListIndex]: self._run_parallel_job(func))
Since default parameter values to functions are evaluated at definition time, this will work.
A more Pythonic solution is to avoid the lambda and use the args parameter:
newThread = threading.Thread(target=self._run_parallel_job, args=(functionList[functionListIndex],))
|
incorrect function being called on multiple fast calls to python's threading.Thread()
|
I'm having some problems with launching threads from a list of functions. They are in a list because they are configuration-specific functions. I'm wrappering the functions so that I can store the results of the functions in 'self', but something is going wrong in a non-threadsafe way that I get the right number of threads started, but some instances aren't the right function. Here's the example code:
import threading, time
class runParallelTest():
def __init__(self):
pass
def runList(self, functionList):
threadList = []
for functionListIndex in range(0, len(functionList)):
newThread = threading.Thread(target=lambda:self._run_parallel_job(functionList[functionListIndex]))
newThread.start()
threadList.append(newThread)
# sleep delay that makes it all work fine.
#time.sleep(2)
# We wait for all the threads to complete and if any of them
# doesn't we report a failure.
for thread in threadList:
thread.join(3600*24) # 1 day better be enough
if thread.isAlive() == True:
raise Exception("thread.isAlive==True")
def _run_parallel_job(self, function):
results = function()
# store the results in a threadsafe way in self
# (I promise I'm using semaphores)
def f(x):
print "f(%d) run" % x
return x
if __name__ == '__main__':
rp = runParallelTest()
functionList = [
lambda:f(0),
lambda:f(1),
lambda:f(2),
lambda:f(3),
lambda:f(4),
lambda:f(5),
lambda:f(6),
lambda:f(7),
]
rp.runList(functionList)
When I run, I see things like this:
> python thread_problem.py
f(0) run
f(1) run
f(2) run
f(4) run
f(5) run
f(5) run
f(6) run
f(7) run
>
While I expect different orders in the prints, I think I should see the numbers 0-7 with no repeats, but I don't. If I add the time.sleep(2), the problem magically goes away, but I'd really like to understand why it doesn't work the way I think it should.
Thanks a bunch!
|
[
"The problem is that functionList[functionListIndex] is evaluated only when the lambda it is in is run (within the thread). By then the value of functionListIndex can change.\nTo fix this, you can pass a parameter to the lambda that will be evaluated at definition time:\nnewThread = threading.Thread(target=lambda func=functionList[functionListIndex]: self._run_parallel_job(func))\n\nSince default parameter values to functions are evaluated at definition time, this will work.\nA more Pythonic solution is to avoid the lambda and use the args parameter:\nnewThread = threading.Thread(target=self._run_parallel_job, args=(functionList[functionListIndex],))\n\n"
] |
[
1
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0001823493_multithreading_python.txt
|
Q:
Debugging Pyparsing Grammar
I'm building a parser for an imaginary programming language called C-- (not the actual C-- language). I've gotten to the stage where I need to translate the language's grammar into something Pyparsing can accept. Unfortunatly when I come to parse my input string (which is correct and should not cause Pyparsing to error) it's not parsing correctly. I fear this is due to errors in my grammar, but as I'm starting Pyparsing for the first time, I can't seem to see where I'm going wrong.
I've uploaded the grammar that I'm translating from here for people to have a read through.
EDIT: Updated with the advice from Paul.
This is the grammer I've currently got (the two top lines of Syntax definition are terribly bad of me I know):
# Lexical structure definition
ifS = Keyword('if')
elseS = Keyword('else')
whileS = Keyword('while')
returnS = Keyword('return')
intVar = Keyword('int')
voidKeyword = Keyword('void')
sumdiff = Literal('+') | Literal('-')
prodquot = Literal('*') | Literal('/')
relation = Literal('<=') | Literal('<') | Literal('==') | \
Literal('!=') | Literal('>') | Literal('=>')
lbrace = Literal('{')
rbrace = Literal('}')
lparn = Literal('(')
rparn = Literal(')')
semi = Literal(';')
comma = Literal(',')
number = Word(nums)
identifier = Word(alphas, alphanums)
# Syntax definition
term = ''
statement = ''
variable = intVar + identifier + semi
locals = ZeroOrMore(variable)
expr = term | OneOrMore(Group(sumdiff + term))
args = ZeroOrMore(OneOrMore(Group(expr + comma)) | expr)
funccall = Group(identifier + lparn + args + rparn)
factor = Group(lparn + expr + rparn) | identifier | funccall | number
term = factor | OneOrMore(prodquot + factor)
cond = Group(lparn + expr + relation + expr + rparn)
returnState = Group(returnS + semi) | Combine(returnS + expr + semi)
assignment = Group(identifier + '=' + expr + semi)
proccall = Group(identifier + lparn + args + rparn + semi)
block = Group(lbrace + locals + statement + rbrace)
iteration = Group(whileS + cond + block)
selection = Group(ifS + cond + block) | Group(ifS + cond + block + elseS + block)
statement = OneOrMore(proccall | assignment | selection | iteration | returnState)
param = Group(intVar + identifier)
paramlist = OneOrMore(Combine(param + comma)) | param
params = paramlist | voidKeyword
procedure = Group(voidKeyword + identifier + lparn + params + rparn + block)
function = Group(intVar + identifier + lparn + params + rparn + block)
declaration = variable | function | procedure
program = OneOrMore(declaration)
I'd like to know if there are any mistakes I've made in translating the grammar across and what improvements I could do to make it simplified whilst adhering to the grammar I've been given.
EDIT 2: Updated to include the new error.
Here is the input string I am parsing:
int larger ( int first , int second ) {
if ( first > second ) {
return first ;
} else {
return second ;
}
}
void main ( void ) {
int count ;
int sum ;
int max ;
int x ;
x = input ( ) ;
max = x ;
sum = 0 ;
count = 0 ;
while ( x != 0 ) {
count = count + 1 ;
sum = sum + x ;
max = larger ( max , x ) ;
x = input ( ) ;
}
output ( count ) ;
output ( sum ) ;
output ( max ) ;
}
And this is the error message I get when running my program from Terminal:
/Users/Joe/Documents/Eclipse Projects/Parser/src/pyparsing.py:1156: SyntaxWarning: null string passed to Literal; use Empty() instead
other = Literal( other )
/Users/Joe/Documents/Eclipse Projects/Parser/src/pyparsing.py:1258: SyntaxWarning: null string passed to Literal; use Empty() instead
other = Literal( other )
Expected ")" (at char 30), (line:6, col:26)
None
A:
1) Change Literal("if") to Keyword("if") (and so on, down to Literal("void")), to prevent matching the leading "if" of a variable named "ifactor".
2) nums, alphas, and alphanums are not expressions, they are strings, that can be used with the Word class to define some typical sets of characters when defining "words" like "a number is a word made up of nums", or "an identifier is a word that starts with an alpha, followed by zero or more alphanums." So instead of:
number = nums
identifier = alphas + OneOrMore(alphanums)
you want
number = Word(nums)
identifier = Word(alphas, alphanums)
3) Instead of Combine, I think you want Group. Use Combine when you want the matched tokens to be contiguous with no intervening whitespace, and will concatenate the tokens and return them as a single string. Combine is often used in cases like this:
realnum = Combine(Word(nums) + "." + Word(nums))
Without Combine, parsing "3.14" would return the list of strings ['3', '.', '14'], so we add Combine so that the parsed result for realnum is '3.14' (which you could then pass to a parse action to convert to the actual floating value 3.14). Combines enforcement of no intervening whitespace also keeps us from accidentally parsing 'The answer is 3. 10 is too much.' and thinking the "3. 10" represents a real number.
4) This should not cause your error, but your input string has lots of extra spaces. If you get your grammar working, you should be able to parse "int x;" just as well as "int x ;".
Hope some of these hints get you going. Have you read any online pyparsing articles or tutorials? And please look through the online examples. You'll need to get a good grasp of how Word, Literal, Combine, etc. perform their individual parsing tasks.
5) You have mis-implemented the recursive definitions for term and statement. Instead of assigning '' to them, write:
term = Forward()
statement = Forward()
Then when you go to actually define them with their recursive definitions, use the << operator (and be sure to enclose the RHS in ()'s).
term << (... term definition ...)
statement << (... statement definition ...)
You can find an example of a recursive parser here, and a presentation on basic pyparsing usage here - see the section titled "Parsing Lists" for more step-by-step on how the recursion is handled.
|
Debugging Pyparsing Grammar
|
I'm building a parser for an imaginary programming language called C-- (not the actual C-- language). I've gotten to the stage where I need to translate the language's grammar into something Pyparsing can accept. Unfortunatly when I come to parse my input string (which is correct and should not cause Pyparsing to error) it's not parsing correctly. I fear this is due to errors in my grammar, but as I'm starting Pyparsing for the first time, I can't seem to see where I'm going wrong.
I've uploaded the grammar that I'm translating from here for people to have a read through.
EDIT: Updated with the advice from Paul.
This is the grammer I've currently got (the two top lines of Syntax definition are terribly bad of me I know):
# Lexical structure definition
ifS = Keyword('if')
elseS = Keyword('else')
whileS = Keyword('while')
returnS = Keyword('return')
intVar = Keyword('int')
voidKeyword = Keyword('void')
sumdiff = Literal('+') | Literal('-')
prodquot = Literal('*') | Literal('/')
relation = Literal('<=') | Literal('<') | Literal('==') | \
Literal('!=') | Literal('>') | Literal('=>')
lbrace = Literal('{')
rbrace = Literal('}')
lparn = Literal('(')
rparn = Literal(')')
semi = Literal(';')
comma = Literal(',')
number = Word(nums)
identifier = Word(alphas, alphanums)
# Syntax definition
term = ''
statement = ''
variable = intVar + identifier + semi
locals = ZeroOrMore(variable)
expr = term | OneOrMore(Group(sumdiff + term))
args = ZeroOrMore(OneOrMore(Group(expr + comma)) | expr)
funccall = Group(identifier + lparn + args + rparn)
factor = Group(lparn + expr + rparn) | identifier | funccall | number
term = factor | OneOrMore(prodquot + factor)
cond = Group(lparn + expr + relation + expr + rparn)
returnState = Group(returnS + semi) | Combine(returnS + expr + semi)
assignment = Group(identifier + '=' + expr + semi)
proccall = Group(identifier + lparn + args + rparn + semi)
block = Group(lbrace + locals + statement + rbrace)
iteration = Group(whileS + cond + block)
selection = Group(ifS + cond + block) | Group(ifS + cond + block + elseS + block)
statement = OneOrMore(proccall | assignment | selection | iteration | returnState)
param = Group(intVar + identifier)
paramlist = OneOrMore(Combine(param + comma)) | param
params = paramlist | voidKeyword
procedure = Group(voidKeyword + identifier + lparn + params + rparn + block)
function = Group(intVar + identifier + lparn + params + rparn + block)
declaration = variable | function | procedure
program = OneOrMore(declaration)
I'd like to know if there are any mistakes I've made in translating the grammar across and what improvements I could do to make it simplified whilst adhering to the grammar I've been given.
EDIT 2: Updated to include the new error.
Here is the input string I am parsing:
int larger ( int first , int second ) {
if ( first > second ) {
return first ;
} else {
return second ;
}
}
void main ( void ) {
int count ;
int sum ;
int max ;
int x ;
x = input ( ) ;
max = x ;
sum = 0 ;
count = 0 ;
while ( x != 0 ) {
count = count + 1 ;
sum = sum + x ;
max = larger ( max , x ) ;
x = input ( ) ;
}
output ( count ) ;
output ( sum ) ;
output ( max ) ;
}
And this is the error message I get when running my program from Terminal:
/Users/Joe/Documents/Eclipse Projects/Parser/src/pyparsing.py:1156: SyntaxWarning: null string passed to Literal; use Empty() instead
other = Literal( other )
/Users/Joe/Documents/Eclipse Projects/Parser/src/pyparsing.py:1258: SyntaxWarning: null string passed to Literal; use Empty() instead
other = Literal( other )
Expected ")" (at char 30), (line:6, col:26)
None
|
[
"1) Change Literal(\"if\") to Keyword(\"if\") (and so on, down to Literal(\"void\")), to prevent matching the leading \"if\" of a variable named \"ifactor\".\n2) nums, alphas, and alphanums are not expressions, they are strings, that can be used with the Word class to define some typical sets of characters when defining \"words\" like \"a number is a word made up of nums\", or \"an identifier is a word that starts with an alpha, followed by zero or more alphanums.\" So instead of: \nnumber = nums\nidentifier = alphas + OneOrMore(alphanums)\n\nyou want\nnumber = Word(nums)\nidentifier = Word(alphas, alphanums)\n\n3) Instead of Combine, I think you want Group. Use Combine when you want the matched tokens to be contiguous with no intervening whitespace, and will concatenate the tokens and return them as a single string. Combine is often used in cases like this:\nrealnum = Combine(Word(nums) + \".\" + Word(nums))\n\nWithout Combine, parsing \"3.14\" would return the list of strings ['3', '.', '14'], so we add Combine so that the parsed result for realnum is '3.14' (which you could then pass to a parse action to convert to the actual floating value 3.14). Combines enforcement of no intervening whitespace also keeps us from accidentally parsing 'The answer is 3. 10 is too much.' and thinking the \"3. 10\" represents a real number.\n4) This should not cause your error, but your input string has lots of extra spaces. If you get your grammar working, you should be able to parse \"int x;\" just as well as \"int x ;\".\nHope some of these hints get you going. Have you read any online pyparsing articles or tutorials? And please look through the online examples. You'll need to get a good grasp of how Word, Literal, Combine, etc. perform their individual parsing tasks.\n5) You have mis-implemented the recursive definitions for term and statement. Instead of assigning '' to them, write:\nterm = Forward()\nstatement = Forward()\n\nThen when you go to actually define them with their recursive definitions, use the << operator (and be sure to enclose the RHS in ()'s).\nterm << (... term definition ...)\nstatement << (... statement definition ...)\n\nYou can find an example of a recursive parser here, and a presentation on basic pyparsing usage here - see the section titled \"Parsing Lists\" for more step-by-step on how the recursion is handled.\n"
] |
[
33
] |
[] |
[] |
[
"pyparsing",
"python"
] |
stackoverflow_0001823427_pyparsing_python.txt
|
Q:
which is a better language (C++ or Python) for complex problem solving exercises (ex. Graphs)?
I am trying to work on some problems and algorithms. I know C++ but a friend told me that it would be better if done with Python.As it would be much faster to develop and less time is spent in programming details which does not actually earn anything solution wise.
EDIT 2: I plan to use python-graph lib from Google-codes, Please provide example codes if you have used it.
EDIT 1: faster - less time && less work to code the solution
Thank you all for your help !
A:
I think you're looking for Python, because you can:
Focus on the algorithms themselves and not have to worry about other detail like memory management.
Do more with less code
The syntax is almost like working with pseudo code.
There is great built in language support for lists, tuples, list comprehensions, etc...
But more specifically...
If by better you mean speed of development, then chose Python.
If by better you mean sheer execution speed, then chose C++.
A:
Instead of focusing on the language, you should focus on the libraries available to you.
You shouldn't write your own graph library when there are already plenty (read, "too many") available, both in C++ and in Python. [Stack Overflow has a list of Python Graph packages with recommendations that you should check out. I didn't find an equivalent question for C++. You could start one.] Also, unless this is an academic excercise or research on truly novel graph algorithms, you should browse through the libraries available to see if any of them already implement those algorithms of interest to you.
Using libraries mitigate the gain of the higher level language of Python, since you won't be working with raw C++ per se, but with a C++ library. Since the Python language has a very small core, it is fairly easy to learn, however, it still takes time. You will need factor in that additional time on top of learning a library, if you choose the Python route, so make sure to weigh that in your decision.
Thus, given you already know C++, you may ultimately find it faster to develop in C++, since you only have to commit the time necessary to learn the library, not a library plus a newβalbeit easy to learnβlanguage.
A:
A bit subjective, but I'd vote for python because it has good libraries and abstracts a lot of the low level 'detail' that you'd have to consider when using c++...
A:
I did all my algorithms work in college in C++ because I knew it.
If I'd had to learn a language at the same time, I would have picked Python most likely.
A:
I am under the impression that it really depends from what you mean by faster.
Faster to develop: go python.
Faster to run: go C++.
However python can use a lot of external C libraries, so the difference in processing time might not be that relevant, depending on the type of implementation.
A:
At my university the 500 students in the "Algorithms and Datastructures" class get to choose the language they want.
Python is by far the most popular choice there, and personally I'm happy I also chose that, even though I already knew C++.
A:
Agree with your friend - use Python and put them within a unit test framework.
I worked for a number of years with scientists who did a lot of their algorithmic work in Python.
The example below shows typical tests (the import statement is for the stuff being tested), with a couple of niceties that might save you some time.
The business with the save and restore of sys.path is so you can have all your tests sitting in a directory adjacent to the src directory, without having to install the source into your main Python modules.
This test script is written so it can be imported into a larger suite of unit tests or simply run with python thisfile.py.
#!/usr/bin/python
"""
VRML Writer tests
"""
import unittest
import os
import sys
if __name__ == '__main__':
global save_syspath
save_syspath = sys.path
sys.path = [os.path.abspath("../src/")] + sys.path
from cgtools.VizValueTools import *
if __name__ == '__main__':
sys.path = save_syspath # RESTORE SYS.PATH
# use some common constants to make tests easier
MINV = 0.002
MAXV = 12.789
class TestColdHotColorGeneration(unittest.TestCase):
def testGeneratesLimitValues(self):
assert generateColdHotColorValue(MINV, MAXV, MINV) == (0.0, 0.0, 1.0)
assert generateColdHotColorValue(MINV, MAXV, MAXV) == (1.0, 0.0, 0.0)
assert generateColdHotColorValue(0, 0, 0) == (1.0, 0.0, 0.0) # cope with weird case where range is effectively one value, should be always top
def testGeneratesLimitValuesWithClipping(self):
assert generateColdHotColorValue(MINV, MAXV, MINV - 1.2) == (0.0, 0.0, 1.0)
assert generateColdHotColorValue(MINV, MAXV, MAXV + 49) == (1.0, 0.0, 0.0)
def testGeneratesMiddleValue(self):
"""
Note to be careful picking values so your value IS in the middle,
to generate pure green
"""
assert generateColdHotColorValue(1.0, 3.0, 2.0) == (0.0, 1.0, 0.0)
if __name__ == '__main__':
# When this module is executed from the command-line, run all its tests
unittest.main()
A:
I would go for python. And if you really need the performance, then you can always write C/C++ extensions and use them in python.
A:
Algorithms are fine in Python (allthough you can only fly one OS scheduled python thread due to the global lock); however, when it comes to data structures + algorithms you need fixed complexity guarantees, and this case you mix Python with C.
I suppose what I have said applies more to long running computations. You can emulate data structures on-top of the python hashmap primitive.
A:
I also vote for python. When do algorithm, we tend to work on the algorithm itself rather than language, low level details. Basically, we works on abstraction level. And using python, we're less likely to be side-tracked.
But if you're very familiar and comfortable with C++ and can use it freely to express your idea, just use it.
A:
With C++, you'd sometimes be concentrating more on the language issues than the problem itself, so Python. I'd even be recommending you do it in a higher-level language like Matlab (although the language itself can be a bit ugly).
A:
If using C++ means that STL is fair game, I'd say that it deserves serious consideration. STL is a fantastic library, combining structures, iterators, and algorithms. I love the Python recommendations, but if I could use STL I'd reconsider C++.
A:
Remember that Python is compiled to bytecode and then interpreted in a VM. So, in performance isn't better (faster) than C++.
|
which is a better language (C++ or Python) for complex problem solving exercises (ex. Graphs)?
|
I am trying to work on some problems and algorithms. I know C++ but a friend told me that it would be better if done with Python.As it would be much faster to develop and less time is spent in programming details which does not actually earn anything solution wise.
EDIT 2: I plan to use python-graph lib from Google-codes, Please provide example codes if you have used it.
EDIT 1: faster - less time && less work to code the solution
Thank you all for your help !
|
[
"I think you're looking for Python, because you can:\n\nFocus on the algorithms themselves and not have to worry about other detail like memory management. \nDo more with less code\nThe syntax is almost like working with pseudo code.\nThere is great built in language support for lists, tuples, list comprehensions, etc...\n\nBut more specifically...\n\nIf by better you mean speed of development, then chose Python.\nIf by better you mean sheer execution speed, then chose C++.\n\n",
"Instead of focusing on the language, you should focus on the libraries available to you.\nYou shouldn't write your own graph library when there are already plenty (read, \"too many\") available, both in C++ and in Python. [Stack Overflow has a list of Python Graph packages with recommendations that you should check out. I didn't find an equivalent question for C++. You could start one.] Also, unless this is an academic excercise or research on truly novel graph algorithms, you should browse through the libraries available to see if any of them already implement those algorithms of interest to you.\nUsing libraries mitigate the gain of the higher level language of Python, since you won't be working with raw C++ per se, but with a C++ library. Since the Python language has a very small core, it is fairly easy to learn, however, it still takes time. You will need factor in that additional time on top of learning a library, if you choose the Python route, so make sure to weigh that in your decision.\nThus, given you already know C++, you may ultimately find it faster to develop in C++, since you only have to commit the time necessary to learn the library, not a library plus a newβalbeit easy to learnβlanguage.\n",
"A bit subjective, but I'd vote for python because it has good libraries and abstracts a lot of the low level 'detail' that you'd have to consider when using c++...\n",
"I did all my algorithms work in college in C++ because I knew it.\nIf I'd had to learn a language at the same time, I would have picked Python most likely.\n",
"I am under the impression that it really depends from what you mean by faster.\nFaster to develop: go python.\nFaster to run: go C++.\nHowever python can use a lot of external C libraries, so the difference in processing time might not be that relevant, depending on the type of implementation.\n",
"At my university the 500 students in the \"Algorithms and Datastructures\" class get to choose the language they want.\nPython is by far the most popular choice there, and personally I'm happy I also chose that, even though I already knew C++. \n",
"Agree with your friend - use Python and put them within a unit test framework.\nI worked for a number of years with scientists who did a lot of their algorithmic work in Python.\nThe example below shows typical tests (the import statement is for the stuff being tested), with a couple of niceties that might save you some time.\nThe business with the save and restore of sys.path is so you can have all your tests sitting in a directory adjacent to the src directory, without having to install the source into your main Python modules.\nThis test script is written so it can be imported into a larger suite of unit tests or simply run with python thisfile.py.\n#!/usr/bin/python\n\"\"\"\nVRML Writer tests\n\"\"\"\n\nimport unittest\nimport os\nimport sys\n\nif __name__ == '__main__':\n global save_syspath\n save_syspath = sys.path\n sys.path = [os.path.abspath(\"../src/\")] + sys.path\n\nfrom cgtools.VizValueTools import *\n\nif __name__ == '__main__':\n sys.path = save_syspath # RESTORE SYS.PATH\n\n# use some common constants to make tests easier\nMINV = 0.002\nMAXV = 12.789\n\nclass TestColdHotColorGeneration(unittest.TestCase):\n\n def testGeneratesLimitValues(self):\n assert generateColdHotColorValue(MINV, MAXV, MINV) == (0.0, 0.0, 1.0)\n assert generateColdHotColorValue(MINV, MAXV, MAXV) == (1.0, 0.0, 0.0)\n assert generateColdHotColorValue(0, 0, 0) == (1.0, 0.0, 0.0) # cope with weird case where range is effectively one value, should be always top\n\n\n def testGeneratesLimitValuesWithClipping(self):\n assert generateColdHotColorValue(MINV, MAXV, MINV - 1.2) == (0.0, 0.0, 1.0)\n assert generateColdHotColorValue(MINV, MAXV, MAXV + 49) == (1.0, 0.0, 0.0)\n\n\n def testGeneratesMiddleValue(self):\n \"\"\"\n Note to be careful picking values so your value IS in the middle,\n to generate pure green\n \"\"\"\n assert generateColdHotColorValue(1.0, 3.0, 2.0) == (0.0, 1.0, 0.0)\n\nif __name__ == '__main__':\n # When this module is executed from the command-line, run all its tests\n unittest.main()\n\n",
"I would go for python. And if you really need the performance, then you can always write C/C++ extensions and use them in python.\n",
"Algorithms are fine in Python (allthough you can only fly one OS scheduled python thread due to the global lock); however, when it comes to data structures + algorithms you need fixed complexity guarantees, and this case you mix Python with C.\nI suppose what I have said applies more to long running computations. You can emulate data structures on-top of the python hashmap primitive.\n",
"I also vote for python. When do algorithm, we tend to work on the algorithm itself rather than language, low level details. Basically, we works on abstraction level. And using python, we're less likely to be side-tracked. \nBut if you're very familiar and comfortable with C++ and can use it freely to express your idea, just use it. \n",
"With C++, you'd sometimes be concentrating more on the language issues than the problem itself, so Python. I'd even be recommending you do it in a higher-level language like Matlab (although the language itself can be a bit ugly).\n",
"If using C++ means that STL is fair game, I'd say that it deserves serious consideration. STL is a fantastic library, combining structures, iterators, and algorithms. I love the Python recommendations, but if I could use STL I'd reconsider C++.\n",
"Remember that Python is compiled to bytecode and then interpreted in a VM. So, in performance isn't better (faster) than C++.\n"
] |
[
23,
9,
8,
6,
6,
5,
4,
4,
3,
2,
2,
1,
0
] |
[] |
[] |
[
"algorithm",
"c++",
"graph",
"python"
] |
stackoverflow_0001823431_algorithm_c++_graph_python.txt
|
Q:
in protocol with regard to sequence
How is this implemented at a python level?
I've got an object that pretends to be a dict for the most part (in retrospect I should have just subclassed dict, but I'd rather not refactor the codebase, and I'd also like to know this for future reference), which looks something a bit like
class configThinger(object):
_config = {}
def __getitem__(self, key):
return self._config[key]
def __setitem__(self, key, value):
self._config[key] = value
Which works exactly as it's supposed to and behaves correctly when I try to access it's elements as configThingerInstance['whatever']
But a call like
t = configThinger()
t.populate() # Internal method that fills it with some useful data
if 'DEBUG' in t:
doStuff()
results in a KeyError being raised because presumably the `in' protocol does a getitem() lookup for the key in question. Do I need to raise some other exception to tell in that it's not there?
I'd rather not do something like this.
try:
t['DEBUG']
except KeyError:
pass
else:
doStuff()
Also, where in the documentation is this?
I was looking around
http://docs.python.org/tutorial/datastructures.html
http://docs.python.org/library/stdtypes.html
but tragically trying to google for something specific to the word 'in' is folly :(
EDIT 1:
With a stack of trace prints, I can see that the program calls configThingerInstance.getitem(0)
however
t = {'rawk': 1,
'rawr': 2,
}
t[0] # Raises KeyError
'thing' in t # returns False
A:
It sounds like you want to overload the in operator?
You can do that by defining the method __contains__: http://docs.python.org/reference/datamodel.html#object.contains
A:
For the best support for the in operator (containment aka membership checking), implement the __contains__ special method on your configThinger class:
class configThinger(object):
_config = {}
def __getitem__(self, key):
return self._config[key]
def __setitem__(self, key, value):
self._config[key] = value
def __contains__(self, key):
return key in self._config
the docs are here (also explaining other, lesser ways to support the in operator).
|
in protocol with regard to sequence
|
How is this implemented at a python level?
I've got an object that pretends to be a dict for the most part (in retrospect I should have just subclassed dict, but I'd rather not refactor the codebase, and I'd also like to know this for future reference), which looks something a bit like
class configThinger(object):
_config = {}
def __getitem__(self, key):
return self._config[key]
def __setitem__(self, key, value):
self._config[key] = value
Which works exactly as it's supposed to and behaves correctly when I try to access it's elements as configThingerInstance['whatever']
But a call like
t = configThinger()
t.populate() # Internal method that fills it with some useful data
if 'DEBUG' in t:
doStuff()
results in a KeyError being raised because presumably the `in' protocol does a getitem() lookup for the key in question. Do I need to raise some other exception to tell in that it's not there?
I'd rather not do something like this.
try:
t['DEBUG']
except KeyError:
pass
else:
doStuff()
Also, where in the documentation is this?
I was looking around
http://docs.python.org/tutorial/datastructures.html
http://docs.python.org/library/stdtypes.html
but tragically trying to google for something specific to the word 'in' is folly :(
EDIT 1:
With a stack of trace prints, I can see that the program calls configThingerInstance.getitem(0)
however
t = {'rawk': 1,
'rawr': 2,
}
t[0] # Raises KeyError
'thing' in t # returns False
|
[
"It sounds like you want to overload the in operator?\nYou can do that by defining the method __contains__: http://docs.python.org/reference/datamodel.html#object.contains\n",
"For the best support for the in operator (containment aka membership checking), implement the __contains__ special method on your configThinger class:\nclass configThinger(object):\n _config = {}\n def __getitem__(self, key):\n return self._config[key]\n def __setitem__(self, key, value):\n self._config[key] = value\n def __contains__(self, key):\n return key in self._config\n\nthe docs are here (also explaining other, lesser ways to support the in operator).\n"
] |
[
3,
1
] |
[] |
[] |
[
"protocols",
"python"
] |
stackoverflow_0001823752_protocols_python.txt
|
Q:
Django best practice for displaying mostly read-only form, one field writeable
I have a requirement where one user creates an 'instance' of an object via a ModelForm. Another user of a different group has access to read all of the fields of the form, but has to update only one field. Think of a student who creates an exam object. Then a teach pulls up the exam and just needs to put in a grade, the rest of the exam is read only.
What's the best way to do that? Should I just query for the object, and display each field individually, then create a form (not a ModelForm?) for just the one field?
A:
Should I just query for the object, and display each field individually, then create a form (not a ModelForm?) for just the one field?
This is probably the best way to go about it. Note you can use a ModelForm for the teacher form, see the Django documentation on using a subset of fields on a model form. You will have to display all the other fields manually in your template, but you should probably have a separate template for this view (I would use separate views as well).
You could find some code for a read only field on Django Snippets, but generally it's better to be explicit about what fields you are updating from each view. This is likely to be more trouble than it's worth.
|
Django best practice for displaying mostly read-only form, one field writeable
|
I have a requirement where one user creates an 'instance' of an object via a ModelForm. Another user of a different group has access to read all of the fields of the form, but has to update only one field. Think of a student who creates an exam object. Then a teach pulls up the exam and just needs to put in a grade, the rest of the exam is read only.
What's the best way to do that? Should I just query for the object, and display each field individually, then create a form (not a ModelForm?) for just the one field?
|
[
"\nShould I just query for the object, and display each field individually, then create a form (not a ModelForm?) for just the one field?\n\nThis is probably the best way to go about it. Note you can use a ModelForm for the teacher form, see the Django documentation on using a subset of fields on a model form. You will have to display all the other fields manually in your template, but you should probably have a separate template for this view (I would use separate views as well).\nYou could find some code for a read only field on Django Snippets, but generally it's better to be explicit about what fields you are updating from each view. This is likely to be more trouble than it's worth.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001823852_django_python.txt
|
Q:
How do I query XHTML using python?
I have created a simple test harness in python for my ASP .net web site.
I would like to look up some HTML tags in the resulting page to find certain values.\
What would be the best way of doing this in python?
eg (returned page):
<div id="ErrorPanel">An error occurred......</div>
would display (in std out from python):
Error: .....
or
<td id="dob">23/3/1985</td>
would display:
Date of birth: 23/3/1985
A:
Do you want to parse XML, as you state in your question's title, or HTML, as you show in the text of the question? For the latter, I recommend BeautifulSoup -- download it and install it, then, once having made a soup object out of the HTML, you can easily locate the tag with a certain id (or other attribute), e.g.:
errp = soup.find(attrs={'id': 'ErrorPanel'})
if errp is not None:
print 'Error:', errp.string
and similarly for the other case (easily tweakable e.g. into a loop if you're looking for non-unique attributes, and so on).
A:
You can also do it with lxml. It handles HTML very well, and you can use CSS selectors for querying DOM, which makes it particularly attractive if you use libraries like jQuery regularly.
|
How do I query XHTML using python?
|
I have created a simple test harness in python for my ASP .net web site.
I would like to look up some HTML tags in the resulting page to find certain values.\
What would be the best way of doing this in python?
eg (returned page):
<div id="ErrorPanel">An error occurred......</div>
would display (in std out from python):
Error: .....
or
<td id="dob">23/3/1985</td>
would display:
Date of birth: 23/3/1985
|
[
"Do you want to parse XML, as you state in your question's title, or HTML, as you show in the text of the question? For the latter, I recommend BeautifulSoup -- download it and install it, then, once having made a soup object out of the HTML, you can easily locate the tag with a certain id (or other attribute), e.g.:\nerrp = soup.find(attrs={'id': 'ErrorPanel'})\nif errp is not None:\n print 'Error:', errp.string\n\nand similarly for the other case (easily tweakable e.g. into a loop if you're looking for non-unique attributes, and so on).\n",
"You can also do it with lxml. It handles HTML very well, and you can use CSS selectors for querying DOM, which makes it particularly attractive if you use libraries like jQuery regularly.\n"
] |
[
4,
4
] |
[] |
[] |
[
"html",
"python"
] |
stackoverflow_0001824057_html_python.txt
|
Q:
Microprocessor to RS-232 realtime plot using PySerial/Matplotlib?
I'm new to the world of Python and my programming skills are fairly poor but I'm trying to figure a way to use Python to display the output from an EEG circuit (using the OpenEEG circuit http://openeeg.sourceforge.net)
The analogue output is amplified and processed via an ADC (in an ATmega8 microcontroller) and is converted to RS232 by a MAX232.
The RS232 Signal is as follows:
Byte 1: sync value 0xa5
Byte 2: sync value 0x5a
Byte 3: version
Byte 4: Frame number
Byte 5: Channel 1 Low Byte
Byte 6: Channel 1 High Byte
Byte 7: Channel 2 Low Byte
Byte 8: Channel 2 High Byte
...
Bytes 9-16 are for extra electrode channels but data not required since only using the first two
...
Byte 17: Button states (b1-b4)
I've got some basic PySerial functionality but I need to figure a way to make use of the incoming data by buffering it and plotting the useful values as 2 real-time x-y waveforms (time vs voltage)
Question update:
I'm getting the code to print with the obvious few lines of PySerial but it's gibberish. I'm trying to strip the data down in to the format of values that can then be plotted. The 17 bytes of data is currently coming in at 256 frames/sec. The (two) channels are made up 10 bits of data each (with 6 zeros to make up the rest of the 2 bytes). They are unsigned giving possible values of 0 to 1023. These correspond to values that should be plotted as positive and negative, so a binary value of 512 corresponds to a plot of zero (micro)volts....
How do I read the incoming stream as 8 bit binary (stripping out the data that I don't need), then combine the two relevant bytes from each channel that I want (possibly removing the surplus 6 zeros if necessary)?
A:
To handle the complicated binary data format you could maybe use structured arrays in numpy (see also here for a nice introduction). After defining the structure of the data it should be very easy to read it in. Then you could use numpy's functionality to cook down the data to what you need.
A:
There's a good realtime plotting example here. It's a good example in that it runs with self generated data, so it's easy to test, but it's also obvious where to modify the code for plotting real data, and the code is easy to follow.
The basic idea is to make a plot window and then update that data as it comes in using
set_xdata(np.arange(len(self.data)))
set_ydata(np.array(self.data))
(Though in the current versions of matplotlib you may want to use set_data(xdata, ydata) instead.)
As for parsing the serial port data, it's probably better to ask that as a separate question.
|
Microprocessor to RS-232 realtime plot using PySerial/Matplotlib?
|
I'm new to the world of Python and my programming skills are fairly poor but I'm trying to figure a way to use Python to display the output from an EEG circuit (using the OpenEEG circuit http://openeeg.sourceforge.net)
The analogue output is amplified and processed via an ADC (in an ATmega8 microcontroller) and is converted to RS232 by a MAX232.
The RS232 Signal is as follows:
Byte 1: sync value 0xa5
Byte 2: sync value 0x5a
Byte 3: version
Byte 4: Frame number
Byte 5: Channel 1 Low Byte
Byte 6: Channel 1 High Byte
Byte 7: Channel 2 Low Byte
Byte 8: Channel 2 High Byte
...
Bytes 9-16 are for extra electrode channels but data not required since only using the first two
...
Byte 17: Button states (b1-b4)
I've got some basic PySerial functionality but I need to figure a way to make use of the incoming data by buffering it and plotting the useful values as 2 real-time x-y waveforms (time vs voltage)
Question update:
I'm getting the code to print with the obvious few lines of PySerial but it's gibberish. I'm trying to strip the data down in to the format of values that can then be plotted. The 17 bytes of data is currently coming in at 256 frames/sec. The (two) channels are made up 10 bits of data each (with 6 zeros to make up the rest of the 2 bytes). They are unsigned giving possible values of 0 to 1023. These correspond to values that should be plotted as positive and negative, so a binary value of 512 corresponds to a plot of zero (micro)volts....
How do I read the incoming stream as 8 bit binary (stripping out the data that I don't need), then combine the two relevant bytes from each channel that I want (possibly removing the surplus 6 zeros if necessary)?
|
[
"To handle the complicated binary data format you could maybe use structured arrays in numpy (see also here for a nice introduction). After defining the structure of the data it should be very easy to read it in. Then you could use numpy's functionality to cook down the data to what you need.\n",
"There's a good realtime plotting example here. It's a good example in that it runs with self generated data, so it's easy to test, but it's also obvious where to modify the code for plotting real data, and the code is easy to follow.\nThe basic idea is to make a plot window and then update that data as it comes in using\nset_xdata(np.arange(len(self.data)))\nset_ydata(np.array(self.data))\n\n(Though in the current versions of matplotlib you may want to use set_data(xdata, ydata) instead.)\nAs for parsing the serial port data, it's probably better to ask that as a separate question.\n"
] |
[
2,
2
] |
[] |
[] |
[
"matplotlib",
"microprocessors",
"pyserial",
"python",
"serial_port"
] |
stackoverflow_0001797249_matplotlib_microprocessors_pyserial_python_serial_port.txt
|
Q:
merge background audio file
I have 2 audio files for primary and background music that I want to merge (not concatenate). The final audio file should be as long as the primary file, and if the background music is shorter then it should repeat.
If there a Linux command or a Python library that can be used to do this? Sox supports merging, but does not appear to allow repeating the background audio.
A:
As a possible solution, why not detect if the length of the background file < length of the foreground file and then construct a background file which is a loop, if necessary? Then you can pass that into sox.
You should be able to get the length from sndhdr (look at the frames count).
As far as a python way of merging the streams, audioop.add may do what you need, although if you're merging two full volume sources, you might want to reduce the volume of one of them (try -12db as a start) if you're mixing music and not.
More audio libraries can be found here.
|
merge background audio file
|
I have 2 audio files for primary and background music that I want to merge (not concatenate). The final audio file should be as long as the primary file, and if the background music is shorter then it should repeat.
If there a Linux command or a Python library that can be used to do this? Sox supports merging, but does not appear to allow repeating the background audio.
|
[
"As a possible solution, why not detect if the length of the background file < length of the foreground file and then construct a background file which is a loop, if necessary? Then you can pass that into sox.\nYou should be able to get the length from sndhdr (look at the frames count).\nAs far as a python way of merging the streams, audioop.add may do what you need, although if you're merging two full volume sources, you might want to reduce the volume of one of them (try -12db as a start) if you're mixing music and not. \nMore audio libraries can be found here.\n"
] |
[
1
] |
[] |
[] |
[
"audio",
"linux",
"merge",
"python"
] |
stackoverflow_0001823480_audio_linux_merge_python.txt
|
Q:
Get mach_absolute_time/UpTime() in nanoseconds in Python
I need to access the elapsed time since startup in nanoseconds from a Python program running on Mac OS X 10.6.
I use the following Carbon calls to get this in C code:
AbsoluteTime uptimeAbs = AbsoluteToNanoseconds(UpTime());
uint64_t elapsedTime = ((uint64_t)uptimeAbs.hi << 32) + uptimeAbs.lo;
Is it possible to get to these functions in Python using a Carbon or PyObjC module? I tried:
from Carbon import *
UpTime()
but got "NameError: name 'UpTime' is not defined".
How can I get access to this value from Python on OS X?
A:
Within the code in one of the answers at CGEventTimestamp to NSDate, I found -[NSProcessInfo systemUptime], available starting in 10.6. This gives me the time in decimal seconds, which I can multiply:
from Foundation import *
NSProcessInfo.processInfo().systemUptime() * 1e9
The result does have nanosecond precision, and should work nicely for my needs.
Update: the following method also works, and is compatible with 10.5 as well:
from Quartz.QuartzCore import *
CACurrentMediaTime() * 1e9
|
Get mach_absolute_time/UpTime() in nanoseconds in Python
|
I need to access the elapsed time since startup in nanoseconds from a Python program running on Mac OS X 10.6.
I use the following Carbon calls to get this in C code:
AbsoluteTime uptimeAbs = AbsoluteToNanoseconds(UpTime());
uint64_t elapsedTime = ((uint64_t)uptimeAbs.hi << 32) + uptimeAbs.lo;
Is it possible to get to these functions in Python using a Carbon or PyObjC module? I tried:
from Carbon import *
UpTime()
but got "NameError: name 'UpTime' is not defined".
How can I get access to this value from Python on OS X?
|
[
"Within the code in one of the answers at CGEventTimestamp to NSDate, I found -[NSProcessInfo systemUptime], available starting in 10.6. This gives me the time in decimal seconds, which I can multiply:\nfrom Foundation import *\nNSProcessInfo.processInfo().systemUptime() * 1e9\n\nThe result does have nanosecond precision, and should work nicely for my needs.\nUpdate: the following method also works, and is compatible with 10.5 as well:\nfrom Quartz.QuartzCore import *\nCACurrentMediaTime() * 1e9\n\n"
] |
[
2
] |
[] |
[] |
[
"macos",
"macos_carbon",
"pyobjc",
"python"
] |
stackoverflow_0001824399_macos_macos_carbon_pyobjc_python.txt
|
Q:
In Pinax, how to invite when ACCOUNT_OPEN_SIGNUP = False?
In Pinax, when
ACCOUNT_OPEN_SIGNUP = False
how does the admin invite more users to the system?
How does one generate invitation codes? How do they work?
A:
The only way currently is to hit /admin/invite_user/ as a site admin. Currently, you can only send out one invitation at a time. We are definitely going to improve this in 0.9. Suggestions welcome.
|
In Pinax, how to invite when ACCOUNT_OPEN_SIGNUP = False?
|
In Pinax, when
ACCOUNT_OPEN_SIGNUP = False
how does the admin invite more users to the system?
How does one generate invitation codes? How do they work?
|
[
"The only way currently is to hit /admin/invite_user/ as a site admin. Currently, you can only send out one invitation at a time. We are definitely going to improve this in 0.9. Suggestions welcome.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"invitation",
"invite",
"pinax",
"python"
] |
stackoverflow_0001817270_django_invitation_invite_pinax_python.txt
|
Q:
major changes in python since version 2.2.3
I've written a small python script to create a file and calculate times. I've tested it on Fedora 10, and Ubuntu 8.x and it worked well. the python versions were 2.5.x.
I tried to run it on my production server (an old red hat based linux server), the version of python is 2.2.3. the script does not work and raises a syntax error in the class definition.
the script defines a class with methods to create files on disk an measure the time, to estimate disk write speed. it starts like this:
class TestDiskSpeed():
def __init__(self, rounds=1, speedMode=SPEED_MODE_MEGABYTE):
the class definition is pointed as the error by python 2.2.3.
what are the major changes in python since 2.2.3 that could possibly crash my application? I'm using these modules: os, sys, time, stat, gc.
Update:
by removing the () from class definition python accepted the class. but it raises another error on this line:
size = long(size) if size != None else self._size
I'm a PHP developer, just entered python programming (maybe a month), and am very used to the ternary operation which is done in PHP like this:
$var = (condition) ? $valueIfTrue : $valueIfFalse;
I searched and found it is done in python like the one I used for my size variable. though it seems python 2.2.3 does not like it.
I was going to insert all the code in here (I'm going to release the script as LGPL anyway), but the code is more than 150 lines (still in development).
A:
I wrote a script a while ago to help answer this exact question: pyqver.
This script attempts to identify the minimum version of Python that is required
to execute a particular source file.
When developing Python scripts for distribution, it is desirable to identify
which minimum version of the Python interpreter is required. pyqver attempts to
answer this question using a simplistic analysis of the output of the Python
compiler.
Use the -v option to list the reasons why your script requires a particular minimum version. This is very helpful in deciding what to change to make your script work with a specific version of Python.
As always, feel free to fork and contribute!
A:
That's weird, because it compiles if you remove the () in the class definition. However, the documentation says that empty parens there is ok.
Since you're using lots of python 2.5 features, it's going to be hard work to find them all. I would recommend reading the "What's new in Python" for every version between 2.2 and 2.5, then coming up with a list of features that you might be able to search for with your, such as:
Comprehensions and generators
Ternary expression
Decorators
New-style classes
Luckily, most of the new features come with a new language keyword (or a new way of using a keyword, in the case of the ternary x if p else y), so it shouldn't be hard to grep for them.
A:
This page links to all the Python version docs - look for the "What's New in Python X.X" doc that Andrew Kuchling has been diligently writing for each release.
Off-hand, I would guess the problem is the empty ()'s in your class definition, but I don't see this syntax change listed in the 2.3 "What's new" doc.
I've tried to maintain backwards compatibility for my pyparsing module back to 2.3.2, but that was when list comprehensions were added, and I just can't make myself go back before that. No chance of upgrading your server?
A:
My money is on new-style classes, which the () on your class would imply.
A:
The ternary operator is quite new. There are a few alternatives but I'd write it like this:
if size is None:
size = self._size
else:
size = long(size)
|
major changes in python since version 2.2.3
|
I've written a small python script to create a file and calculate times. I've tested it on Fedora 10, and Ubuntu 8.x and it worked well. the python versions were 2.5.x.
I tried to run it on my production server (an old red hat based linux server), the version of python is 2.2.3. the script does not work and raises a syntax error in the class definition.
the script defines a class with methods to create files on disk an measure the time, to estimate disk write speed. it starts like this:
class TestDiskSpeed():
def __init__(self, rounds=1, speedMode=SPEED_MODE_MEGABYTE):
the class definition is pointed as the error by python 2.2.3.
what are the major changes in python since 2.2.3 that could possibly crash my application? I'm using these modules: os, sys, time, stat, gc.
Update:
by removing the () from class definition python accepted the class. but it raises another error on this line:
size = long(size) if size != None else self._size
I'm a PHP developer, just entered python programming (maybe a month), and am very used to the ternary operation which is done in PHP like this:
$var = (condition) ? $valueIfTrue : $valueIfFalse;
I searched and found it is done in python like the one I used for my size variable. though it seems python 2.2.3 does not like it.
I was going to insert all the code in here (I'm going to release the script as LGPL anyway), but the code is more than 150 lines (still in development).
|
[
"I wrote a script a while ago to help answer this exact question: pyqver. \n\nThis script attempts to identify the minimum version of Python that is required\n to execute a particular source file.\nWhen developing Python scripts for distribution, it is desirable to identify\n which minimum version of the Python interpreter is required. pyqver attempts to\n answer this question using a simplistic analysis of the output of the Python\n compiler.\n\nUse the -v option to list the reasons why your script requires a particular minimum version. This is very helpful in deciding what to change to make your script work with a specific version of Python.\nAs always, feel free to fork and contribute!\n",
"That's weird, because it compiles if you remove the () in the class definition. However, the documentation says that empty parens there is ok.\nSince you're using lots of python 2.5 features, it's going to be hard work to find them all. I would recommend reading the \"What's new in Python\" for every version between 2.2 and 2.5, then coming up with a list of features that you might be able to search for with your, such as:\n\nComprehensions and generators\nTernary expression\nDecorators\nNew-style classes\n\nLuckily, most of the new features come with a new language keyword (or a new way of using a keyword, in the case of the ternary x if p else y), so it shouldn't be hard to grep for them.\n",
"This page links to all the Python version docs - look for the \"What's New in Python X.X\" doc that Andrew Kuchling has been diligently writing for each release.\nOff-hand, I would guess the problem is the empty ()'s in your class definition, but I don't see this syntax change listed in the 2.3 \"What's new\" doc.\nI've tried to maintain backwards compatibility for my pyparsing module back to 2.3.2, but that was when list comprehensions were added, and I just can't make myself go back before that. No chance of upgrading your server?\n",
"My money is on new-style classes, which the () on your class would imply.\n",
"The ternary operator is quite new. There are a few alternatives but I'd write it like this:\nif size is None:\n size = self._size\nelse:\n size = long(size)\n\n"
] |
[
8,
1,
1,
1,
0
] |
[] |
[] |
[
"changelog",
"python"
] |
stackoverflow_0001824417_changelog_python.txt
|
Q:
Infinity generated in python code
I'm looking over some complex Python 2.6 code which is occasionally resulting in an infinity being generated (at least an Infinity being serialized by the json library -- which checks w/ math.isinf).
What is especially baffling is that Python (as far as I can tell) shouldn't be able to ever produce computation results set to infinity. Am I wrong with this assumption? I was aware you can only get infinities from constants:
k = float('inf')
k = 1e900
A:
Somewhere between 1e308 and 1e309 the floats run out of precision, so if you are computing results above that range you will see inf
>>> 1e308
1e+308
>>> 1e309
inf
>>> json.dumps(1e308,allow_nan=False)
'1e+308'
>>> json.dumps(1e309,allow_nan=False)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/lib/python2.6/json/encoder.py", line 367, in encode
chunks = list(self.iterencode(o))
File "/usr/lib/python2.6/json/encoder.py", line 304, in _iterencode
yield floatstr(o, self.allow_nan)
File "/usr/lib/python2.6/json/encoder.py", line 47, in floatstr
raise ValueError(msg)
ValueError: Out of range float values are not JSON compliant: inf
>>>
Decimal can handle larger numbers, but obviously there is a performance penalty (and it can't be serialised with json)
>>> from decimal import Decimal
>>> Decimal('1e900')/10
Decimal("1E+899")
Here is an example of an addition that doesn't raise overflow exception
>>> a=1e308
>>> a+a
inf
|
Infinity generated in python code
|
I'm looking over some complex Python 2.6 code which is occasionally resulting in an infinity being generated (at least an Infinity being serialized by the json library -- which checks w/ math.isinf).
What is especially baffling is that Python (as far as I can tell) shouldn't be able to ever produce computation results set to infinity. Am I wrong with this assumption? I was aware you can only get infinities from constants:
k = float('inf')
k = 1e900
|
[
"Somewhere between 1e308 and 1e309 the floats run out of precision, so if you are computing results above that range you will see inf\n>>> 1e308\n1e+308\n>>> 1e309\ninf\n\n>>> json.dumps(1e308,allow_nan=False)\n'1e+308'\n>>> json.dumps(1e309,allow_nan=False)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python2.6/json/__init__.py\", line 237, in dumps\n **kw).encode(obj)\n File \"/usr/lib/python2.6/json/encoder.py\", line 367, in encode\n chunks = list(self.iterencode(o))\n File \"/usr/lib/python2.6/json/encoder.py\", line 304, in _iterencode\n yield floatstr(o, self.allow_nan)\n File \"/usr/lib/python2.6/json/encoder.py\", line 47, in floatstr\n raise ValueError(msg)\nValueError: Out of range float values are not JSON compliant: inf\n>>> \n\nDecimal can handle larger numbers, but obviously there is a performance penalty (and it can't be serialised with json)\n>>> from decimal import Decimal\n>>> Decimal('1e900')/10\nDecimal(\"1E+899\")\n\nHere is an example of an addition that doesn't raise overflow exception\n>>> a=1e308\n>>> a+a\ninf\n\n"
] |
[
13
] |
[] |
[] |
[
"infinity",
"python"
] |
stackoverflow_0001824751_infinity_python.txt
|
Q:
How to send status to the VIM status line after calling custom VIM (Python) function
I've just created my first VIM script, I wrote it in Python. It's a simple script to switch color schemes from a directory (/vim/etc/colors). I would like to know how to send a notification after the color scheme changed with the name of the selected color scheme to the vim 'statusline'.
rson gave an answer to my question, here is an updated (and debugged) version of the script for who is interested (works fine as far as I can test)
Implemented (kind of) the suggestions of AI and Caleb, thanks!:
" toggleColorScheme 0.9 (l) 2009 by Jasper Poppe <jpoppe@ebay.com>
" cycle through colorschemes with F8 and Shift+F8
nnoremap <silent><F8> :call ToggleColorScheme("1")<CR>
nnoremap <silent><s-F8> :call ToggleColorScheme("-1")<CR>
" set directory with color schemes to cycle through
let g:Toggle_Color_Scheme_Path = "/etc/vim/colors"
function! ToggleColorScheme(paramater)
python << endpython
import vim
import os
paramater = (vim.eval('a:paramater'))
scheme_path = vim.eval('g:Toggle_Color_Scheme_Path')
colorschemes = [color.split('.')[0] for color in os.listdir(scheme_path) if color.endswith('.vim')]
colorschemes.sort()
if not vars().has_key('position'):
start_scheme = vim.eval('g:colors_name') + '.vim'
if start_scheme in colorschemes:
position = colorschemes.index(start_scheme)
else:
position = 0
position += int(paramater)
position %= len(colorschemes)
vim.command('colorscheme %s' % colorschemes[position])
vim.command('redraw | echo "%s"' % colorschemes[position])
vim.command('return 1')
endpython
endfunction
A:
vim.command('redraw | echo "%s"' % colorschemes[position])
From :help echo:
A later redraw may make the message disappear again.
And since Vim mostly postpones redrawing until it's
finished with a sequence of commands this happens
quite often. To avoid that a command from before the
":echo" causes a redraw afterwards (redraws are often
postponed until you type something), force a redraw
with the |:redraw| command. Example:
:new | redraw | echo "there is a new window"
A:
Since you are updating the script here,
Instead of
if argument == 'next':
position += 1
if position == len(colorschemes) - 1:
position = 0
elif argument == 'prev':
position -= 1
if position == -1:
position = len(colorschemes) - 1
Perhaps
scroll['next'] = +1
scroll['prev'] = -1
position += scroll[argument]
position = position % len(colorschemes)
|
How to send status to the VIM status line after calling custom VIM (Python) function
|
I've just created my first VIM script, I wrote it in Python. It's a simple script to switch color schemes from a directory (/vim/etc/colors). I would like to know how to send a notification after the color scheme changed with the name of the selected color scheme to the vim 'statusline'.
rson gave an answer to my question, here is an updated (and debugged) version of the script for who is interested (works fine as far as I can test)
Implemented (kind of) the suggestions of AI and Caleb, thanks!:
" toggleColorScheme 0.9 (l) 2009 by Jasper Poppe <jpoppe@ebay.com>
" cycle through colorschemes with F8 and Shift+F8
nnoremap <silent><F8> :call ToggleColorScheme("1")<CR>
nnoremap <silent><s-F8> :call ToggleColorScheme("-1")<CR>
" set directory with color schemes to cycle through
let g:Toggle_Color_Scheme_Path = "/etc/vim/colors"
function! ToggleColorScheme(paramater)
python << endpython
import vim
import os
paramater = (vim.eval('a:paramater'))
scheme_path = vim.eval('g:Toggle_Color_Scheme_Path')
colorschemes = [color.split('.')[0] for color in os.listdir(scheme_path) if color.endswith('.vim')]
colorschemes.sort()
if not vars().has_key('position'):
start_scheme = vim.eval('g:colors_name') + '.vim'
if start_scheme in colorschemes:
position = colorschemes.index(start_scheme)
else:
position = 0
position += int(paramater)
position %= len(colorschemes)
vim.command('colorscheme %s' % colorschemes[position])
vim.command('redraw | echo "%s"' % colorschemes[position])
vim.command('return 1')
endpython
endfunction
|
[
"vim.command('redraw | echo \"%s\"' % colorschemes[position])\nFrom :help echo:\n\nA later redraw may make the message disappear again.\n And since Vim mostly postpones redrawing until it's\n finished with a sequence of commands this happens\n quite often. To avoid that a command from before the\n \":echo\" causes a redraw afterwards (redraws are often\n postponed until you type something), force a redraw\n with the |:redraw| command. Example: \n\n:new | redraw | echo \"there is a new window\"\n\n\n",
"Since you are updating the script here,\nInstead of \nif argument == 'next':\n position += 1\n if position == len(colorschemes) - 1:\n position = 0\nelif argument == 'prev':\n position -= 1\n if position == -1:\n position = len(colorschemes) - 1\n\nPerhaps\nscroll['next'] = +1\nscroll['prev'] = -1\nposition += scroll[argument]\nposition = position % len(colorschemes) \n\n"
] |
[
5,
1
] |
[] |
[] |
[
"color_scheme",
"python",
"scripting",
"vim"
] |
stackoverflow_0001822619_color_scheme_python_scripting_vim.txt
|
Q:
Can I find all of a certain base model in App Engine?
Given a class-like relationship:
class A(db.Model):
pass
class B(A):
pass
Can I get all of the base class? The query:
models.A.all().fetch(1)
returns an empty list.
A:
The datastore doesn't natively support this sort of polymorphism - but you can use the polymodel class to do this. Just inherit from PolyModel instead of Model and things will behave more or less as you expect them to.
A:
The datastore does not record inheritance, per se: it stores the B entities as being of kind B. You can get all (direct, proper) subclasses of A with A.__subclasses__() (if you want indirect subclasses as well you'll need to do the same with each of these, and so forth, recursively, until you stop getting subclasses), and perform all the .all queries on them.
|
Can I find all of a certain base model in App Engine?
|
Given a class-like relationship:
class A(db.Model):
pass
class B(A):
pass
Can I get all of the base class? The query:
models.A.all().fetch(1)
returns an empty list.
|
[
"The datastore doesn't natively support this sort of polymorphism - but you can use the polymodel class to do this. Just inherit from PolyModel instead of Model and things will behave more or less as you expect them to.\n",
"The datastore does not record inheritance, per se: it stores the B entities as being of kind B. You can get all (direct, proper) subclasses of A with A.__subclasses__() (if you want indirect subclasses as well you'll need to do the same with each of these, and so forth, recursively, until you stop getting subclasses), and perform all the .all queries on them.\n"
] |
[
2,
1
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001823151_google_app_engine_python.txt
|
Q:
Python QtreeWidget: return tree hierarchy
I got stuck in trying to obtain the hierarchical view of a widget tree.
The code works fine and generates a nice tree like that:
ROOT(Animal):
|
|
|___Not extinct:
. | (red)
. |_____BIRD--------------(blue)
. | (green)
|
| (red)
|_____Mammal------------(blue)
| (green)
|
| (red)
|_____Reptile-----------(blue)
(green)
Here is the code with the tree hierarchy:
def myTreeWDG(self):
....
"""define tree"""
self.obj_animalTreeWDG = QtGui.QTreeWidget(self.obj_viewGroupBox)
self.obj_animalTreeWDG.setGeometry(QtCore.QRect(10, 20, 191, 131))
self.obj_animalTreeWDG.setObjectName("obj_animalTreeWDG")
"""ROOT: animal"""
obj_parent1 = QtGui.QTreeWidgetItem(self.obj_animalTreeWDG)
"""not extinct:"""
obj_childView1_1 = QtGui.QTreeWidgetItem()
obj_parent1.addChild(obj_childView1_1)
"""bird"""
obj_childView1_1_1 = QtGui.QTreeWidgetItem()
obj_childView1_1.addChild(obj_childView1_1_1)
"""3: red, blue, green"""
total=3
self.insert_treeLeaves(total,obj_childView1_1_1)
"""mamal"""
obj_childView1_1_2 = QtGui.QTreeWidgetItem()
obj_childView1_1.addChild(obj_childView1_1_2)
"""3: red, blue, green"""
total=3
self.insert_treeLeaves(total,obj_childView1_1_2)
"""reptile"""
obj_childView1_1_3 = QtGui.QTreeWidgetItem()
obj_childView1_1.addChild(obj_childView1_1_3)
"""3: red, blue, green"""
total=3
self.insert_treeLeaves(total,obj_childView1_1_3)
"""connect event"""
QtCore.QObject.connect(self.obj_animalTreeWDG, QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.obj_treeViewInput)
Here is the code to add the leaves into the tree:
def insert_treeLeaves(self,total,tree_directParent):
for i in range(0,total):
"""leaves with color name"""
tree_child_leaf = QtGui.QTreeWidgetItem()
tree_directParent.addChild(tree_child_leaf)
Then, we have the function that tells us every time the tree is clicked, and where it was clicked:
def obj_treeViewInput(self,item,col):
print "obj _Qtree : pressed"
print "name:" item.text(col)
The problem is, how can we get if the touched leaf (red) belongs to the Bird or other father, i.e. how to get the following output give some mouse click:
Animal - Not extinct - Mammal - (red).
All comments and suggestions are highly appreciated.
A:
What about a method in each QtreeWidgetItem in which you could print the path to this item.
In this method, you could use recursion to get the complete path of the item's parents (you have a "QTreeWidgetItem * parent () const" method to do this) and you add the current item's text to its parent's path ! You stop the recursion when an item do not have any parent.
I hope I understood your question and this helps you a little bit !
Do you have your own QTreeWidgetItem class ? You could use a specific role to achieve this...
|
Python QtreeWidget: return tree hierarchy
|
I got stuck in trying to obtain the hierarchical view of a widget tree.
The code works fine and generates a nice tree like that:
ROOT(Animal):
|
|
|___Not extinct:
. | (red)
. |_____BIRD--------------(blue)
. | (green)
|
| (red)
|_____Mammal------------(blue)
| (green)
|
| (red)
|_____Reptile-----------(blue)
(green)
Here is the code with the tree hierarchy:
def myTreeWDG(self):
....
"""define tree"""
self.obj_animalTreeWDG = QtGui.QTreeWidget(self.obj_viewGroupBox)
self.obj_animalTreeWDG.setGeometry(QtCore.QRect(10, 20, 191, 131))
self.obj_animalTreeWDG.setObjectName("obj_animalTreeWDG")
"""ROOT: animal"""
obj_parent1 = QtGui.QTreeWidgetItem(self.obj_animalTreeWDG)
"""not extinct:"""
obj_childView1_1 = QtGui.QTreeWidgetItem()
obj_parent1.addChild(obj_childView1_1)
"""bird"""
obj_childView1_1_1 = QtGui.QTreeWidgetItem()
obj_childView1_1.addChild(obj_childView1_1_1)
"""3: red, blue, green"""
total=3
self.insert_treeLeaves(total,obj_childView1_1_1)
"""mamal"""
obj_childView1_1_2 = QtGui.QTreeWidgetItem()
obj_childView1_1.addChild(obj_childView1_1_2)
"""3: red, blue, green"""
total=3
self.insert_treeLeaves(total,obj_childView1_1_2)
"""reptile"""
obj_childView1_1_3 = QtGui.QTreeWidgetItem()
obj_childView1_1.addChild(obj_childView1_1_3)
"""3: red, blue, green"""
total=3
self.insert_treeLeaves(total,obj_childView1_1_3)
"""connect event"""
QtCore.QObject.connect(self.obj_animalTreeWDG, QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.obj_treeViewInput)
Here is the code to add the leaves into the tree:
def insert_treeLeaves(self,total,tree_directParent):
for i in range(0,total):
"""leaves with color name"""
tree_child_leaf = QtGui.QTreeWidgetItem()
tree_directParent.addChild(tree_child_leaf)
Then, we have the function that tells us every time the tree is clicked, and where it was clicked:
def obj_treeViewInput(self,item,col):
print "obj _Qtree : pressed"
print "name:" item.text(col)
The problem is, how can we get if the touched leaf (red) belongs to the Bird or other father, i.e. how to get the following output give some mouse click:
Animal - Not extinct - Mammal - (red).
All comments and suggestions are highly appreciated.
|
[
"What about a method in each QtreeWidgetItem in which you could print the path to this item.\nIn this method, you could use recursion to get the complete path of the item's parents (you have a \"QTreeWidgetItem * parent () const\" method to do this) and you add the current item's text to its parent's path ! You stop the recursion when an item do not have any parent.\nI hope I understood your question and this helps you a little bit !\nDo you have your own QTreeWidgetItem class ? You could use a specific role to achieve this...\n"
] |
[
2
] |
[] |
[] |
[
"hierarchy",
"pyqt",
"python",
"qt",
"treeview"
] |
stackoverflow_0001824735_hierarchy_pyqt_python_qt_treeview.txt
|
Q:
Self import of subpackages or not?
Suppose you have the following
b
b/__init__.py
b/c
b/c/__init__.py
b/c/d
b/c/d/__init__.py
In some python packages, if you import b, you only get the symbols defined in b. To access b.c, you have to explicitly import b.c or from b import c. In other words, you have to
import b
import b.c
import b.c.d
print b.c.d
In other cases I saw an automatic import of all the subpackages. This means that the following code does not produce an error
import b
print b.c.d
because b/__init__.py takes care of importing its subpackages.
I tend to prefer the first (explicit better than implicit), and I always used it, but are there cases where the second one is preferred to the first?
A:
I like namespaces -- so I think that import b should only get what's in b itself (presumably in b/__init__.py). If there's a reason to segregate other functionality in b.c, b.c.d, or whatever, then just import b should not drag it all in -- if the "drag it all in" does happen, I think that suggests that the namespace separation was probably a bogus one to start with. Of course, there are examples even in the standard library (import os, then you can use os.path.join and the like), but they're ancient, by now essentially "grandfathered" things from way before the Python packaging system was mature and stable. In new code, I'd strongly recommend that a package should not drag its subpackages along for the ride when you import it. (Do import this at the Python prompt and contemplate the very last line it shows;-).
|
Self import of subpackages or not?
|
Suppose you have the following
b
b/__init__.py
b/c
b/c/__init__.py
b/c/d
b/c/d/__init__.py
In some python packages, if you import b, you only get the symbols defined in b. To access b.c, you have to explicitly import b.c or from b import c. In other words, you have to
import b
import b.c
import b.c.d
print b.c.d
In other cases I saw an automatic import of all the subpackages. This means that the following code does not produce an error
import b
print b.c.d
because b/__init__.py takes care of importing its subpackages.
I tend to prefer the first (explicit better than implicit), and I always used it, but are there cases where the second one is preferred to the first?
|
[
"I like namespaces -- so I think that import b should only get what's in b itself (presumably in b/__init__.py). If there's a reason to segregate other functionality in b.c, b.c.d, or whatever, then just import b should not drag it all in -- if the \"drag it all in\" does happen, I think that suggests that the namespace separation was probably a bogus one to start with. Of course, there are examples even in the standard library (import os, then you can use os.path.join and the like), but they're ancient, by now essentially \"grandfathered\" things from way before the Python packaging system was mature and stable. In new code, I'd strongly recommend that a package should not drag its subpackages along for the ride when you import it. (Do import this at the Python prompt and contemplate the very last line it shows;-).\n"
] |
[
5
] |
[
"__all__ = [your vars, functions, classes]\nUse syntax above in package b's __init__.py to auto load things listed in dict. :)\n"
] |
[
-1
] |
[
"package",
"python"
] |
stackoverflow_0001824001_package_python.txt
|
Q:
Is it possible for my linux machine (with no GUI) to hit Twitter sign up page, and then spit out a captcha in a webpage format
So that I can just type in the letters and register (through my linux box's IP)?
(twitter uses recaptcha)
Is there some way to grab that javascript, output it into a webpage. Then submit it through?
A:
Twitter offers a special API for services. Use that to automatically login from one of your programs to post tweets.
|
Is it possible for my linux machine (with no GUI) to hit Twitter sign up page, and then spit out a captcha in a webpage format
|
So that I can just type in the letters and register (through my linux box's IP)?
(twitter uses recaptcha)
Is there some way to grab that javascript, output it into a webpage. Then submit it through?
|
[
"Twitter offers a special API for services. Use that to automatically login from one of your programs to post tweets.\n"
] |
[
3
] |
[] |
[] |
[
"captcha",
"forms",
"http",
"python",
"twitter"
] |
stackoverflow_0001825186_captcha_forms_http_python_twitter.txt
|
Q:
What's the best way to divide large files in Python for multiprocessing?
I run across a lot of "embarrassingly parallel" projects I'd like to parallelize with the multiprocessing module. However, they often involve reading in huge files (greater than 2gb), processing them line by line, running basic calculations, and then writing results. What's the best way to split a file and process it using Python's multiprocessing module? Should Queue or JoinableQueue in multiprocessing be used? Or the Queue module itself? Or, should I map the file iterable over a pool of processes using multiprocessing? I've experimented with these approaches but the overhead is immense in distribution the data line by line. I've settled on a lightweight pipe-filters design by using cat file | process1 --out-file out1 --num-processes 2 | process2 --out-file out2, which passes a certain percentage of the first process's input directly to the second input (see this post), but I'd like to have a solution contained entirely in Python.
Surprisingly, the Python documentation doesn't suggest a canonical way of doing this (despite a lengthy section on programming guidelines in the multiprocessing documentation).
Thanks,
Vince
Additional information: Processing time per line varies. Some problems are fast and barely not I/O bound, some are CPU-bound. The CPU bound, non-dependent tasks will gain the post from parallelization, such that even inefficient ways of assigning data to a processing function would still be beneficial in terms of wall clock time.
A prime example is a script that extracts fields from lines, checks for a variety of bitwise flags, and writes lines with certain flags to a new file in an entirely new format. This seems like an I/O bound problem, but when I ran it with my cheap concurrent version with pipes, it was about 20% faster. When I run it with pool and map, or queue in multiprocessing it is always over 100% slower.
A:
One of the best architectures is already part of Linux OS's. No special libraries required.
You want a "fan-out" design.
A "main" program creates a number of subprocesses connected by pipes.
The main program reads the file, writing lines to the pipes doing the minimum filtering required to deal the lines to appropriate subprocesses.
Each subprocess should probably be a pipeline of distinct processes that read and write from stdin.
You don't need a queue data structure, that's exactly what an in-memory pipeline is -- a queue of bytes between two concurrent processes.
A:
One strategy is to assign each worker an offset so if you have eight worker processes you assign then numbers 0 to 7. Worker number 0 reads the first record processes it then skips 7 and goes on to process the 8th record etc., worker number 1 reads the second record then skips 7 and processes the 9th record.........
There are a number of advantages to this scheme. It doesnt matter how big the file is the work is always divided evenly, processes on the same machine will process at roughly the same rate, and use the same buffer areas so you dont incur any excessive I/O overhead. As long as the file hasnt been updated you can rerun individual threads to recover from failures.
A:
You dont mention how you are processing the lines; possibly the most important piece of info.
Is each line independant? Is the calculation dependant on one line coming before the next? Must they be processed in blocks? How long does the processing for each line take? Is there a processing step that must incorporate "all" the data at the end? Or can intermediate results be thrown away and just a running total maintained? Can the file be initially split by dividing filesize by count of threads? Or does it grow as you process it?
If the lines are independant and the file doesn't grow, the only coordination you need is to farm out "starting addresses" and "lengths" to each of the workers; they can independantly open and seek into the file and then you must simply coordinate their results; perhaps by waiting for N results to come back into a queue.
If the lines are not independant, the answer will depend highly on the structure of the file.
A:
It depends a lot on the format of your file.
Does it make sense to split it anywhere? Or do you need to split it at a new line? Or do you need to make sure that you split it at the end of an object definition?
Instead of splitting the file, you should use multiple readers on the same file, using os.lseek to jump to the appropriate part of the file.
Update: Poster added that he wants to split on new lines. Then I propose the following:
Let's say you have 4 processes. Then the simple solution is to os.lseek to 0%, 25%, 50% and 75% of the file, and read bytes until you hit the first new line. That's your starting point for each process. You don't need to split the file to do this, just seek to the right location in the large file in each process and start reading from there.
A:
I know you specifically asked about Python, but I will encourage you to look at Hadoop (http://hadoop.apache.org/): it implements the Map and Reduce algorithm which was specifically designed to address this kind of problem.
Good luck
A:
Fredrik Lundh's Some Notes on Tim Bray's Wide Finder Benchmark is an interesting read, about a very similar use case, with a lot of good advice. Various other authors also implemented the same thing, some are linked from the article, but you might want to try googling for "python wide finder" or something to find some more. (there was also a solution somewhere based on the multiprocessing module, but that doesn't seem to be available anymore)
A:
If the run time is long, instead of having each process read its next line through a Queue, have the processes read batches of lines. This way the overhead is amortized over several lines (e.g. thousands or more).
|
What's the best way to divide large files in Python for multiprocessing?
|
I run across a lot of "embarrassingly parallel" projects I'd like to parallelize with the multiprocessing module. However, they often involve reading in huge files (greater than 2gb), processing them line by line, running basic calculations, and then writing results. What's the best way to split a file and process it using Python's multiprocessing module? Should Queue or JoinableQueue in multiprocessing be used? Or the Queue module itself? Or, should I map the file iterable over a pool of processes using multiprocessing? I've experimented with these approaches but the overhead is immense in distribution the data line by line. I've settled on a lightweight pipe-filters design by using cat file | process1 --out-file out1 --num-processes 2 | process2 --out-file out2, which passes a certain percentage of the first process's input directly to the second input (see this post), but I'd like to have a solution contained entirely in Python.
Surprisingly, the Python documentation doesn't suggest a canonical way of doing this (despite a lengthy section on programming guidelines in the multiprocessing documentation).
Thanks,
Vince
Additional information: Processing time per line varies. Some problems are fast and barely not I/O bound, some are CPU-bound. The CPU bound, non-dependent tasks will gain the post from parallelization, such that even inefficient ways of assigning data to a processing function would still be beneficial in terms of wall clock time.
A prime example is a script that extracts fields from lines, checks for a variety of bitwise flags, and writes lines with certain flags to a new file in an entirely new format. This seems like an I/O bound problem, but when I ran it with my cheap concurrent version with pipes, it was about 20% faster. When I run it with pool and map, or queue in multiprocessing it is always over 100% slower.
|
[
"One of the best architectures is already part of Linux OS's. No special libraries required.\nYou want a \"fan-out\" design.\n\nA \"main\" program creates a number of subprocesses connected by pipes.\nThe main program reads the file, writing lines to the pipes doing the minimum filtering required to deal the lines to appropriate subprocesses.\n\nEach subprocess should probably be a pipeline of distinct processes that read and write from stdin.\nYou don't need a queue data structure, that's exactly what an in-memory pipeline is -- a queue of bytes between two concurrent processes.\n",
"One strategy is to assign each worker an offset so if you have eight worker processes you assign then numbers 0 to 7. Worker number 0 reads the first record processes it then skips 7 and goes on to process the 8th record etc., worker number 1 reads the second record then skips 7 and processes the 9th record.........\nThere are a number of advantages to this scheme. It doesnt matter how big the file is the work is always divided evenly, processes on the same machine will process at roughly the same rate, and use the same buffer areas so you dont incur any excessive I/O overhead. As long as the file hasnt been updated you can rerun individual threads to recover from failures.\n",
"You dont mention how you are processing the lines; possibly the most important piece of info.\nIs each line independant? Is the calculation dependant on one line coming before the next? Must they be processed in blocks? How long does the processing for each line take? Is there a processing step that must incorporate \"all\" the data at the end? Or can intermediate results be thrown away and just a running total maintained? Can the file be initially split by dividing filesize by count of threads? Or does it grow as you process it?\nIf the lines are independant and the file doesn't grow, the only coordination you need is to farm out \"starting addresses\" and \"lengths\" to each of the workers; they can independantly open and seek into the file and then you must simply coordinate their results; perhaps by waiting for N results to come back into a queue.\nIf the lines are not independant, the answer will depend highly on the structure of the file.\n",
"It depends a lot on the format of your file.\nDoes it make sense to split it anywhere? Or do you need to split it at a new line? Or do you need to make sure that you split it at the end of an object definition?\nInstead of splitting the file, you should use multiple readers on the same file, using os.lseek to jump to the appropriate part of the file.\nUpdate: Poster added that he wants to split on new lines. Then I propose the following:\nLet's say you have 4 processes. Then the simple solution is to os.lseek to 0%, 25%, 50% and 75% of the file, and read bytes until you hit the first new line. That's your starting point for each process. You don't need to split the file to do this, just seek to the right location in the large file in each process and start reading from there.\n",
"I know you specifically asked about Python, but I will encourage you to look at Hadoop (http://hadoop.apache.org/): it implements the Map and Reduce algorithm which was specifically designed to address this kind of problem. \nGood luck\n",
"Fredrik Lundh's Some Notes on Tim Bray's Wide Finder Benchmark is an interesting read, about a very similar use case, with a lot of good advice. Various other authors also implemented the same thing, some are linked from the article, but you might want to try googling for \"python wide finder\" or something to find some more. (there was also a solution somewhere based on the multiprocessing module, but that doesn't seem to be available anymore)\n",
"If the run time is long, instead of having each process read its next line through a Queue, have the processes read batches of lines. This way the overhead is amortized over several lines (e.g. thousands or more).\n"
] |
[
9,
6,
4,
1,
1,
1,
0
] |
[] |
[] |
[
"bioinformatics",
"concurrency",
"multiprocessing",
"python"
] |
stackoverflow_0001823300_bioinformatics_concurrency_multiprocessing_python.txt
|
Q:
Inheriting methods from a metaclass
In the example enumeration code given in this question, reproduced below, why does TOKEN contain the implementations of __contains__ and __repr__ from the metaclass EnumerationType?
from ctypes import *
class EnumerationType(type(c_uint)):
def __new__(metacls, name, bases, dict):
if not "_members_" in dict:
_members_ = {}
for key,value in dict.items():
if not key.startswith("_"):
_members_[key] = value
dict["_members_"] = _members_
cls = type(c_uint).__new__(metacls, name, bases, dict)
for key,value in cls._members_.items():
globals()[key] = value
return cls
def __contains__(self, value):
return value in self._members_.values()
def __repr__(self):
return "<Enumeration %s>" % self.__name__
class Enumeration(c_uint):
__metaclass__ = EnumerationType
_members_ = {}
def __init__(self, value):
for k,v in self._members_.items():
if v == value:
self.name = k
break
else:
raise ValueError("No enumeration member with value %r" % value)
c_uint.__init__(self, value)
@classmethod
def from_param(cls, param):
if isinstance(param, Enumeration):
if param.__class__ != cls:
raise ValueError("Cannot mix enumeration members")
else:
return param
else:
return cls(param)
def __repr__(self):
return "<member %s=%d of %r>" % (self.name, self.value, self.__class__)
class TOKEN(Enumeration):
_members_ = {'T_UNDEF':0, 'T_NAME':1, 'T_NUMBER':2, 'T_STRING':3, 'T_OPERATOR':4, 'T_VARIABLE':5, 'T_FUNCTION':6}
I would expect to have exceptions thrown by the following code to the effect that __contains__ is not implemented, instead however, I receive True False.
print 2 in TOKEN, 7 in TOKEN
A:
Both Enumeration and TOKEN are instances of EnumerationType:
>>> isinstance(Enumeration, EnumerationType)
True
>>> isinstance(TOKEN, EnumerationType)
True
And special methods for instances of new style classes are looked up in class, e.g. repr(TOKEN) is equivalent to type(TOKEN).__repr__(TOKEN), which is EnumerationType.__repr__(TOKEN).
|
Inheriting methods from a metaclass
|
In the example enumeration code given in this question, reproduced below, why does TOKEN contain the implementations of __contains__ and __repr__ from the metaclass EnumerationType?
from ctypes import *
class EnumerationType(type(c_uint)):
def __new__(metacls, name, bases, dict):
if not "_members_" in dict:
_members_ = {}
for key,value in dict.items():
if not key.startswith("_"):
_members_[key] = value
dict["_members_"] = _members_
cls = type(c_uint).__new__(metacls, name, bases, dict)
for key,value in cls._members_.items():
globals()[key] = value
return cls
def __contains__(self, value):
return value in self._members_.values()
def __repr__(self):
return "<Enumeration %s>" % self.__name__
class Enumeration(c_uint):
__metaclass__ = EnumerationType
_members_ = {}
def __init__(self, value):
for k,v in self._members_.items():
if v == value:
self.name = k
break
else:
raise ValueError("No enumeration member with value %r" % value)
c_uint.__init__(self, value)
@classmethod
def from_param(cls, param):
if isinstance(param, Enumeration):
if param.__class__ != cls:
raise ValueError("Cannot mix enumeration members")
else:
return param
else:
return cls(param)
def __repr__(self):
return "<member %s=%d of %r>" % (self.name, self.value, self.__class__)
class TOKEN(Enumeration):
_members_ = {'T_UNDEF':0, 'T_NAME':1, 'T_NUMBER':2, 'T_STRING':3, 'T_OPERATOR':4, 'T_VARIABLE':5, 'T_FUNCTION':6}
I would expect to have exceptions thrown by the following code to the effect that __contains__ is not implemented, instead however, I receive True False.
print 2 in TOKEN, 7 in TOKEN
|
[
"Both Enumeration and TOKEN are instances of EnumerationType:\n>>> isinstance(Enumeration, EnumerationType)\nTrue\n>>> isinstance(TOKEN, EnumerationType)\nTrue\n\nAnd special methods for instances of new style classes are looked up in class, e.g. repr(TOKEN) is equivalent to type(TOKEN).__repr__(TOKEN), which is EnumerationType.__repr__(TOKEN).\n"
] |
[
2
] |
[] |
[] |
[
"metaclass",
"python"
] |
stackoverflow_0001825544_metaclass_python.txt
|
Q:
Is SOAPpy the same thing as SOAPy?
I would normally read the documentation to figure that out, but the links from both websites are on sourceforge and both are 404ing.
A:
They appear to be 2 separate projects.
SOAPy was written by Adam Elman (from here.)
SOAPpy was originally written by Cayce Ullman and Brian Matthews (from here.)
|
Is SOAPpy the same thing as SOAPy?
|
I would normally read the documentation to figure that out, but the links from both websites are on sourceforge and both are 404ing.
|
[
"They appear to be 2 separate projects. \nSOAPy was written by Adam Elman (from here.) \nSOAPpy was originally written by Cayce Ullman and Brian Matthews (from here.)\n"
] |
[
2
] |
[] |
[] |
[
"python",
"soap",
"soappy"
] |
stackoverflow_0001825873_python_soap_soappy.txt
|
Q:
Decoding a WBXML SyncML message from an S60 device
I'm trying to decode a WBXML encoded SyncML message from a Nokia N95.
My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of <unknown> tags and a big chunk of binary within a <Collection> tag. I tried running the contents of the <Collection> through by itself but it failed. Is there something I'm missing?
Also, does anyone know of a pure python implementation of a wbxml parser? Failing that a command line or online tool to decode these messages would be useful -- it would make it a lot easier for me to write my own...
A:
Funnily enough I've been working on the same problem. I'm about halfway through writing my own pure-Python WBXML parser, but it's not yet complete enough to be useful, and I have very little time to work on it right now.
Those <Unknown> tags might be because pywbxml / libwbxml doesn't have the right tag vocabulary loaded. WBXML represents tags by an index number to avoid transmitting the same tag name hundreds of times, and the table that maps index numbers to tag names has to be supplied separately from the WBXML document itself. From a vague glance at the libwbxml source it seems like libwbxml has a bunch of tag tables hard coded. It has tables for SyncML 1.0-1.2; I think my Nokia E71 sends SyncML 1.3 (if so, your N95 probably does too), which it looks like libwbxml doesn't support yet.
Getting it to work might be as simple as adding a SyncML 1.3 table to libwbxml. That said, last time I tried, pywbxml doesn't compile against the vanilla libwbxml source, so you have to apply some patches first... so "simple" may be a relative term.
A:
I ended up writing a python parser myself. I managed to do it by following the spec here:
http://www.w3.org/TR/wbxml/
And then taking the code tables from the horde.org cvs.
The open mobile alliance's site and documentation are terrible, this was a very trying project :(
A:
I used pywbxml ,
Just needed one patch in pywbxml.pyx:
params.lang in function wbxml2xml around line 25 set to:
params.lang = WBXML_LANG_UNKNOWN
works like charm. Also changing base class for WBXMLParseError to exception helps:
class WBXMLParseError(Exception):
|
Decoding a WBXML SyncML message from an S60 device
|
I'm trying to decode a WBXML encoded SyncML message from a Nokia N95.
My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of <unknown> tags and a big chunk of binary within a <Collection> tag. I tried running the contents of the <Collection> through by itself but it failed. Is there something I'm missing?
Also, does anyone know of a pure python implementation of a wbxml parser? Failing that a command line or online tool to decode these messages would be useful -- it would make it a lot easier for me to write my own...
|
[
"Funnily enough I've been working on the same problem. I'm about halfway through writing my own pure-Python WBXML parser, but it's not yet complete enough to be useful, and I have very little time to work on it right now.\nThose <Unknown> tags might be because pywbxml / libwbxml doesn't have the right tag vocabulary loaded. WBXML represents tags by an index number to avoid transmitting the same tag name hundreds of times, and the table that maps index numbers to tag names has to be supplied separately from the WBXML document itself. From a vague glance at the libwbxml source it seems like libwbxml has a bunch of tag tables hard coded. It has tables for SyncML 1.0-1.2; I think my Nokia E71 sends SyncML 1.3 (if so, your N95 probably does too), which it looks like libwbxml doesn't support yet.\nGetting it to work might be as simple as adding a SyncML 1.3 table to libwbxml. That said, last time I tried, pywbxml doesn't compile against the vanilla libwbxml source, so you have to apply some patches first... so \"simple\" may be a relative term.\n",
"I ended up writing a python parser myself. I managed to do it by following the spec here:\nhttp://www.w3.org/TR/wbxml/\nAnd then taking the code tables from the horde.org cvs.\nThe open mobile alliance's site and documentation are terrible, this was a very trying project :(\n",
"I used pywbxml ,\nJust needed one patch in pywbxml.pyx:\nparams.lang in function wbxml2xml around line 25 set to:\nparams.lang = WBXML_LANG_UNKNOWN\n\nworks like charm. Also changing base class for WBXMLParseError to exception helps:\nclass WBXMLParseError(Exception):\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"python",
"s60",
"syncml",
"wbxml"
] |
stackoverflow_0000226279_python_s60_syncml_wbxml.txt
|
Q:
Django, updating a user profile with a ModelForm
I'm trying to display a simple ModelForm for a user's profile and allow the user to update it. The problem here is that my logic is somehow flawed, and after a successful form.save() call, the old values show on the page. It isn't until a refresh that the appropriate value is shown. What is wrong here?
@login_required
def user_profile(request):
success = False
user = User.objects.get(pk=request.user.id)
upform = UserProfileForm(instance=user.get_profile())
if request.method == 'POST':
userprofile = UserProfileForm(request.POST, instance=user.get_profile())
if userprofile.is_valid():
up = userprofile.save(commit=False)
up.user = request.user
up.save()
success = True
return render_to_response('profile/index.html',
locals(), context_instance=RequestContext(request))
I'm just looking to update an existing profile, not add a new one.
A:
Try this:
@login_required
def user_profile(request):
success = False
user = User.objects.get(pk=request.user.id)
if request.method == 'POST':
upform = UserProfileForm(request.POST, instance=user.get_profile())
if upform.is_valid():
up = upform.save(commit=False)
up.user = request.user
up.save()
success = True
else:
upform = UserProfileForm(instance=user.get_profile())
return render_to_response('profile/index.html',
locals(), context_instance=RequestContext(request))
A:
You could also use a generic view:
from django.views.generic.create_update import update_object
@login_required
def user_profile(request):
return update_object(request,
form_class=UserProfileForm,
object_id=request.user.get_profile().id,
template_name='profile/index.html')
|
Django, updating a user profile with a ModelForm
|
I'm trying to display a simple ModelForm for a user's profile and allow the user to update it. The problem here is that my logic is somehow flawed, and after a successful form.save() call, the old values show on the page. It isn't until a refresh that the appropriate value is shown. What is wrong here?
@login_required
def user_profile(request):
success = False
user = User.objects.get(pk=request.user.id)
upform = UserProfileForm(instance=user.get_profile())
if request.method == 'POST':
userprofile = UserProfileForm(request.POST, instance=user.get_profile())
if userprofile.is_valid():
up = userprofile.save(commit=False)
up.user = request.user
up.save()
success = True
return render_to_response('profile/index.html',
locals(), context_instance=RequestContext(request))
I'm just looking to update an existing profile, not add a new one.
|
[
"Try this:\n@login_required\ndef user_profile(request):\n success = False\n user = User.objects.get(pk=request.user.id)\n if request.method == 'POST':\n upform = UserProfileForm(request.POST, instance=user.get_profile())\n if upform.is_valid():\n up = upform.save(commit=False)\n up.user = request.user\n up.save()\n success = True\n else:\n upform = UserProfileForm(instance=user.get_profile()) \n\n return render_to_response('profile/index.html',\n locals(), context_instance=RequestContext(request))\n\n",
"You could also use a generic view:\nfrom django.views.generic.create_update import update_object\n\n@login_required\ndef user_profile(request):\n return update_object(request,\n form_class=UserProfileForm,\n object_id=request.user.get_profile().id,\n template_name='profile/index.html')\n\n"
] |
[
8,
3
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001823588_django_python.txt
|
Q:
Suppress linebreak on file.write
When writing to a text file, some of the file.write instances are followed by a linebreak in the output file and others aren't. I don't want linebreaks except where I tell them to occur. Code:
for doc,wc in wordcounts.items():
out.write(doc) #this works fine, no linebreak
for word in wordlist:
if word in wc: out.write("\t%d" % wc[word]) #linebreaks appear
else: out.write("\t0") #after each of these
out.write("\n") #this line had mixed spaces/tabs
What am I missing?
Update
I should have taken a clue from how the code pasted into SO. For some reason there was a mixture of spaces and tabs in the final line, such that in TextMate it visually appeared outside the "for word..." loopβbut the interpreter was treating it as part of that loop. Converting spaces to tabs solved the problem.
Thanks for your input.
A:
file.write() does not add any newlines if the string you write does not contain any \ns.
But you force a newline for each word in your word list using out.write("\n"), is that what you want?
for doc,wc in wordcounts.items():
out.write(doc) #this works fine, no linebreak
for word in wordlist:
if word in wc: out.write("\t%d" % wc[word]) #linebreaks appear
else: out.write("\t0") #after each of these
out.write("\n") #<--- NEWLINE ON EACH ITERATION!
Perhaps you indented out.write("\n") too far???
A:
You write a line breaks after every word:
for word in wordlist:
...
out.write("\n")
Are these the line breaks you are seeing, or are there more additional ones?
A:
You might need to perform a strip() on each wc[word]. Printing a single item from wc is would probably be enough to determine if there are already line breaks on those items that area causing this behavior.
Either that or the indentation on your final out.write("\n") is not doing what you intended it to do.
A:
I think your indentation is wrong.
(also I took the liberty to make your if clause redundant and code more readable :)
for doc,wc in wordcounts.items()
out.write(doc)
for word in wordlist:
out.write("\t%d" % wc.get(word,0))
out.write("\n")
|
Suppress linebreak on file.write
|
When writing to a text file, some of the file.write instances are followed by a linebreak in the output file and others aren't. I don't want linebreaks except where I tell them to occur. Code:
for doc,wc in wordcounts.items():
out.write(doc) #this works fine, no linebreak
for word in wordlist:
if word in wc: out.write("\t%d" % wc[word]) #linebreaks appear
else: out.write("\t0") #after each of these
out.write("\n") #this line had mixed spaces/tabs
What am I missing?
Update
I should have taken a clue from how the code pasted into SO. For some reason there was a mixture of spaces and tabs in the final line, such that in TextMate it visually appeared outside the "for word..." loopβbut the interpreter was treating it as part of that loop. Converting spaces to tabs solved the problem.
Thanks for your input.
|
[
"file.write() does not add any newlines if the string you write does not contain any \\ns.\nBut you force a newline for each word in your word list using out.write(\"\\n\"), is that what you want?\n for doc,wc in wordcounts.items(): \n out.write(doc) #this works fine, no linebreak\n for word in wordlist: \n if word in wc: out.write(\"\\t%d\" % wc[word]) #linebreaks appear\n else: out.write(\"\\t0\") #after each of these\n out.write(\"\\n\") #<--- NEWLINE ON EACH ITERATION!\n\nPerhaps you indented out.write(\"\\n\") too far???\n",
"You write a line breaks after every word:\nfor word in wordlist:\n ...\n out.write(\"\\n\")\n\nAre these the line breaks you are seeing, or are there more additional ones?\n",
"You might need to perform a strip() on each wc[word]. Printing a single item from wc is would probably be enough to determine if there are already line breaks on those items that area causing this behavior. \nEither that or the indentation on your final out.write(\"\\n\") is not doing what you intended it to do.\n",
"I think your indentation is wrong.\n(also I took the liberty to make your if clause redundant and code more readable :)\nfor doc,wc in wordcounts.items()\n out.write(doc)\n for word in wordlist:\n out.write(\"\\t%d\" % wc.get(word,0))\n out.write(\"\\n\")\n\n"
] |
[
13,
1,
1,
0
] |
[] |
[] |
[
"file",
"line_breaks",
"python"
] |
stackoverflow_0001826400_file_line_breaks_python.txt
|
Q:
Passing a list to eval()
Is there a way to pass a list as a function argument to eval() Or do I have to convert it to a string and then parse it as a list in the function?
My simple example looks like:
eval("func1(\'" + fArgs + "\')")
I'm just not sure if there is a better way of taking fArgs as a list instead of a string
Note:
The list is provided from a JSON response
EDIT: Ok here's a bit more of my class so there's a better understanding of how I'm using eval
def test(arg):
print arg
#Add all allowed functions to this list to be mapped to a dictionary
safe_list = ['test']
safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
class Validate:
def __init__(self, Value, fName, fArgs):
eval(fName + "(\'" + fArgs + "\')", {"__builtins__":None},safe_dict)
I may be wrong in thinking this, but to my understanding this is a safe use of eval because the only functions that can be called are the ones that are listed in the safe_list dictionary. The function to be run and the arguments for that function are being extracted out of a JSON object. The arguments are to be structured as a list, Will joining the list together with ", " be interpreted as actual arguments or just a single argument?
A:
If you're using Python 2.6.x, then you should be able to use the json module (see py doc 19.2). If not, then there is python-json available through the python package index. Both of these packages will provide a reader for parsing JSON data into an appropriate Python data type.
For your second problem of calling a function determined by a message, you can do the following:
def foo():
print 'I am foo!'
def bar():
pass
def baz():
pass
funcs = {'func_a':foo, 'func_b':bar, 'func_c':baz}
funcs['func_a']()
This approach can be a bit more secure than eval because it prevents 'unsafe' python library functions from being injected into the JSON. However, you still need to be cautious that the data supplied to your functions can't be manipulated to cause problems.
A:
Specifying parameters the following way works:
root@parrot$ more test.py
def func1(*args):
for i in args:
print i
l = [1,'a',9.1]
func1(*l)
root@parrot$ python test.py
1
a
9.1
so, no direct need for eval(), unless I'm misunderstanding something.
A:
Using a library to parse JSON input may be a better approach than eval, something like:
import json
func1(json.loads(fArgs))
Assert-ing that user input is correct would be a good idea, too.
A:
The others have a good point, that you shouldn't be using eval. But, if you must:
eval("func1(%s)" % ", ".join(fArgs))
will call the function with all the arguments in the list. This:
eval("func1([%s])" % ", ".join(fArgs))
will call it with the list of arguments in just one argument. Maybe you even want this?
eval("func1([%s])" % ", ".join(map(eval, fArgs)))
which would eval the arguments as well?
|
Passing a list to eval()
|
Is there a way to pass a list as a function argument to eval() Or do I have to convert it to a string and then parse it as a list in the function?
My simple example looks like:
eval("func1(\'" + fArgs + "\')")
I'm just not sure if there is a better way of taking fArgs as a list instead of a string
Note:
The list is provided from a JSON response
EDIT: Ok here's a bit more of my class so there's a better understanding of how I'm using eval
def test(arg):
print arg
#Add all allowed functions to this list to be mapped to a dictionary
safe_list = ['test']
safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
class Validate:
def __init__(self, Value, fName, fArgs):
eval(fName + "(\'" + fArgs + "\')", {"__builtins__":None},safe_dict)
I may be wrong in thinking this, but to my understanding this is a safe use of eval because the only functions that can be called are the ones that are listed in the safe_list dictionary. The function to be run and the arguments for that function are being extracted out of a JSON object. The arguments are to be structured as a list, Will joining the list together with ", " be interpreted as actual arguments or just a single argument?
|
[
"If you're using Python 2.6.x, then you should be able to use the json module (see py doc 19.2). If not, then there is python-json available through the python package index. Both of these packages will provide a reader for parsing JSON data into an appropriate Python data type.\nFor your second problem of calling a function determined by a message, you can do the following:\ndef foo():\n print 'I am foo!'\ndef bar():\n pass\ndef baz():\n pass\n\nfuncs = {'func_a':foo, 'func_b':bar, 'func_c':baz}\n\nfuncs['func_a']()\n\nThis approach can be a bit more secure than eval because it prevents 'unsafe' python library functions from being injected into the JSON. However, you still need to be cautious that the data supplied to your functions can't be manipulated to cause problems.\n",
"Specifying parameters the following way works:\nroot@parrot$ more test.py\ndef func1(*args):\n for i in args:\n print i\n\nl = [1,'a',9.1]\nfunc1(*l)\n\nroot@parrot$ python test.py\n1\na\n9.1\n\nso, no direct need for eval(), unless I'm misunderstanding something.\n",
"Using a library to parse JSON input may be a better approach than eval, something like:\nimport json\nfunc1(json.loads(fArgs))\n\nAssert-ing that user input is correct would be a good idea, too.\n",
"The others have a good point, that you shouldn't be using eval. But, if you must:\neval(\"func1(%s)\" % \", \".join(fArgs))\n\nwill call the function with all the arguments in the list. This:\neval(\"func1([%s])\" % \", \".join(fArgs))\n\nwill call it with the list of arguments in just one argument. Maybe you even want this?\neval(\"func1([%s])\" % \", \".join(map(eval, fArgs)))\n\nwhich would eval the arguments as well?\n"
] |
[
7,
2,
2,
0
] |
[] |
[] |
[
"eval",
"json",
"list",
"python"
] |
stackoverflow_0001826467_eval_json_list_python.txt
|
Q:
Outgoing load balancer
I have a big threaded feed retrieval script in python.
My question is, how can I load balance outgoing requests so that I don't hit any one host too often?
This is a big problem for feedburner, since a large percentage of sites proxy their RSS through feedburner and to further complicate matters many sites will alias a subdomain on their domain to feedburner to obscure the fact that they're using it (e.g. "mysite" sets its RSS url to feeds.mysite.com/mysite, where feeds.mysite.com bounces to feedburner). Sometimes it blocks me for awhile and redirects to their "automated requests" error page.
A:
You should probably do a one-time request (per week/month, whatever fits). for each feed and follow redirects to get the "true" address. Regardless of your throttling situation at the time, you should be able to resolve all feeds, save that data and then just do it once for every new feed you add to the list. You can look at urllib's geturl() as it returns the final url from the URL you put into it. When you do ping the feeds, be sure to use the original (keep the "real" simply for load-balancing) to make sure it redirects properly if the user has moved it or similar.
Once that is done, you can simply devise a load mechanism such as only X requests per hour for a given domain, going through each feed and skipping feeds whose hosts have hit the limit. If feedburner keeps their limits public (not likely) you can use that for X, but otherwise you will just have to estimate it and make a rough estimate that you know to be below the limit. Knowing google however, their limits might measure patterns and not have a specific hard limit.
Edit: Added suggestion from comment.
A:
If your problem is related to Feedburner "throttling you", it most certainly does this because of the source IP of your bot. The way to "load balance to Feedburner" would be to have multiple different source IPs to start from.
Now there are numerous ways to achieving this, 2 of them being:
Multi-homed server: multiple IPs on the same machine
Multiple discrete machines
Of course, don't you go a put a NAT box in front of them now ;-)
The above takes care of the possible "throttling problems", now for the "scheduling part". You should maintain a "virtual scheduler" per "destination" and make sure not to exceed the parameters of the Web Service (e.g. Feedburner) in question. Now, the tricky part is to get hold of these "limits"... sometimes they are advertised and sometimes you need to figure them out experimentally.
I understand this is "high level architectural guidelines" but I am not ready to be coding this for you... I hope you forgive me ;-)
A:
"how can I load balance outgoing requests so that I don't hit any one host too often?"
Generally, you do this by designing a better algorithm.
For example, randomly scramble your requests.
Or shuffle them 'fairly' so so that you round-robin through the sources. That would be a simple list of queues where you dequeue one request from each host.
|
Outgoing load balancer
|
I have a big threaded feed retrieval script in python.
My question is, how can I load balance outgoing requests so that I don't hit any one host too often?
This is a big problem for feedburner, since a large percentage of sites proxy their RSS through feedburner and to further complicate matters many sites will alias a subdomain on their domain to feedburner to obscure the fact that they're using it (e.g. "mysite" sets its RSS url to feeds.mysite.com/mysite, where feeds.mysite.com bounces to feedburner). Sometimes it blocks me for awhile and redirects to their "automated requests" error page.
|
[
"You should probably do a one-time request (per week/month, whatever fits). for each feed and follow redirects to get the \"true\" address. Regardless of your throttling situation at the time, you should be able to resolve all feeds, save that data and then just do it once for every new feed you add to the list. You can look at urllib's geturl() as it returns the final url from the URL you put into it. When you do ping the feeds, be sure to use the original (keep the \"real\" simply for load-balancing) to make sure it redirects properly if the user has moved it or similar.\nOnce that is done, you can simply devise a load mechanism such as only X requests per hour for a given domain, going through each feed and skipping feeds whose hosts have hit the limit. If feedburner keeps their limits public (not likely) you can use that for X, but otherwise you will just have to estimate it and make a rough estimate that you know to be below the limit. Knowing google however, their limits might measure patterns and not have a specific hard limit.\nEdit: Added suggestion from comment.\n",
"If your problem is related to Feedburner \"throttling you\", it most certainly does this because of the source IP of your bot. The way to \"load balance to Feedburner\" would be to have multiple different source IPs to start from.\nNow there are numerous ways to achieving this, 2 of them being:\n\nMulti-homed server: multiple IPs on the same machine\nMultiple discrete machines\n\nOf course, don't you go a put a NAT box in front of them now ;-)\n\nThe above takes care of the possible \"throttling problems\", now for the \"scheduling part\". You should maintain a \"virtual scheduler\" per \"destination\" and make sure not to exceed the parameters of the Web Service (e.g. Feedburner) in question. Now, the tricky part is to get hold of these \"limits\"... sometimes they are advertised and sometimes you need to figure them out experimentally.\nI understand this is \"high level architectural guidelines\" but I am not ready to be coding this for you... I hope you forgive me ;-)\n",
"\"how can I load balance outgoing requests so that I don't hit any one host too often?\"\nGenerally, you do this by designing a better algorithm.\nFor example, randomly scramble your requests.\nOr shuffle them 'fairly' so so that you round-robin through the sources. That would be a simple list of queues where you dequeue one request from each host.\n"
] |
[
3,
2,
1
] |
[] |
[] |
[
"feedburner",
"load_balancing",
"networking",
"python",
"web_crawler"
] |
stackoverflow_0001827018_feedburner_load_balancing_networking_python_web_crawler.txt
|
Q:
The best way to join two dissimilar mySQL tables -- planning for django from python
table a (t_a):
id name last first email state country
0 sklass klass steve sklass@foo.com in uk
1 jabid abid john abid@foo.com ny us
2 jcolle colle john jcolle@foo.com wi us
table b (t_b):
id sn given nick email l c
0 steven klass steve sklass@foo.com in uk
1 john abid - abid_j@foo.com ny us
2 johnny colle john jcolle@foo.com wi us
3 john abid - abid@foo.com ny us
What is listed above is an (abbreviated) column and row mySQL tables. Looking at the two tables it becomes pretty clear that by strictly looking at the values (id's not looked at) and comparing the matching number of values you would get these value matches.
t_a t_b
0 0
1 3
2 2
- 1
What I ultimately looking to do is to do this in Django β I'm not sure if that matters. In the past I have done this using pure python in which I destroy the old data and just create three new tables. I want to shift away from my implementation (listed below) because the problems I see is that time changes things and people come and go. In the past I have just regenerated the data -- but now I want to keep track of when people leave and don't simply replace (delete) the data. I believe that by doing a SQL update is more elegant and preserves the history.
I'd like to know how to get this merged answer directly from mySQL (Either a SQL function or the construction of a new table) which merges the data in the following manner. I want to do this using pure SQL (I believe then I can do this in Django). So I am looking for a solution which meets the following criteria:
There is a min_match which defines the minimum number of matches between the two rows of which must be aligned to be considered valid.
While the tables may have different lengths it is a 1-to-1 mapping. In other words many to one may not happen (yet)
Now my background is python and for me the simplest way to do this has always been to do a for loop over the shorter of the two tables, which then does a for loop over the other table looking at the number of matches. In code this looks like this.
t_a = [ ["sklass", "klass", "steve", "sklass@foo.com", "in", "uk", ],
["jabid", "abid", "john", "abid@foo.com", "ny", "us", ],
["jcolle", "colle", "john", "jcolle@foo.com", "wi", "us", ], ]
t_b = [ ["steven", "klass", "steve", "sklass@foo.com", "in", "uk",],
["john", "abid", "abid_j@foo.com", "ny", "us",],
["johnny", "colle", "john", "jcolle@foo.com", "wi", "us",],
["john", "abid", "abid@foo.com", "ny", "us",], ]
min_match = 3
for person_a in t_a:
match = 0
match_pct = 0.0
match_a_index = t_a.index(person_a)
for person_b in t_b:
new_match_count = len(list(set(person_a) & set(person_b)))
if new_match_count > match:
match = new_match_count
match_b_index = t_b.index(person_b)
match_pct = "%.2f" % (float(new_match_count) / \
float(len(set(person_a + person_b))) * 100)
if match >= min_match:
print match_a_index, match_b_index #, match_pct, match
The comments beg the question why don't you just join on the email address. I don't necessarily know that the values in a column will match. I am certain that values from a given row in t_a will match values for a row in t_b. I want the highest (most probable) match for a given row in t_a to t_b and only if the number of matches is higher than min_match.
A:
You can do this in MySQL directly via a cursor executed through a stored procedure.
DELIMITER $$
CREATE PROCEDURE `proc_name`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE a_id BIGINT UNSIGNED;
DECLARE b_id BIGINT UNSIGNED;
DECLARE x_count INT;
-- something like the following
DECLARE cur1 CURSOR FOR SELECT t_a.id, t_b.id FROM t_a, t_b WHERE t_a.email = t_b.email;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SELECT COUNT(*) INTO x_count FROM t_a, t_b WHERE t_a.email = t_b.email;
IF(x_count > <some_min_value>) THEN
OPEN cur1;
REPEAT
FETCH cur1 INTO a_id, b_id;
IF NOT done THEN
-- do something here like update rows, remove rows, etc.
-- a_id and b_id hold the two id values for the two tables which
-- I assume to be primary keys
END IF;
UNTIL done END REPEAT;
CLOSE cur1;
END IF;
END
$$
|
The best way to join two dissimilar mySQL tables -- planning for django from python
|
table a (t_a):
id name last first email state country
0 sklass klass steve sklass@foo.com in uk
1 jabid abid john abid@foo.com ny us
2 jcolle colle john jcolle@foo.com wi us
table b (t_b):
id sn given nick email l c
0 steven klass steve sklass@foo.com in uk
1 john abid - abid_j@foo.com ny us
2 johnny colle john jcolle@foo.com wi us
3 john abid - abid@foo.com ny us
What is listed above is an (abbreviated) column and row mySQL tables. Looking at the two tables it becomes pretty clear that by strictly looking at the values (id's not looked at) and comparing the matching number of values you would get these value matches.
t_a t_b
0 0
1 3
2 2
- 1
What I ultimately looking to do is to do this in Django β I'm not sure if that matters. In the past I have done this using pure python in which I destroy the old data and just create three new tables. I want to shift away from my implementation (listed below) because the problems I see is that time changes things and people come and go. In the past I have just regenerated the data -- but now I want to keep track of when people leave and don't simply replace (delete) the data. I believe that by doing a SQL update is more elegant and preserves the history.
I'd like to know how to get this merged answer directly from mySQL (Either a SQL function or the construction of a new table) which merges the data in the following manner. I want to do this using pure SQL (I believe then I can do this in Django). So I am looking for a solution which meets the following criteria:
There is a min_match which defines the minimum number of matches between the two rows of which must be aligned to be considered valid.
While the tables may have different lengths it is a 1-to-1 mapping. In other words many to one may not happen (yet)
Now my background is python and for me the simplest way to do this has always been to do a for loop over the shorter of the two tables, which then does a for loop over the other table looking at the number of matches. In code this looks like this.
t_a = [ ["sklass", "klass", "steve", "sklass@foo.com", "in", "uk", ],
["jabid", "abid", "john", "abid@foo.com", "ny", "us", ],
["jcolle", "colle", "john", "jcolle@foo.com", "wi", "us", ], ]
t_b = [ ["steven", "klass", "steve", "sklass@foo.com", "in", "uk",],
["john", "abid", "abid_j@foo.com", "ny", "us",],
["johnny", "colle", "john", "jcolle@foo.com", "wi", "us",],
["john", "abid", "abid@foo.com", "ny", "us",], ]
min_match = 3
for person_a in t_a:
match = 0
match_pct = 0.0
match_a_index = t_a.index(person_a)
for person_b in t_b:
new_match_count = len(list(set(person_a) & set(person_b)))
if new_match_count > match:
match = new_match_count
match_b_index = t_b.index(person_b)
match_pct = "%.2f" % (float(new_match_count) / \
float(len(set(person_a + person_b))) * 100)
if match >= min_match:
print match_a_index, match_b_index #, match_pct, match
The comments beg the question why don't you just join on the email address. I don't necessarily know that the values in a column will match. I am certain that values from a given row in t_a will match values for a row in t_b. I want the highest (most probable) match for a given row in t_a to t_b and only if the number of matches is higher than min_match.
|
[
"You can do this in MySQL directly via a cursor executed through a stored procedure.\nDELIMITER $$\nCREATE PROCEDURE `proc_name`()\nBEGIN\n DECLARE done INT DEFAULT 0;\n DECLARE a_id BIGINT UNSIGNED;\n DECLARE b_id BIGINT UNSIGNED;\n DECLARE x_count INT;\n\n -- something like the following\n DECLARE cur1 CURSOR FOR SELECT t_a.id, t_b.id FROM t_a, t_b WHERE t_a.email = t_b.email;\n DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;\n\n SELECT COUNT(*) INTO x_count FROM t_a, t_b WHERE t_a.email = t_b.email;\n\n IF(x_count > <some_min_value>) THEN\n\n OPEN cur1;\n\n REPEAT\n FETCH cur1 INTO a_id, b_id;\n IF NOT done THEN\n\n -- do something here like update rows, remove rows, etc.\n -- a_id and b_id hold the two id values for the two tables which\n -- I assume to be primary keys\n\n END IF;\n UNTIL done END REPEAT;\n\n CLOSE cur1;\n\n END IF;\nEND\n$$\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_models",
"mysql",
"python"
] |
stackoverflow_0001826686_django_django_models_mysql_python.txt
|
Q:
import from {in,out}side of a packages
I have a project I build on a library I'm building in parallel. The structure is the following :
project/
main.py
MyLibrary/
__init__.py --> empty
Module1.py --> contain the class Class1
Module2.py --> contain the class Class2
Module3.py --> contain the class Class3
...
I need to import the class Class2 into Class1.py, if I do
from Module1 import Class1
it's ok. But when in project/main.py I do
from MyLibrary import Module1
I got ImportError: No module name Module1
I could solve the issue by replacing:
from Module1 import Class1
by
from .Module1 import Class1
But then I'm not able any more to run Module1.py direcly (Python complain that I'm trying to do a relative impact on a non package...). And I need that to run test.
How I could I have import that work in both case ?
Thank for your attention !
edit: the first described solution seems to work on my linux desktop but not on my windows Xp powerred laptop. It's weird...
A:
The behavior you're experiencing (where imports work normally on one machine and not another) often happens because you've got multiple packages named MyLibrary on one system and your PYTHONPATH doesn't list '.' first.
To test if this is the problem, in the project directory, run Python and do
>>> import MyLibrary
>>> print MyLibrary
and see if the path to MyLibrary matches your expectations. If it doesn't, tweak your PYTHONPATH and/or delete the outdated version of your package.
A common way to avoid this sort of problem is to use virtualenv to create an isolated Python environment.
|
import from {in,out}side of a packages
|
I have a project I build on a library I'm building in parallel. The structure is the following :
project/
main.py
MyLibrary/
__init__.py --> empty
Module1.py --> contain the class Class1
Module2.py --> contain the class Class2
Module3.py --> contain the class Class3
...
I need to import the class Class2 into Class1.py, if I do
from Module1 import Class1
it's ok. But when in project/main.py I do
from MyLibrary import Module1
I got ImportError: No module name Module1
I could solve the issue by replacing:
from Module1 import Class1
by
from .Module1 import Class1
But then I'm not able any more to run Module1.py direcly (Python complain that I'm trying to do a relative impact on a non package...). And I need that to run test.
How I could I have import that work in both case ?
Thank for your attention !
edit: the first described solution seems to work on my linux desktop but not on my windows Xp powerred laptop. It's weird...
|
[
"The behavior you're experiencing (where imports work normally on one machine and not another) often happens because you've got multiple packages named MyLibrary on one system and your PYTHONPATH doesn't list '.' first.\nTo test if this is the problem, in the project directory, run Python and do\n>>> import MyLibrary\n>>> print MyLibrary\n\nand see if the path to MyLibrary matches your expectations. If it doesn't, tweak your PYTHONPATH and/or delete the outdated version of your package.\nA common way to avoid this sort of problem is to use virtualenv to create an isolated Python environment.\n"
] |
[
1
] |
[] |
[] |
[
"import",
"python"
] |
stackoverflow_0001783996_import_python.txt
|
Q:
In python how can I check to see if an object has a value?
Base Account
class BaseAccount(models.Model):
user = models.ForeignKey(User, unique=True)
def __unicode__(self):
"""
Return the unicode representation of this customer, which is the user's
full name, if set, otherwise, the user's username
"""
fn = self.user.get_full_name()
if fn:
return fn
return self.user.username
def user_name(self):
"""
Returns the full name of the related user object
"""
return self.user.get_full_name()
def email(self):
"""
Return the email address of the related user object
"""
return self.user.email
def is_store(self):
#try:
# self.user.is_store
# return True
#except ObjectDoesNotExist:
# return False
return self.user.is_store
def is_professional(self):
try:
self.user.is_professional
return True
except ObjectDoesNotExist:
return False
Account Class
class Account(BaseAccount):
"""
The account is an extension of the Django user and serves as the profile
object in user.get_profile() for shop purchases and sessions
"""
telephone = models.CharField(max_length=32)
default_address = models.ForeignKey(Address, related_name='billing_account', blank=True, null=True)
security_question = models.ForeignKey(SecurityQuestion)
security_answer = models.CharField(max_length=200)
how_heard = models.CharField("How did you hear about us?", max_length=100)
feedback = models.TextField(blank=True)
opt_in = models.BooleanField("Subscribe to mailing list", help_text="Please tick here if you would like to receive updates from %s" % Site.objects.get_current().name)
temporary = models.BooleanField()
def has_placed_orders(self):
"""
Returns True if the user has placed at least one order, False otherwise
"""
return self.order_set.count() > 0
def get_last_order(self):
"""
Returns the latest order that this customer has placed. If no orders
have been placed, then None is returned
"""
try:
return self.order_set.all().order_by('-date')[0]
except IndexError:
return None
def get_currency(self):
"""
Get the currency for this customer. If global currencies are enabled
(settings.ENABLE_GLOBAL_CURRENCIES) then this function will return
the currency related to their default address, otherwise, it returns
the site default
"""
if settings.ENABLE_GLOBAL_CURRENCIES:
return self.default_address.country.currency
return Currency.get_default_currency()
currency = property(get_currency)
def get_gateway_currency(self):
"""
Get the currency that an order will be put through protx with. If protx
currencies are enabled (settings.ENABLE_PROTX_CURRENCIES), then the
currency will be the same returned by get_currency, otherwise, the
site default is used
"""
if settings.ENABLE_PROTX_CURRENCIES and settings.ENABLE_GLOBAL_CURRENCIES:
return self.currency
return Currency.get_default_currency()
gateway_currency = property(get_gateway_currency)
Address Class
class Address(models.Model):
"""
This class encapsulates the data required for postage and payment mechanisms
across the site. Each address is associated with a single store account
"""
trade_user = models.BooleanField("Are you a stockist of Neal & Wolf Products", help_text="Please here if you are a Neal & Wolf Stockist")
company_name = models.CharField(max_length=32, blank=True)
line1 = models.CharField(max_length=200)
line2 = models.CharField(max_length=200, blank=True)
line3 = models.CharField(max_length=200, blank=True)
city = models.CharField(max_length=32)
county = models.CharField(max_length=32)
postcode = models.CharField(max_length=12)
country = models.ForeignKey(Country)
account = models.ForeignKey('Account')
class Meta:
"""
Django meta options
verbose_name_plural = "Addresses"
"""
verbose_name_plural = "Addresses"
def __unicode__(self):
"""
The unicode representation of this address, the postcode plus the county
"""
return ', '.join((self.postcode, str(self.county)))
def line_list(self):
"""
Return a list of all of this objects address lines that are not blank,
in the natural order that you'd expect to see them. This is useful for
outputting to a template with the aid of python String.join()
"""
return [val for val in (self.line1, self.line2, self.line3, self.city, self.county, self.postcode, self.country.name) if val]
About see three classes my question is easy how do i find out whether or not the user, is a trade user(this value is gathered in the Address class)
Thanks
A:
If the Account class is your user profile, as its docstring suggests, then you should be able to do something like this:
is_trade_user = user.get_profile().default_address.trade_user
if the definition of a trade user is "Has a default address for which trade_user is true"
On the other hand, if the definition of trade user is "Has any address for which trade_user is true" then you will need to do something more complicated -- check all of the addresses, and return true if any of them have trade_user set:
is_trade_user = user.get_profile().address_set.filter(trade_user=True).count() > 0
|
In python how can I check to see if an object has a value?
|
Base Account
class BaseAccount(models.Model):
user = models.ForeignKey(User, unique=True)
def __unicode__(self):
"""
Return the unicode representation of this customer, which is the user's
full name, if set, otherwise, the user's username
"""
fn = self.user.get_full_name()
if fn:
return fn
return self.user.username
def user_name(self):
"""
Returns the full name of the related user object
"""
return self.user.get_full_name()
def email(self):
"""
Return the email address of the related user object
"""
return self.user.email
def is_store(self):
#try:
# self.user.is_store
# return True
#except ObjectDoesNotExist:
# return False
return self.user.is_store
def is_professional(self):
try:
self.user.is_professional
return True
except ObjectDoesNotExist:
return False
Account Class
class Account(BaseAccount):
"""
The account is an extension of the Django user and serves as the profile
object in user.get_profile() for shop purchases and sessions
"""
telephone = models.CharField(max_length=32)
default_address = models.ForeignKey(Address, related_name='billing_account', blank=True, null=True)
security_question = models.ForeignKey(SecurityQuestion)
security_answer = models.CharField(max_length=200)
how_heard = models.CharField("How did you hear about us?", max_length=100)
feedback = models.TextField(blank=True)
opt_in = models.BooleanField("Subscribe to mailing list", help_text="Please tick here if you would like to receive updates from %s" % Site.objects.get_current().name)
temporary = models.BooleanField()
def has_placed_orders(self):
"""
Returns True if the user has placed at least one order, False otherwise
"""
return self.order_set.count() > 0
def get_last_order(self):
"""
Returns the latest order that this customer has placed. If no orders
have been placed, then None is returned
"""
try:
return self.order_set.all().order_by('-date')[0]
except IndexError:
return None
def get_currency(self):
"""
Get the currency for this customer. If global currencies are enabled
(settings.ENABLE_GLOBAL_CURRENCIES) then this function will return
the currency related to their default address, otherwise, it returns
the site default
"""
if settings.ENABLE_GLOBAL_CURRENCIES:
return self.default_address.country.currency
return Currency.get_default_currency()
currency = property(get_currency)
def get_gateway_currency(self):
"""
Get the currency that an order will be put through protx with. If protx
currencies are enabled (settings.ENABLE_PROTX_CURRENCIES), then the
currency will be the same returned by get_currency, otherwise, the
site default is used
"""
if settings.ENABLE_PROTX_CURRENCIES and settings.ENABLE_GLOBAL_CURRENCIES:
return self.currency
return Currency.get_default_currency()
gateway_currency = property(get_gateway_currency)
Address Class
class Address(models.Model):
"""
This class encapsulates the data required for postage and payment mechanisms
across the site. Each address is associated with a single store account
"""
trade_user = models.BooleanField("Are you a stockist of Neal & Wolf Products", help_text="Please here if you are a Neal & Wolf Stockist")
company_name = models.CharField(max_length=32, blank=True)
line1 = models.CharField(max_length=200)
line2 = models.CharField(max_length=200, blank=True)
line3 = models.CharField(max_length=200, blank=True)
city = models.CharField(max_length=32)
county = models.CharField(max_length=32)
postcode = models.CharField(max_length=12)
country = models.ForeignKey(Country)
account = models.ForeignKey('Account')
class Meta:
"""
Django meta options
verbose_name_plural = "Addresses"
"""
verbose_name_plural = "Addresses"
def __unicode__(self):
"""
The unicode representation of this address, the postcode plus the county
"""
return ', '.join((self.postcode, str(self.county)))
def line_list(self):
"""
Return a list of all of this objects address lines that are not blank,
in the natural order that you'd expect to see them. This is useful for
outputting to a template with the aid of python String.join()
"""
return [val for val in (self.line1, self.line2, self.line3, self.city, self.county, self.postcode, self.country.name) if val]
About see three classes my question is easy how do i find out whether or not the user, is a trade user(this value is gathered in the Address class)
Thanks
|
[
"If the Account class is your user profile, as its docstring suggests, then you should be able to do something like this:\nis_trade_user = user.get_profile().default_address.trade_user\n\nif the definition of a trade user is \"Has a default address for which trade_user is true\"\nOn the other hand, if the definition of trade user is \"Has any address for which trade_user is true\" then you will need to do something more complicated -- check all of the addresses, and return true if any of them have trade_user set:\nis_trade_user = user.get_profile().address_set.filter(trade_user=True).count() > 0\n\n"
] |
[
5
] |
[] |
[] |
[
"django",
"django_models",
"django_views",
"python"
] |
stackoverflow_0001827683_django_django_models_django_views_python.txt
|
Q:
Django using a generic view for create_update update_object, form not displaying
Trying to use a generic view so I can update an object via a user facing form. My code looks like this in views:
from django.views.generic.create_update import update_object
@permission_required('myapp.change_foo', login_url="/accounts/login/")
def foo_update(request, foo_id):
return update_object(
request,
form_class=FooForm,
object_id=sr_id,
template_name = 'foo/update.html',
template_object_name = 'foo',
)
The form definition looks like this:
class FooForm(ModelForm):
somefield = forms.CharField(
widget=forms.TextInput(attrs={'readonly':'readonly'})
)
class Meta:
model = Foo
And in my template I have a snippet like this in foo/update.html:
<form action="" method="post">
<table>
{{ foo.as_table }}
</table>
<p>
<input type="submit" value="Submit" />
</p>
</form>
I've never had issues displaying 'foo' before, but this is the first time I'm using this particular generic view. No syntax errors, just no form showing up in my template at all.
Does update_object() not embed 'foo' as a form? is it still up to me to add the form add additional content and then write the save() logic for it? I wish there was slightly more documentation on this generic view and how it works.
A:
It's right there in the documentation:
In addition to extra_context, the template's context will be:
form: A django.forms.ModelForm instance representing the form for editing the object. This lets you refer to form fields easily in the template system.
The template_object_name argument influences the name of the actual object.
/edit
Jeez, you people... criticizing one of the best documented open source projects out there, but not even trying to read the documentation if it is spoonfed to you. To continue my quote of the docs:
For example, if the model has two fields, name and address:
<form action="" method="post">
<p>{{ form.name.label_tag }} {{ form.name }}</p>
<p>{{ form.address.label_tag }} {{ form.address }}</p>
</form>
See the forms documentation for more information about using Form objects in templates.
|
Django using a generic view for create_update update_object, form not displaying
|
Trying to use a generic view so I can update an object via a user facing form. My code looks like this in views:
from django.views.generic.create_update import update_object
@permission_required('myapp.change_foo', login_url="/accounts/login/")
def foo_update(request, foo_id):
return update_object(
request,
form_class=FooForm,
object_id=sr_id,
template_name = 'foo/update.html',
template_object_name = 'foo',
)
The form definition looks like this:
class FooForm(ModelForm):
somefield = forms.CharField(
widget=forms.TextInput(attrs={'readonly':'readonly'})
)
class Meta:
model = Foo
And in my template I have a snippet like this in foo/update.html:
<form action="" method="post">
<table>
{{ foo.as_table }}
</table>
<p>
<input type="submit" value="Submit" />
</p>
</form>
I've never had issues displaying 'foo' before, but this is the first time I'm using this particular generic view. No syntax errors, just no form showing up in my template at all.
Does update_object() not embed 'foo' as a form? is it still up to me to add the form add additional content and then write the save() logic for it? I wish there was slightly more documentation on this generic view and how it works.
|
[
"It's right there in the documentation:\n\nIn addition to extra_context, the template's context will be:\n\nform: A django.forms.ModelForm instance representing the form for editing the object. This lets you refer to form fields easily in the template system.\n\n\nThe template_object_name argument influences the name of the actual object.\n/edit\nJeez, you people... criticizing one of the best documented open source projects out there, but not even trying to read the documentation if it is spoonfed to you. To continue my quote of the docs:\n\nFor example, if the model has two fields, name and address:\n <form action=\"\" method=\"post\">\n <p>{{ form.name.label_tag }} {{ form.name }}</p>\n <p>{{ form.address.label_tag }} {{ form.address }}</p>\n </form>\n\nSee the forms documentation for more information about using Form objects in templates.\n\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001827817_django_python.txt
|
Q:
Using super() in nested classes
Imagine this:
class A(object):
class B(object):
def __init__(self):
super(B, self).__init__()
This creates an error:
NameError: global name B is not defined.
I've tried A.B, but then it says that A is not defined.
Update:
I've found the problem.
I've had a class like this:
class A(object):
class B(object):
def __init__(self):
super(B, self).__init__()
someattribute = B()
In that scope, A isn't defined yet.
A:
I'm not sure why A.B is not working correctly for you, as it should.. Here's some shell output that works:
>>> class A(object):
... class B(object):
... def __init__(self):
... super(A.B, self).__init__()
... def getB(self):
... return A.B()
...
>>> A().getB()
<__main__.B object at 0x100496410>
A:
Since B will likely never be extended itself, this should work:
class A(object):
class B(object):
def __init__(self):
super(self.__class__, self).__init__()
A:
If the class A.B is unlikely to participate in any multiple inheritance, then you're better off just hard-coding the constructor call:
class A(object):
class B(object):
def __init__(self):
object.__init__(self)
But if you really do need to have the full power of super, then you can get what you want by defining a custom descriptor that will initialize the B attribute lazily:
class LazyAttribute(object):
def __init__(self, func, *args, **kwargs):
self._func = func
self._args = args
self._kwargs = kwargs
self._value = None
def __get__(self, obj, type=None):
if self._value is None:
print 'created', self._value
self._value = self._func(*self._args, **self._kwargs)
return self._value
class A(object):
class B(object):
def __init__(self):
super(A.B, self).__init__()
someattribute = LazyAttribute(B)
This will cause the B attribute to be instantiated the first time it's accessed, and then reused thereafter:
>>> print A.someattribute
created <__main__.B object at 0x00AA8E70>
<__main__.B object at 0x00AA8E90>
>>> print A().someattribute
<__main__.B object at 0x00AA8E90>
For more info on descriptors, see: http://users.rcn.com/python/download/Descriptor.htm
|
Using super() in nested classes
|
Imagine this:
class A(object):
class B(object):
def __init__(self):
super(B, self).__init__()
This creates an error:
NameError: global name B is not defined.
I've tried A.B, but then it says that A is not defined.
Update:
I've found the problem.
I've had a class like this:
class A(object):
class B(object):
def __init__(self):
super(B, self).__init__()
someattribute = B()
In that scope, A isn't defined yet.
|
[
"I'm not sure why A.B is not working correctly for you, as it should.. Here's some shell output that works:\n>>> class A(object):\n... class B(object):\n... def __init__(self):\n... super(A.B, self).__init__()\n... def getB(self):\n... return A.B()\n... \n>>> A().getB()\n<__main__.B object at 0x100496410>\n\n",
"Since B will likely never be extended itself, this should work:\nclass A(object):\n class B(object):\n def __init__(self):\n super(self.__class__, self).__init__()\n\n",
"If the class A.B is unlikely to participate in any multiple inheritance, then you're better off just hard-coding the constructor call:\nclass A(object):\n class B(object):\n def __init__(self):\n object.__init__(self)\n\nBut if you really do need to have the full power of super, then you can get what you want by defining a custom descriptor that will initialize the B attribute lazily:\nclass LazyAttribute(object):\n def __init__(self, func, *args, **kwargs):\n self._func = func\n self._args = args\n self._kwargs = kwargs\n self._value = None\n\n def __get__(self, obj, type=None):\n if self._value is None:\n print 'created', self._value\n self._value = self._func(*self._args, **self._kwargs)\n return self._value\n\nclass A(object):\n class B(object):\n def __init__(self):\n super(A.B, self).__init__()\n\n someattribute = LazyAttribute(B)\n\nThis will cause the B attribute to be instantiated the first time it's accessed, and then reused thereafter:\n>>> print A.someattribute\ncreated <__main__.B object at 0x00AA8E70>\n<__main__.B object at 0x00AA8E90>\n>>> print A().someattribute\n<__main__.B object at 0x00AA8E90>\n\nFor more info on descriptors, see: http://users.rcn.com/python/download/Descriptor.htm\n"
] |
[
20,
5,
2
] |
[] |
[] |
[
"python",
"super"
] |
stackoverflow_0001825384_python_super.txt
|
Q:
os.kill not raising an OSError, however I do not see the given pid running
On my ubuntu server I run the following command:
python -c 'import os; os.kill(5555, 0)'
This is done so that I can see if pid 5555 is running. From my understanding this should raise an OSError if the pid is not running. This is not raising an OSError for me which means it should be a running process. However when I run:
ps aux | grep 5555
I see no process running with that pid. This also happens on several other pids in that general range, but it does not happen with say 555 or 55555.
Does anyone have any insight as to why os.kill would not raise an OSError like it is expected to?
Note: this is running under python 2.5.1.
A:
Under linux, each process and each thread have a different pid. os.kill doesn't care whether you have a thread pid, or a task pid, however ps doesn't normally show the thread pids.
For instance on my machine the process with PID 8502 is running threads which you can see like this
$ ls /proc/8502/task/
8502 8503 8504 8505 8506 8507 8511 8512 8514 8659
Note that 8503 doesn't appear in the process list
$ ps aux | grep [8]503
$
However using some more ps arguments you can see it
$ ps -eLf | grep [8]503
ncw 8502 1 8503 0 10 10:00 ? 00:00:00 /usr/lib/virtualbox/VBoxSVC --automate
(Grepping for [8]503 means that the grep won't show up - it's an old unix trick!)
Now lets see if it is alive or not
$ python
Python 2.6.4 (r264:75706, Nov 2 2009, 14:44:17)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
Loaded customisations from '/home/ncw/.pystartup'
>>> import os
>>> os.kill(8503, 0)
>>>
This duplicates your problem.
I think if you do
ls /proc/*/task/5555
or
ps -eLf | grep [5]555
You will see the culprit thread.
A:
Try installing htop (sudo apt-get install htop), it sometimes displays process that ps doesn't.
A:
Maybe it's a bug in 2.5? On 2.6.4 I get:
gruszczy@gruszczy-laptop:~$ python -c 'import os; os.kill(5555, 0)'
Traceback (most recent call last):
File "<string>", line 1, in <module>
OSError: [Errno 3] No such process
I believe, there is a bug report for this:
http://mail.python.org/pipermail/new-bugs-announce/2009-February/004222.html
A:
I don't know why that OSError is not raised in some cases, but it's important to note that there is a max pid value on linux and unix based OS:
$> cat /proc/sys/kernel/pid_max
32768
|
os.kill not raising an OSError, however I do not see the given pid running
|
On my ubuntu server I run the following command:
python -c 'import os; os.kill(5555, 0)'
This is done so that I can see if pid 5555 is running. From my understanding this should raise an OSError if the pid is not running. This is not raising an OSError for me which means it should be a running process. However when I run:
ps aux | grep 5555
I see no process running with that pid. This also happens on several other pids in that general range, but it does not happen with say 555 or 55555.
Does anyone have any insight as to why os.kill would not raise an OSError like it is expected to?
Note: this is running under python 2.5.1.
|
[
"Under linux, each process and each thread have a different pid. os.kill doesn't care whether you have a thread pid, or a task pid, however ps doesn't normally show the thread pids.\nFor instance on my machine the process with PID 8502 is running threads which you can see like this\n$ ls /proc/8502/task/\n8502 8503 8504 8505 8506 8507 8511 8512 8514 8659\n\nNote that 8503 doesn't appear in the process list\n$ ps aux | grep [8]503\n$\n\nHowever using some more ps arguments you can see it\n$ ps -eLf | grep [8]503\nncw 8502 1 8503 0 10 10:00 ? 00:00:00 /usr/lib/virtualbox/VBoxSVC --automate\n\n(Grepping for [8]503 means that the grep won't show up - it's an old unix trick!)\nNow lets see if it is alive or not\n$ python\nPython 2.6.4 (r264:75706, Nov 2 2009, 14:44:17)\n[GCC 4.4.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\nLoaded customisations from '/home/ncw/.pystartup'\n>>> import os\n>>> os.kill(8503, 0)\n>>>\n\nThis duplicates your problem.\nI think if you do\nls /proc/*/task/5555\n\nor\nps -eLf | grep [5]555\n\nYou will see the culprit thread.\n",
"Try installing htop (sudo apt-get install htop), it sometimes displays process that ps doesn't.\n",
"Maybe it's a bug in 2.5? On 2.6.4 I get:\ngruszczy@gruszczy-laptop:~$ python -c 'import os; os.kill(5555, 0)'\nTraceback (most recent call last):\n File \"<string>\", line 1, in <module>\nOSError: [Errno 3] No such process\n\nI believe, there is a bug report for this:\nhttp://mail.python.org/pipermail/new-bugs-announce/2009-February/004222.html\n",
"I don't know why that OSError is not raised in some cases, but it's important to note that there is a max pid value on linux and unix based OS:\n$> cat /proc/sys/kernel/pid_max\n32768\n\n"
] |
[
7,
1,
1,
0
] |
[] |
[] |
[
"pid",
"python",
"ubuntu"
] |
stackoverflow_0001826824_pid_python_ubuntu.txt
|
Q:
Writing a Template Tag in Django
I'm trying to customise a CMS written in Django. The content editors aren't flexible enough so I'm trying to come up with a better solution.
Without over-explaining it, I'd like it to be a bit like django-better-chunks or django-flatblocks. You set up an editable region entirely from within the template. I want to bind these editable regions to a mix of strings and object instances. One example would be having multiple editable regions based on one product:
{% block product_instance "title" %}
{% block product_instance "product description" %}
So if you have a view with another product as product_instance those two blocks would show different data. I would also see there being use for site-wide blocks that only pass through the string part. Essentially, I would like to be able to pass 1-infinity identifiers.
But I'm really struggling on two fronts here:
How do I define the relationship between the mixed identifier and the actual content "block" instance? I have a feeling contenttypes might feature here but I've really no idea where to start looking!
And how do I write a template tag to read the above syntax and convert that into an object for rendering?
A:
for this you can create an inclusion tag and use it like:
{% load my_tags %}
{% product bicycle <extra vars ...> %}
To define the tag, add to your app/templatetags/mytags.py:
@register.inclusion_tag('results.html')
def product(item, *extra):
#maybe repackage extra variables
#and add them to the returned dictionary
item_form = ItemForm(item) #form.ModelForm instance
return {'item': item, 'item_form':item_form, ...}
Then you'll need a template that returns html for the item:
<h1>{{item.title}}</h1>
{{item_form}}
... add some conditional statements depending on extra vars
|
Writing a Template Tag in Django
|
I'm trying to customise a CMS written in Django. The content editors aren't flexible enough so I'm trying to come up with a better solution.
Without over-explaining it, I'd like it to be a bit like django-better-chunks or django-flatblocks. You set up an editable region entirely from within the template. I want to bind these editable regions to a mix of strings and object instances. One example would be having multiple editable regions based on one product:
{% block product_instance "title" %}
{% block product_instance "product description" %}
So if you have a view with another product as product_instance those two blocks would show different data. I would also see there being use for site-wide blocks that only pass through the string part. Essentially, I would like to be able to pass 1-infinity identifiers.
But I'm really struggling on two fronts here:
How do I define the relationship between the mixed identifier and the actual content "block" instance? I have a feeling contenttypes might feature here but I've really no idea where to start looking!
And how do I write a template tag to read the above syntax and convert that into an object for rendering?
|
[
"for this you can create an inclusion tag and use it like:\n{% load my_tags %}\n{% product bicycle <extra vars ...> %}\n\nTo define the tag, add to your app/templatetags/mytags.py:\n@register.inclusion_tag('results.html')\ndef product(item, *extra):\n #maybe repackage extra variables\n #and add them to the returned dictionary\n item_form = ItemForm(item) #form.ModelForm instance\n return {'item': item, 'item_form':item_form, ...}\n\nThen you'll need a template that returns html for the item:\n<h1>{{item.title}}</h1>\n{{item_form}}\n... add some conditional statements depending on extra vars\n\n"
] |
[
2
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0001200548_django_django_templates_python.txt
|
Q:
Overload a method with a function at runtime
OK, I'll admit upfront this is a mega kludge and that I could definately implement this better. It's only morbid curiosity that's driving me to find out how I could do this.
class SomeClass(object):
def __init__(self):
def __(self, arg):
self.doStuff(arg)
self.overLoaded = __
def doStuff(self, string):
print string
SomeClass().overLoaded("test string")
This returns a parameter error because I'm only supplying overLoaded() with one argument instead of two. Is there some magic to tell the interpreter that it's now a method of a class (I tried decorating it with @classmethod, I always understood this to be it's purpose??)
A:
Don't worry about the self parameter, the function already has that from local scope.
class SomeClass(object):
def __init__(self):
def __(arg):
self.bar(arg)
self.foo = __
def foo(self, arg):
print "foo", arg
def bar(self, arg):
print "bar", arg
SomeClass().foo("thing") # prints "bar thing"
When creating an instance (after __new__, iirc, but before __init__) Python binds all the methods to automagically supply the instance as the first argument. If you're adding a method later then you need to supply the instance manually. As you are defining the function with self already in scope you don't need to pass it again.
Python's new module is not a solution as it has been deprecated since 2.6. If you want to create a "real" instance method do it with the partial decorator like this:
import functools
class SomeClass(object):
def __init__(self):
def __(self, arg):
self.bar(arg)
self.foo = functools.partial(__, self)
def foo(self, arg):
print "foo", arg
def bar(self, arg):
print "bar", arg
SomeClass().foo("thing") # prints "bar thing"
A:
The issue is that you are trying to add a new instance method (not class method) and it is not binding properly. Python has a module function to manually bind functions to instances.
import new
self.method = new.instancemethod(func, self, class)
Edit: Apparently the new module is deprecated. Use the types module instead for metamagic.
import types
self.method = types.MethodType(func, self, class)
A:
sj26's solution is a good one. Another alternative, if you want to set up a method that can be overloaded with any user-supplied function or with another of the object's methods, is build a custom descriptor. This descriptor can be used as a decorator (analogous to @classmethod or @staticmethod); and it allows you to store a function in an instance's dictionary, and returns it as a method:
import types
class overloadable(object):
def __init__(self, func):
self._default_func = func
self._name = func.__name__
def __get__(self, obj, type=None):
func = obj.__dict__.get(self._name, self._default_func)
return types.MethodType(func, obj, type)
def __set__(self, obj, value):
if hasattr(value, 'im_func'): value = value.im_func
obj.__dict__[self._name] = value
def __delete__(self, obj):
del obj.__dict__[self._name]
Now we can just decorate a function with "@overloadable":
class SomeClass(object):
def doStuff(self, string):
print 'do stuff:', string
@overloadable
def overLoaded(self, arg):
print 'default behavior:', arg
And it'll just do the right thing when we overload it for a given instance:
>>> sc = SomeClass()
>>> sc.overLoaded("test string") # Before customization
default behavior: test string
>>> sc.overLoaded = sc.doStuff # Customize
>>> sc.overLoaded("test string")
do stuff: test string
>>> del sc.overLoaded # Revert to default behavior
>>> sc.overLoaded("test string")
default behavior: test string
|
Overload a method with a function at runtime
|
OK, I'll admit upfront this is a mega kludge and that I could definately implement this better. It's only morbid curiosity that's driving me to find out how I could do this.
class SomeClass(object):
def __init__(self):
def __(self, arg):
self.doStuff(arg)
self.overLoaded = __
def doStuff(self, string):
print string
SomeClass().overLoaded("test string")
This returns a parameter error because I'm only supplying overLoaded() with one argument instead of two. Is there some magic to tell the interpreter that it's now a method of a class (I tried decorating it with @classmethod, I always understood this to be it's purpose??)
|
[
"Don't worry about the self parameter, the function already has that from local scope.\nclass SomeClass(object):\n def __init__(self):\n def __(arg):\n self.bar(arg)\n self.foo = __\n def foo(self, arg):\n print \"foo\", arg\n def bar(self, arg):\n print \"bar\", arg\n\nSomeClass().foo(\"thing\") # prints \"bar thing\"\n\nWhen creating an instance (after __new__, iirc, but before __init__) Python binds all the methods to automagically supply the instance as the first argument. If you're adding a method later then you need to supply the instance manually. As you are defining the function with self already in scope you don't need to pass it again.\nPython's new module is not a solution as it has been deprecated since 2.6. If you want to create a \"real\" instance method do it with the partial decorator like this:\nimport functools\n\nclass SomeClass(object):\n def __init__(self):\n def __(self, arg):\n self.bar(arg)\n self.foo = functools.partial(__, self)\n def foo(self, arg):\n print \"foo\", arg\n def bar(self, arg):\n print \"bar\", arg\n\nSomeClass().foo(\"thing\") # prints \"bar thing\"\n\n",
"The issue is that you are trying to add a new instance method (not class method) and it is not binding properly. Python has a module function to manually bind functions to instances.\nimport new\nself.method = new.instancemethod(func, self, class)\n\nEdit: Apparently the new module is deprecated. Use the types module instead for metamagic.\nimport types\nself.method = types.MethodType(func, self, class)\n\n",
"sj26's solution is a good one. Another alternative, if you want to set up a method that can be overloaded with any user-supplied function or with another of the object's methods, is build a custom descriptor. This descriptor can be used as a decorator (analogous to @classmethod or @staticmethod); and it allows you to store a function in an instance's dictionary, and returns it as a method:\nimport types\n\nclass overloadable(object):\n def __init__(self, func):\n self._default_func = func\n self._name = func.__name__\n\n def __get__(self, obj, type=None):\n func = obj.__dict__.get(self._name, self._default_func)\n return types.MethodType(func, obj, type)\n\n def __set__(self, obj, value):\n if hasattr(value, 'im_func'): value = value.im_func\n obj.__dict__[self._name] = value\n\n def __delete__(self, obj):\n del obj.__dict__[self._name]\n\nNow we can just decorate a function with \"@overloadable\":\nclass SomeClass(object):\n def doStuff(self, string):\n print 'do stuff:', string\n @overloadable\n def overLoaded(self, arg):\n print 'default behavior:', arg\n\nAnd it'll just do the right thing when we overload it for a given instance:\n>>> sc = SomeClass()\n>>> sc.overLoaded(\"test string\") # Before customization\ndefault behavior: test string\n\n>>> sc.overLoaded = sc.doStuff # Customize\n>>> sc.overLoaded(\"test string\")\ndo stuff: test string\n\n>>> del sc.overLoaded # Revert to default behavior\n>>> sc.overLoaded(\"test string\")\ndefault behavior: test string\n\n"
] |
[
8,
3,
0
] |
[] |
[] |
[
"metaprogramming",
"python"
] |
stackoverflow_0001823898_metaprogramming_python.txt
|
Q:
PyQt subclassing
The usual way to use Qt widgets from Python seems to be to subclass them.
Qt widget classes have a great many methods, so inevitably I'm going to end up adding a method to the subclass, with the same name as one inherited from the Qt widget. In Python, all methods are virtual, so what I'm concerned about is that some Qt code might end up calling my method instead of the expected Qt one - in the worst-case scenario, breaking some edge case that doesn't easily show up in testing.
On the other hand, maybe all the PyQt methods are just wrappers for C++ code, which would of course be unaffected by anything I do in terms of Python subclassing.
Anyone know offhand which is the case?
A:
If the underlaying C++ methods are virtual, your Python methods that override them will be called any time C++ code calls them. If they are just regular methods, any C++ code will call the original C++ methods by default (Python code will call the Python methods though, because it sees the Python object and all methods are "virtual" there).
|
PyQt subclassing
|
The usual way to use Qt widgets from Python seems to be to subclass them.
Qt widget classes have a great many methods, so inevitably I'm going to end up adding a method to the subclass, with the same name as one inherited from the Qt widget. In Python, all methods are virtual, so what I'm concerned about is that some Qt code might end up calling my method instead of the expected Qt one - in the worst-case scenario, breaking some edge case that doesn't easily show up in testing.
On the other hand, maybe all the PyQt methods are just wrappers for C++ code, which would of course be unaffected by anything I do in terms of Python subclassing.
Anyone know offhand which is the case?
|
[
"If the underlaying C++ methods are virtual, your Python methods that override them will be called any time C++ code calls them. If they are just regular methods, any C++ code will call the original C++ methods by default (Python code will call the Python methods though, because it sees the Python object and all methods are \"virtual\" there).\n"
] |
[
3
] |
[] |
[] |
[
"pyqt",
"pyqt4",
"python",
"qt",
"qt4"
] |
stackoverflow_0001828567_pyqt_pyqt4_python_qt_qt4.txt
|
Q:
reading mails using python
how do i read mails from my mail box using python??
import getpass, imaplib
M = imaplib.IMAP4('IMAP4.gmail.com:993')
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()
this is my code..
but when i execute this its throwing error:
Traceback (most recent call last):
File "E:/jagdish/python progs/readmail.py", line 2, in <module>
M = imaplib.IMAP4('IMAP4.gmail.com:993')
File "C:\Python25\lib\imaplib.py", line 163, in __init__
self.open(host, port)
File "C:\Python25\lib\imaplib.py", line 230, in open
self.sock.connect((host, port))
File "<string>", line 1, in connect
gaierror: (11001, 'getaddrinfo failed')
can anyone help me with this???
A:
Three issues:
The hostname is imap.gmail.com, not imap4.gmail.com
The IMAP4 constructor takes two parameters: the host and port (not colon-separated)
Gmail expects you to be talking SSL
So:
import imaplib
M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
A:
The error means that the host is unreachable or does not exist, which you could find out by googling for 'gaierror' (it stands for get address info error).
Try "imap.gmail.com:993" instead, as described here.
|
reading mails using python
|
how do i read mails from my mail box using python??
import getpass, imaplib
M = imaplib.IMAP4('IMAP4.gmail.com:993')
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, data[0][1])
M.close()
M.logout()
this is my code..
but when i execute this its throwing error:
Traceback (most recent call last):
File "E:/jagdish/python progs/readmail.py", line 2, in <module>
M = imaplib.IMAP4('IMAP4.gmail.com:993')
File "C:\Python25\lib\imaplib.py", line 163, in __init__
self.open(host, port)
File "C:\Python25\lib\imaplib.py", line 230, in open
self.sock.connect((host, port))
File "<string>", line 1, in connect
gaierror: (11001, 'getaddrinfo failed')
can anyone help me with this???
|
[
"Three issues:\n\nThe hostname is imap.gmail.com, not imap4.gmail.com\nThe IMAP4 constructor takes two parameters: the host and port (not colon-separated)\nGmail expects you to be talking SSL\n\nSo:\nimport imaplib\nM = imaplib.IMAP4_SSL(\"imap.gmail.com\", 993)\n\n",
"The error means that the host is unreachable or does not exist, which you could find out by googling for 'gaierror' (it stands for get address info error).\nTry \"imap.gmail.com:993\" instead, as described here.\n"
] |
[
13,
1
] |
[] |
[] |
[
"email",
"gmail",
"imap",
"python"
] |
stackoverflow_0001827848_email_gmail_imap_python.txt
|
Q:
2 Axes Reportlab Graph
I have managed to create a 2 axes graph in ReportLab, by overlapping a barchart and linepot. Here is the code for anyone interested in something similar:
from reportlab.graphics.shapes import Drawing,colors
from reportlab.graphics.widgets.markers import makeMarker
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics.charts.lineplots import LinePlot
drawing = Drawing(400, 200)
data = [(13, 5, 20, 22, 37, 45, 19, 4)
]
noOfBars=len(data[0])
bc = VerticalBarChart()
bc.x = 50
bc.y = 50
bc.height = 125
bc.width = 300
bc.data = data
bc.valueAxis.valueMin = 0
bc.valueAxis.valueMax = 50
bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99','May-99','Jun-99','Jul-99','Aug-99']
drawing.add(bc)
data3=[[(0.5, 4), (1.5, 3), (2.5, 4), (3.5, 6), (4.5, 4), (5.5, 2), (6.5, 5), (7.5, 6)]
]
lp = LinePlot()
lp.x = bc.x
lp.y = bc.y
lp.height = bc.height
lp.width = bc.width
lp.data = data3
lp.joinedLines = 1
lp.lines[0].symbol = makeMarker('Circle')
lp.lines[0].strokeColor=colors.blue
lp.lineLabelFormat = '%2.0f'
lp.xValueAxis.valueMin = 0
lp.xValueAxis.valueMax = noOfBars
lp.yValueAxis.valueMin = 0
lp.yValueAxis.valueMax = 8
lp.xValueAxis.visible=False
lp.yValueAxis.visible=False #Hide 2nd plot its Yaxis
drawing.add(lp)
y2Axis = YValueAxis()#Replicate 2nd plot Yaxis in the right
y2Axis.setProperties(lp.yValueAxis.getProperties())
y2Axis.setPosition(lp.x+lp.width,lp.y,lp.height)
y2Axis.tickRight=5
y2Axis.tickLeft=0
y2Axis.configure(data3)
y2Axis.visible=True
drawing.add(y2Axis)
renderPDF.drawToFile(drawing, '../tmp/barline.pdf')
The only problem is that the 2nd has labels pointing inside the graph. I would like them to be outside the graph!. I found a property to adjust the ticks (y2Axis.tickRight=5 , y2Axis.tickLeft=0) but the yvalue labels position is yet a mystery!
Thanks in advance
A:
I did this recently. Something like
y2Axis.labels.dx = 10
should do the trick for you.
|
2 Axes Reportlab Graph
|
I have managed to create a 2 axes graph in ReportLab, by overlapping a barchart and linepot. Here is the code for anyone interested in something similar:
from reportlab.graphics.shapes import Drawing,colors
from reportlab.graphics.widgets.markers import makeMarker
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics.charts.lineplots import LinePlot
drawing = Drawing(400, 200)
data = [(13, 5, 20, 22, 37, 45, 19, 4)
]
noOfBars=len(data[0])
bc = VerticalBarChart()
bc.x = 50
bc.y = 50
bc.height = 125
bc.width = 300
bc.data = data
bc.valueAxis.valueMin = 0
bc.valueAxis.valueMax = 50
bc.categoryAxis.categoryNames = ['Jan-99','Feb-99','Mar-99','Apr-99','May-99','Jun-99','Jul-99','Aug-99']
drawing.add(bc)
data3=[[(0.5, 4), (1.5, 3), (2.5, 4), (3.5, 6), (4.5, 4), (5.5, 2), (6.5, 5), (7.5, 6)]
]
lp = LinePlot()
lp.x = bc.x
lp.y = bc.y
lp.height = bc.height
lp.width = bc.width
lp.data = data3
lp.joinedLines = 1
lp.lines[0].symbol = makeMarker('Circle')
lp.lines[0].strokeColor=colors.blue
lp.lineLabelFormat = '%2.0f'
lp.xValueAxis.valueMin = 0
lp.xValueAxis.valueMax = noOfBars
lp.yValueAxis.valueMin = 0
lp.yValueAxis.valueMax = 8
lp.xValueAxis.visible=False
lp.yValueAxis.visible=False #Hide 2nd plot its Yaxis
drawing.add(lp)
y2Axis = YValueAxis()#Replicate 2nd plot Yaxis in the right
y2Axis.setProperties(lp.yValueAxis.getProperties())
y2Axis.setPosition(lp.x+lp.width,lp.y,lp.height)
y2Axis.tickRight=5
y2Axis.tickLeft=0
y2Axis.configure(data3)
y2Axis.visible=True
drawing.add(y2Axis)
renderPDF.drawToFile(drawing, '../tmp/barline.pdf')
The only problem is that the 2nd has labels pointing inside the graph. I would like them to be outside the graph!. I found a property to adjust the ticks (y2Axis.tickRight=5 , y2Axis.tickLeft=0) but the yvalue labels position is yet a mystery!
Thanks in advance
|
[
"I did this recently. Something like\ny2Axis.labels.dx = 10\n\nshould do the trick for you.\n"
] |
[
3
] |
[] |
[] |
[
"graph",
"python",
"reportlab"
] |
stackoverflow_0001826761_graph_python_reportlab.txt
|
Q:
Setting object owner with generic create_object view in django
Is it possible to use create_object view to create a new object and automatically assign request.user as foreign key?
P.E:
class Post(models.Model):
text = models.TextField()
author = models.ForeignKey(User)
What I want is to use create_object and fill author with request.user.
A:
In many ways, all the solutions to this will be more trouble than they are worth. This one qualifies as a hack. It is possible for a django update to leave you high and dry if they change the way create_update is implemented. For simplicity sake, I'll assume that you are trying to set a default user, not silently force the user to be the logged in user.
Write a context processor:
from django.views.generic.create_update import get_model_and_form_class
def form_user_default(request):
if request.method == 'GET':
model, custom_form = get_model_and_form_class(Post,None)
custom_form.author = request.user
return {'form':custom_form}
else: return {}
What this will do is override the form object that create_update passes to the template. What it's technically doing is re-creating the form after the default view has done it.
Then in your url conf:
url(r'pattern_to_match', 'django.views.generic.create_update.create_object', kwargs={'context_processors':form_user_default})
Again, I had to delve into the source code to figure out how to do this. It might really be best to try writing your own view (but incorporate as many Django custom objects as possible). There's no "simple default" way to do this, because in the django paradigm forms are more closely tied to the model layer than to views, and only views have knowledge of the request object.
A:
You may want to consider a closure.
from django.forms import ModelForm
from django.views.generic.create_update import create_object, update_object
def make_foo_form(request):
class FooForm(ModelForm):
class Meta:
model = Foo
fields = ['foo', 'bar']
def save(self, commit=True):
f = super(FooForm, self).save(commit=False)
if not f.pk: f.user = request.user
if commit: f.save()
return f
return FooForm
def create_foo(request):
FooForm = make_foo_form(request)
return create_object(form_class=FooForm)
There is some inefficiency here, since you need to create the ModelForm object on each request, but it does allow you to inject functionality into the generic view.
You need to decide whether the added complexity for the form creation is worth maintaining simplicity on the view side.
A benefit here, though, is that this also works with the update case with practically no extra effort:
def update_foo(request, object_id):
FooForm = make_foo_form(request)
return update_object(form_class=FooForm, object_id=object_id)
Obviously, you can use this approach for more complex cases as well.
A:
If a user is authenticated, their user object is the request.user object.
I'm not familiar with create_object... I'm still a beginner to django and have only just started my first real project with it.
Note that you should check to make sure a user is logged in before using this. This can be done with request.user.is_authenticated().
A:
There is no good way to hook into the saving of an object when using the current Django generic views. Once they are rewritten as classes, you'll be able to subclass the view and hook in at the proper place without having to rewrite the whole view.
I already use my own class-based generic views for this reason.
A:
I would suggest to make a wrapper for the create_object, as this author suggest
http://www.b-list.org/weblog/2006/nov/16/django-tips-get-most-out-generic-views/
in the view you'll have access to the user info.
Afterwards, you will need to use the extra_context to pass the user to the template. Finally at the template you can add a hidden field with the user info. I haven't tried it, but I have been thinking of it for quite some time. Hope this solution suits you!
;) cheers!
|
Setting object owner with generic create_object view in django
|
Is it possible to use create_object view to create a new object and automatically assign request.user as foreign key?
P.E:
class Post(models.Model):
text = models.TextField()
author = models.ForeignKey(User)
What I want is to use create_object and fill author with request.user.
|
[
"In many ways, all the solutions to this will be more trouble than they are worth. This one qualifies as a hack. It is possible for a django update to leave you high and dry if they change the way create_update is implemented. For simplicity sake, I'll assume that you are trying to set a default user, not silently force the user to be the logged in user.\nWrite a context processor:\nfrom django.views.generic.create_update import get_model_and_form_class\ndef form_user_default(request):\n if request.method == 'GET':\n model, custom_form = get_model_and_form_class(Post,None)\n custom_form.author = request.user\n return {'form':custom_form}\n else: return {}\n\nWhat this will do is override the form object that create_update passes to the template. What it's technically doing is re-creating the form after the default view has done it. \nThen in your url conf:\nurl(r'pattern_to_match', 'django.views.generic.create_update.create_object', kwargs={'context_processors':form_user_default})\n\nAgain, I had to delve into the source code to figure out how to do this. It might really be best to try writing your own view (but incorporate as many Django custom objects as possible). There's no \"simple default\" way to do this, because in the django paradigm forms are more closely tied to the model layer than to views, and only views have knowledge of the request object.\n",
"You may want to consider a closure.\nfrom django.forms import ModelForm\nfrom django.views.generic.create_update import create_object, update_object\n\ndef make_foo_form(request):\n class FooForm(ModelForm):\n class Meta:\n model = Foo\n fields = ['foo', 'bar']\n\n def save(self, commit=True):\n f = super(FooForm, self).save(commit=False)\n if not f.pk: f.user = request.user\n if commit: f.save()\n return f\n\n return FooForm\n\ndef create_foo(request):\n FooForm = make_foo_form(request)\n return create_object(form_class=FooForm)\n\nThere is some inefficiency here, since you need to create the ModelForm object on each request, but it does allow you to inject functionality into the generic view.\nYou need to decide whether the added complexity for the form creation is worth maintaining simplicity on the view side.\nA benefit here, though, is that this also works with the update case with practically no extra effort:\ndef update_foo(request, object_id):\n FooForm = make_foo_form(request)\n return update_object(form_class=FooForm, object_id=object_id)\n\nObviously, you can use this approach for more complex cases as well.\n",
"If a user is authenticated, their user object is the request.user object.\nI'm not familiar with create_object... I'm still a beginner to django and have only just started my first real project with it.\nNote that you should check to make sure a user is logged in before using this. This can be done with request.user.is_authenticated().\n",
"There is no good way to hook into the saving of an object when using the current Django generic views. Once they are rewritten as classes, you'll be able to subclass the view and hook in at the proper place without having to rewrite the whole view.\nI already use my own class-based generic views for this reason.\n",
"I would suggest to make a wrapper for the create_object, as this author suggest\nhttp://www.b-list.org/weblog/2006/nov/16/django-tips-get-most-out-generic-views/\nin the view you'll have access to the user info.\nAfterwards, you will need to use the extra_context to pass the user to the template. Finally at the template you can add a hidden field with the user info. I haven't tried it, but I have been thinking of it for quite some time. Hope this solution suits you!\n;) cheers!\n"
] |
[
3,
3,
1,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0000639792_django_python.txt
|
Q:
return a FaultObject on purpose from pyamf
I am currently migrating from RubyAMF to PyAMF. In RubyAMF you can return a FaultObject deliberately like so:
render :amf => FaultObject.new("Thats not your pie!")
Is there comparable functionality in PyAMF? I've searched the docs and can't find any mention of it.
A:
coulix is right (but due to reputation restrictions I cannot upvote! :)
From within your service method, raise an exception as you would normally and PyAMF will trap that and convert it to an appropriate fault object for consumption by the requestor (e.g. using Flex Messaging this will be an ErrorMessage instance).
class HandsOffThatPie(Exception):
pass
def get_pie(please=False):
if not please:
raise HandsOffThatPie('Say please!')
A:
raise Exception, "ur message" can do.
|
return a FaultObject on purpose from pyamf
|
I am currently migrating from RubyAMF to PyAMF. In RubyAMF you can return a FaultObject deliberately like so:
render :amf => FaultObject.new("Thats not your pie!")
Is there comparable functionality in PyAMF? I've searched the docs and can't find any mention of it.
|
[
"coulix is right (but due to reputation restrictions I cannot upvote! :)\nFrom within your service method, raise an exception as you would normally and PyAMF will trap that and convert it to an appropriate fault object for consumption by the requestor (e.g. using Flex Messaging this will be an ErrorMessage instance).\nclass HandsOffThatPie(Exception):\n pass\n\ndef get_pie(please=False):\n if not please:\n raise HandsOffThatPie('Say please!')\n\n",
"raise Exception, \"ur message\" can do.\n"
] |
[
1,
0
] |
[] |
[] |
[
"actionscript_3",
"apache_flex",
"django",
"pyamf",
"python"
] |
stackoverflow_0001772226_actionscript_3_apache_flex_django_pyamf_python.txt
|
Q:
Delaunay tessellation in Python?
I need to find the Delaunay tessellation of a polygon in Python, and the only libraries I could find (Delny, scikits) triangulate point clouds, not polygons. Any suggestions?
A:
Apparently Triangle has a Python binding. I'll try to get it working
A:
According to Wikipedia's article, the Delaunay triangulation is defined for a set of points, not for a polygon. Could you just pass the set of the polygon's points into one of those libraries?
A:
Have you tried matplotlib.delaunay.interpolate link text or Delny link text?
|
Delaunay tessellation in Python?
|
I need to find the Delaunay tessellation of a polygon in Python, and the only libraries I could find (Delny, scikits) triangulate point clouds, not polygons. Any suggestions?
|
[
"Apparently Triangle has a Python binding. I'll try to get it working\n",
"According to Wikipedia's article, the Delaunay triangulation is defined for a set of points, not for a polygon. Could you just pass the set of the polygon's points into one of those libraries?\n",
"Have you tried matplotlib.delaunay.interpolate link text or Delny link text? \n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"delaunay",
"graphics",
"python"
] |
stackoverflow_0001829365_delaunay_graphics_python.txt
|
Q:
python modify __metaclass__ for whole program
EDIT: Note that this is a REALLY BAD idea to do in production code. This was just an interesting thing for me. Don't do this at home!
Is it possible to modify __metaclass__ variable for whole program (interpreter) in Python?
This simple example is working:
class ChattyType(type):
def __init__(cls, name, bases, dct):
print "Class init", name
super(ChattyType, cls).__init__(name, bases, dct)
__metaclass__= ChattyType
class Data:
pass
data = Data() # prints "Class init Data"
print data
but I would love to be able change of __metaclass__ to work even in submodules. So for example (file m1.py):
class A:
pass
a=A()
print a
file main.py:
class ChattyType(type):
def __init__(cls, name, bases, dct):
print "Class init", name
super(ChattyType, cls).__init__(name, bases, dct)
__metaclass__= ChattyType
import m1 # and now print "Class init A"
class Data:
pass
data = Data() # print "Class init Data"
print data
I understand that global __metaclass__ is no longer working in Python 3.X, but that is not my concern (my code if proof of concept). So is there any way to accomplish this in Python-2.x?
A:
The "global __metaclass__" feature of Python 2 is designed to work per-module, only (just think what havoc it would wreak, otherwise, by forcing your own metaclass on all library and third-party modules that you imported from that point onwards -- shudder!). If it's very important to you to "secretly" alter the behavior of all modules you're importing from a certain point onwards, for whatever cloak-and-dagger reason, you could play very very dirty tricks with an import hook (at worst by first copying the sources to a temporary location while altering them...) but the effort would be proportionate to the enormity of the deed, which seems appropriate;-)
A:
Okay; IMO this is gross, hairy, dark magic. You shouldn't use it, perhaps ever, but especially not in production code. It is kind of interesting just for curiosity's sake, however.
You can write a custom importer using the mechanisms described in PEP 302, and further discussed in Doug Hellmann's PyMOTW: Modules and Imports. That gives you the tools to accomplish the task you contemplated.
I implemented such an importer, just because I was curious. Essentially, for the modules you specify by means of the class variable __chatty_for__, it will insert a custom type as a __metaclass__ variable in the imported module's __dict__, before the code is evaluated. If the code in question defines its own __metaclass__, that will replace the one pre-inserted by the importer. It would be inadvisable to apply this importer to any modules before carefully considering what it would do to them.
I haven't written many importers, so I may have done one or more silly things while writing this one. If anyone notices flaws / corner cases I missed in the implementation, please leave a comment.
source file 1:
# foo.py
class Foo: pass
source file 2:
# bar.py
class Bar: pass
source file 3:
# baaz.py
class Baaz: pass
and the main event:
# chattyimport.py
import imp
import sys
import types
class ChattyType(type):
def __init__(cls, name, bases, dct):
print "Class init", name
super(ChattyType, cls).__init__(name, bases, dct)
class ChattyImporter(object):
__chatty_for__ = []
def __init__(self, path_entry):
pass
def find_module(self, fullname, path=None):
if fullname not in self.__chatty_for__:
return None
try:
if path is None:
self.find_results = imp.find_module(fullname)
else:
self.find_results = imp.find_module(fullname, path)
except ImportError:
return None
(f,fn,(suf,mode,typ)) = self.find_results
if typ == imp.PY_SOURCE:
return self
return None
def load_module(self, fullname):
#print '%s loading module %s' % (type(self).__name__, fullname)
(f,fn,(suf,mode,typ)) = self.find_results
data = f.read()
if fullname in sys.modules:
module = sys.modules[fullname]
else:
sys.modules[fullname] = module = types.ModuleType(fullname)
module.__metaclass__ = ChattyType
module.__file__ = fn
module.__name__ = fullname
codeobj = compile(data, fn, 'exec')
exec codeobj in module.__dict__
return module
class ChattyImportSomeModules(ChattyImporter):
__chatty_for__ = 'foo bar'.split()
sys.meta_path.append(ChattyImportSomeModules(''))
import foo # prints 'Class init Foo'
import bar # prints 'Class init Bar'
import baaz
A:
Nope. (This is a feature!)
|
python modify __metaclass__ for whole program
|
EDIT: Note that this is a REALLY BAD idea to do in production code. This was just an interesting thing for me. Don't do this at home!
Is it possible to modify __metaclass__ variable for whole program (interpreter) in Python?
This simple example is working:
class ChattyType(type):
def __init__(cls, name, bases, dct):
print "Class init", name
super(ChattyType, cls).__init__(name, bases, dct)
__metaclass__= ChattyType
class Data:
pass
data = Data() # prints "Class init Data"
print data
but I would love to be able change of __metaclass__ to work even in submodules. So for example (file m1.py):
class A:
pass
a=A()
print a
file main.py:
class ChattyType(type):
def __init__(cls, name, bases, dct):
print "Class init", name
super(ChattyType, cls).__init__(name, bases, dct)
__metaclass__= ChattyType
import m1 # and now print "Class init A"
class Data:
pass
data = Data() # print "Class init Data"
print data
I understand that global __metaclass__ is no longer working in Python 3.X, but that is not my concern (my code if proof of concept). So is there any way to accomplish this in Python-2.x?
|
[
"The \"global __metaclass__\" feature of Python 2 is designed to work per-module, only (just think what havoc it would wreak, otherwise, by forcing your own metaclass on all library and third-party modules that you imported from that point onwards -- shudder!). If it's very important to you to \"secretly\" alter the behavior of all modules you're importing from a certain point onwards, for whatever cloak-and-dagger reason, you could play very very dirty tricks with an import hook (at worst by first copying the sources to a temporary location while altering them...) but the effort would be proportionate to the enormity of the deed, which seems appropriate;-)\n",
"Okay; IMO this is gross, hairy, dark magic. You shouldn't use it, perhaps ever, but especially not in production code. It is kind of interesting just for curiosity's sake, however.\nYou can write a custom importer using the mechanisms described in PEP 302, and further discussed in Doug Hellmann's PyMOTW: Modules and Imports. That gives you the tools to accomplish the task you contemplated.\nI implemented such an importer, just because I was curious. Essentially, for the modules you specify by means of the class variable __chatty_for__, it will insert a custom type as a __metaclass__ variable in the imported module's __dict__, before the code is evaluated. If the code in question defines its own __metaclass__, that will replace the one pre-inserted by the importer. It would be inadvisable to apply this importer to any modules before carefully considering what it would do to them.\nI haven't written many importers, so I may have done one or more silly things while writing this one. If anyone notices flaws / corner cases I missed in the implementation, please leave a comment.\nsource file 1:\n# foo.py\nclass Foo: pass\n\nsource file 2:\n# bar.py\nclass Bar: pass\n\nsource file 3:\n# baaz.py\nclass Baaz: pass\n\nand the main event:\n# chattyimport.py\nimport imp\nimport sys\nimport types\n\nclass ChattyType(type):\n def __init__(cls, name, bases, dct):\n print \"Class init\", name\n super(ChattyType, cls).__init__(name, bases, dct)\n\nclass ChattyImporter(object):\n\n __chatty_for__ = []\n\n def __init__(self, path_entry):\n pass\n\n def find_module(self, fullname, path=None):\n if fullname not in self.__chatty_for__:\n return None\n try:\n if path is None:\n self.find_results = imp.find_module(fullname)\n else:\n self.find_results = imp.find_module(fullname, path)\n except ImportError:\n return None\n (f,fn,(suf,mode,typ)) = self.find_results\n if typ == imp.PY_SOURCE:\n return self\n return None\n\n def load_module(self, fullname):\n #print '%s loading module %s' % (type(self).__name__, fullname)\n (f,fn,(suf,mode,typ)) = self.find_results\n data = f.read()\n if fullname in sys.modules:\n module = sys.modules[fullname]\n else:\n sys.modules[fullname] = module = types.ModuleType(fullname)\n\n module.__metaclass__ = ChattyType\n module.__file__ = fn\n module.__name__ = fullname\n codeobj = compile(data, fn, 'exec')\n exec codeobj in module.__dict__\n return module\n\nclass ChattyImportSomeModules(ChattyImporter):\n __chatty_for__ = 'foo bar'.split()\n\nsys.meta_path.append(ChattyImportSomeModules(''))\n\nimport foo # prints 'Class init Foo'\nimport bar # prints 'Class init Bar'\nimport baaz\n\n",
"Nope. (This is a feature!)\n"
] |
[
7,
4,
1
] |
[] |
[] |
[
"metaclass",
"metaprogramming",
"python",
"python_2.x"
] |
stackoverflow_0001829205_metaclass_metaprogramming_python_python_2.x.txt
|
Q:
Good way to pass variables for common elements to Mako templates?
I'm using Mako's inheritance features to factor out common page elements, like a header and footer, into a "base.mako" template. Page-specific controllers use their own templates, which inherit base.mako.
base.mako needs a set of variables -- for example, the name of the logged-on user goes in the header for all pages. However, it's the individual page controller that selects and renders the template, and is therefore responsible for passing variables to it.
I'd rather all of those page controllers not have to know what the base template needs in its context. What's a good way to establish the context for the base template in a situation like this?
Thanks in advance!
A:
You have two OO design choices for your page controllers.
Common features can be handled two ways.
Inheritance. All page controllers are subclasses of a common class that provides the common attributes.
Delegation. All page controllers are part of a pipeline where some common process (either before or after the page controller) folds in the additional information.
You have to pick one.
|
Good way to pass variables for common elements to Mako templates?
|
I'm using Mako's inheritance features to factor out common page elements, like a header and footer, into a "base.mako" template. Page-specific controllers use their own templates, which inherit base.mako.
base.mako needs a set of variables -- for example, the name of the logged-on user goes in the header for all pages. However, it's the individual page controller that selects and renders the template, and is therefore responsible for passing variables to it.
I'd rather all of those page controllers not have to know what the base template needs in its context. What's a good way to establish the context for the base template in a situation like this?
Thanks in advance!
|
[
"You have two OO design choices for your page controllers.\nCommon features can be handled two ways.\n\nInheritance. All page controllers are subclasses of a common class that provides the common attributes.\nDelegation. All page controllers are part of a pipeline where some common process (either before or after the page controller) folds in the additional information.\n\nYou have to pick one.\n"
] |
[
0
] |
[] |
[] |
[
"mako",
"python"
] |
stackoverflow_0001830042_mako_python.txt
|
Q:
TypeError: ListControl, must set a sequence (python error)
I am using Python Mechanize to open a website, fill out a form, and submit that form.
It's actually pretty simple.
It works until I come across radio buttons and "select" input boxes.
br.open(url)
br.select_form(name="postmsg")
br.form['subject'] = "Is this good for the holidays? "
br.form['message'] = "I'm new to technology."
br.form['E'] = '0'
br.submit()
br.form['E'] = '0'
File "build/bdist.linux-x86_64/egg/ClientForm.py", line 2897, in __setitem__
File "build/bdist.linux-x86_64/egg/ClientForm.py", line 2092, in __setattr__
File "build/bdist.linux-x86_64/egg/ClientForm.py", line 2100, in _set_value
TypeError: ListControl, must set a sequence
Why am I getting this error? Why can't I set E just like the text boxes? (E is a radio button)
Edit: This is the form, according to Web Developer.
Elements
Index Id Name Type Value Label Size Maximum Length State
0 subject subject text 35
2 message message textarea
3 identity identity select 1
13 action_btn hidden
14 _charset_ hidden
16 r hidden /Stocks_(A_to_Z)/Stocks_G
9 E radio 0
Checked
8 E radio 1
15 .crumb hidden 1n1Yo3MQae3
7 E radio 2
17 bn hidden 25263
6 E radio 3
5 E radio 4
4 E radio 5
12 SubmitCancel SubmitCancel submit Cancel
1 mbpostthreads threads button Check Existing Topics First
11 SubmitPost SubmitPost submit Post Message
10 SubmitPreview SubmitPreview submit Preview Message
18 yIdCoreIdUser hidden annamae41g
A:
Radio buttons and Check-boxes can have different behavior then other elements. It depends on their name and id.
If the items have the same name, try doing this:
br.find_control(name="E").value = ["0"]
Another option is:
form.find_control(name="E", kind="list").value = ["0"]
and finally, this might work:
br["E"] = ["0"]
(I haven't used mechanize in a while so i don't remember exactly).
|
TypeError: ListControl, must set a sequence (python error)
|
I am using Python Mechanize to open a website, fill out a form, and submit that form.
It's actually pretty simple.
It works until I come across radio buttons and "select" input boxes.
br.open(url)
br.select_form(name="postmsg")
br.form['subject'] = "Is this good for the holidays? "
br.form['message'] = "I'm new to technology."
br.form['E'] = '0'
br.submit()
br.form['E'] = '0'
File "build/bdist.linux-x86_64/egg/ClientForm.py", line 2897, in __setitem__
File "build/bdist.linux-x86_64/egg/ClientForm.py", line 2092, in __setattr__
File "build/bdist.linux-x86_64/egg/ClientForm.py", line 2100, in _set_value
TypeError: ListControl, must set a sequence
Why am I getting this error? Why can't I set E just like the text boxes? (E is a radio button)
Edit: This is the form, according to Web Developer.
Elements
Index Id Name Type Value Label Size Maximum Length State
0 subject subject text 35
2 message message textarea
3 identity identity select 1
13 action_btn hidden
14 _charset_ hidden
16 r hidden /Stocks_(A_to_Z)/Stocks_G
9 E radio 0
Checked
8 E radio 1
15 .crumb hidden 1n1Yo3MQae3
7 E radio 2
17 bn hidden 25263
6 E radio 3
5 E radio 4
4 E radio 5
12 SubmitCancel SubmitCancel submit Cancel
1 mbpostthreads threads button Check Existing Topics First
11 SubmitPost SubmitPost submit Post Message
10 SubmitPreview SubmitPreview submit Preview Message
18 yIdCoreIdUser hidden annamae41g
|
[
"Radio buttons and Check-boxes can have different behavior then other elements. It depends on their name and id.\nIf the items have the same name, try doing this:\nbr.find_control(name=\"E\").value = [\"0\"]\n\nAnother option is:\nform.find_control(name=\"E\", kind=\"list\").value = [\"0\"]\n\nand finally, this might work:\n br[\"E\"] = [\"0\"]\n\n(I haven't used mechanize in a while so i don't remember exactly).\n"
] |
[
8
] |
[] |
[] |
[
"http",
"mechanize",
"python",
"url"
] |
stackoverflow_0001830262_http_mechanize_python_url.txt
|
Q:
How to cleanly loop over two files in parallel in Python
I frequently write code like:
lines = open('wordprob.txt','r').readlines()
words = open('StdWord.txt','r').readlines()
i = 0
for line in lines:
v = [eval(s) for s in line.split()]
if v[0] > v[1]:
print words[i].strip(),
i += 1
Is it possible to avoid use variable i and make the program shorter?
Thanks.
A:
It looks like you don't care what the value of i is. You just are using it as a way to pair up the lines and the words. Therefore, I recommend you read one line at a time, and at the same time read one word. Then they will match.
Also, when you use .readlines() you read all the input at once into memory. For large inputs, this will be slow. For this simple code, one line at a time is all you need. The file object returned by open() can act as an iterator that returns one line at a time.
If you can, you should avoid the use of eval(). In a simple exercise where you know what the input data will be, it is pretty safe, but if you get data from outside sources, the use of eval() could possibly allow your computer to be attacked. See this page for more info. I will write my example code to assume that you are using eval() to turn text into a float value. float() will work on an integer string value, too: float('3') will return 3.0.
Also, it appears that the input lines can only have two values. If a line ever has extra values, your code will not detect this condition. We can change the code to explicitly unpack two values from the split line, and then if there are more than two values, Python will raise an exception. Plus, the code will be slightly nicer to read.
So here is my suggested rewrite of this example:
lines = open('wordprob.txt','rt')
words = open('StdWord.txt','rt')
for line in lines:
word = words.next().strip() # in Python 3: word = next(words).strip()
a, b = [float(s) for s in line.split()]
if a > b:
print word, # in Python 3: print(word + ' ', end='')
EDIT: And here is the same solution, but using izip().
import itertools
lines = open('wordprob.txt','rt')
words = open('StdWord.txt','rt')
# in Python 3, just use zip() instead of izip()
for line, word in itertools.izip(lines, words):
word = word.strip()
a, b = [float(s) for s in line.split()]
if a > b:
print word, # in Python 3: print(word + ' ', end='')
In Python 3, the built-in zip() returns an iterator, so you can just use that and not need to import itertools.
EDIT:
It is best practice to use a with statement to make sure the files are properly closed, no matter what. In recent versions of Python you can have multiple with statements, and I'll do that in my solution. Also, we can unpack a generator expression just as easily as we can unpack a list, so I've changed the line that sets a, b to use a generator expression; that should be slightly faster. And we don't need to strip word unless we are going to use it. Put the changes together to get:
from itertools import izip
with open('wordprob.txt','rt') as lines, open('StdWord.txt','rt') as words:
# in Python 3, just use zip() instead of izip()
for line, word in izip(lines, words):
a, b = (float(s) for s in line.split())
if a > b:
print word.strip(), # in Python 3: print(word.strip() + ' ', end='')
A:
You can try to use enumerate,
http://docs.python.org/tutorial/datastructures.html#looping-techniques
lines = open('wordprob.txt','r').readlines()
words = open('StdWord.txt','r').readlines()
for i,line in enumerate(lines):
v = [eval(s) for s in line.split()]
if v[0] > v[1]:
print words[i].strip()
A:
In general enumerate is a good solution. In this case, you could do something like:
lines = open('wordprob.txt','r').readlines()
words = open('StdWord.txt','r').readlines()
for word, line in zip(words, lines):
v = [eval(s) for s in line.split()]
if v[0] > v[1]:
print word.strip(),
A:
Take a look at enumerate:
>>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
... print i, season
0 Spring
1 Summer
2 Fall
3 Winter
|
How to cleanly loop over two files in parallel in Python
|
I frequently write code like:
lines = open('wordprob.txt','r').readlines()
words = open('StdWord.txt','r').readlines()
i = 0
for line in lines:
v = [eval(s) for s in line.split()]
if v[0] > v[1]:
print words[i].strip(),
i += 1
Is it possible to avoid use variable i and make the program shorter?
Thanks.
|
[
"It looks like you don't care what the value of i is. You just are using it as a way to pair up the lines and the words. Therefore, I recommend you read one line at a time, and at the same time read one word. Then they will match.\nAlso, when you use .readlines() you read all the input at once into memory. For large inputs, this will be slow. For this simple code, one line at a time is all you need. The file object returned by open() can act as an iterator that returns one line at a time.\nIf you can, you should avoid the use of eval(). In a simple exercise where you know what the input data will be, it is pretty safe, but if you get data from outside sources, the use of eval() could possibly allow your computer to be attacked. See this page for more info. I will write my example code to assume that you are using eval() to turn text into a float value. float() will work on an integer string value, too: float('3') will return 3.0.\nAlso, it appears that the input lines can only have two values. If a line ever has extra values, your code will not detect this condition. We can change the code to explicitly unpack two values from the split line, and then if there are more than two values, Python will raise an exception. Plus, the code will be slightly nicer to read.\nSo here is my suggested rewrite of this example:\nlines = open('wordprob.txt','rt')\nwords = open('StdWord.txt','rt')\n\nfor line in lines:\n word = words.next().strip() # in Python 3: word = next(words).strip()\n a, b = [float(s) for s in line.split()]\n if a > b:\n print word, # in Python 3: print(word + ' ', end='')\n\nEDIT: And here is the same solution, but using izip().\nimport itertools\nlines = open('wordprob.txt','rt')\nwords = open('StdWord.txt','rt')\n\n# in Python 3, just use zip() instead of izip()\nfor line, word in itertools.izip(lines, words):\n word = word.strip()\n a, b = [float(s) for s in line.split()]\n if a > b:\n print word, # in Python 3: print(word + ' ', end='')\n\nIn Python 3, the built-in zip() returns an iterator, so you can just use that and not need to import itertools.\nEDIT:\nIt is best practice to use a with statement to make sure the files are properly closed, no matter what. In recent versions of Python you can have multiple with statements, and I'll do that in my solution. Also, we can unpack a generator expression just as easily as we can unpack a list, so I've changed the line that sets a, b to use a generator expression; that should be slightly faster. And we don't need to strip word unless we are going to use it. Put the changes together to get:\nfrom itertools import izip\n\nwith open('wordprob.txt','rt') as lines, open('StdWord.txt','rt') as words:\n # in Python 3, just use zip() instead of izip()\n for line, word in izip(lines, words):\n a, b = (float(s) for s in line.split())\n if a > b:\n print word.strip(), # in Python 3: print(word.strip() + ' ', end='')\n\n",
"You can try to use enumerate, \nhttp://docs.python.org/tutorial/datastructures.html#looping-techniques\nlines = open('wordprob.txt','r').readlines()\nwords = open('StdWord.txt','r').readlines()\nfor i,line in enumerate(lines):\n v = [eval(s) for s in line.split()]\n if v[0] > v[1]:\n print words[i].strip()\n\n",
"In general enumerate is a good solution. In this case, you could do something like:\nlines = open('wordprob.txt','r').readlines()\nwords = open('StdWord.txt','r').readlines()\nfor word, line in zip(words, lines):\n v = [eval(s) for s in line.split()]\n if v[0] > v[1]:\n print word.strip(),\n\n",
"Take a look at enumerate:\n>>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):\n... print i, season\n0 Spring\n1 Summer\n2 Fall\n3 Winter\n\n"
] |
[
22,
16,
5,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001830552_python.txt
|
Q:
Uncompress Zlib string in using ByteArrays
I have a web application developed in Adobe Flex 3 and Python 2.5 (deployed on Google App Engine). A RESTful web service has been created in Python and its results are currently in an XML format which is being read by Flex using the HttpService object.
Now the main objective is to compress the XML so that there is as less a time between the HttpService send() method and result events. I looked up Python docs and managed to use zlib.compress() to compress the XML result.
Then I set the HttpService result type from "xml" to "text" and tried using ByteArrays to uncompress the string back to XML. Here's where I failed. I am doing something like this:
var byteArray:ByteArray = new ByteArray();
byteArray.writeUTF( event.result.toString() );
byteArray.uncompress();
var xmlResult:XML = byteArray.readUTF();
Its throwing an exception at byteArray.uncompress() and says unable to uncompress the byteArray. Also when I trace the length of the byteArray it gets 0.
Unable to figure out what I'm doing wrong. All help is appreciated.
-- Edit --
The code:
# compressing the xml result in Python
print zlib.compress(xmlResult)
# decompresisng it in AS3
var byteArray:ByteArray = new ByteArray();
byteArray.writeUTF( event.result.toString() );
byteArray.uncompress()
Event is of type ResultEvent.
The error:
Error: Error #2058: There was an error decompressing the data.
The error could be because the value of byteArray.bytesAvailable = 0 which means the raw bytes python generated hasn't been written into byteArray properly..
-- Sri
A:
What is byteArray.writeUTF( event.result.toString() ); supposed to do? The result of zlib.compress() is neither unicode nor "UTF" (meaningless without a number after it!?); it is binary aka raw bytes; you should neither decode it nor encode it nor apply any other transformation to it. The receiver should decompress immediately the raw bytes that it receives, in order to recover the data that was passed to zlib.compress().
Update What documentation do you have to support the notion that byteArray.uncompress() is expecting a true zlib stream and not a deflate stream (i.e. a zlib stream after you've snipped the first 2 bytes and the last 4)?
The Flex 3 documentation of ByteArray gives this example:
bytes.uncompress(CompressionAlgorithm.DEFLATE);
but unhelpfully doesn't say what the default (if any) is. If there is a default, it's not documented anywhere obvious, so it would be a very good idea for you to use
bytes.uncompress(CompressionAlgorithm.ZLIB);
to make it obvious what you intend.
AND the docs talk about a writeUTFBytes method, not a writeUTF method. Are you sure that you copy/pasted the exact receiver code in your question?
Update 2
Thanks for the URL. Looks like I got hold of the "help", not the real docs :=(. A couple of points:
(1) Yes, there is an explicit inflate() method. However uncompress DOES have an algorithm arg; it can be either CompressionAlgorithm.ZLIB (the default) or CompressionAlgorithm.DEFLATE ... interestingly the latter is however only available in Adobe Air, not in Flash Player. At least we know the uncompress() call appears OK, and we can get back to the problem of getting the raw bytes onto the wire and off again into a ByteArray instance.
(2) More importantly, there are both writeUTF (Writes a UTF-8 string to the byte stream. The length of the UTF-8 string in bytes is written first, as a 16-bit integer, followed by the bytes representing the characters of the string) and writeUTFBytes (Writes a UTF-8 string to the byte stream. Similar to the writeUTF() method, but writeUTFBytes() does not prefix the string with a 16-bit length word).
Whatever the merits of supplying UTF8-encoded bytes (nil, IMHO), you don't want a 2-byte length prefix there; using writeUTF() is guaranteed to cause uncompress() to bork.
Getting it on to the wire: using Python print on binary data doesn't seem like a good idea (unless sys.stdout has been nobbled to run in raw mode, which you didn't show in your code).
Likewise doing event.result.toString() getting a string (similar to a Python unicode object, yes/no?) -- with what and then encoding it in UTF-8 seem rather unlikely to work.
Given I didn't know that flex existed until today, I really can't help you effectively. Here are some further suggestions towards self-sufficiency in case nobody who knows more flex comes along soon:
(1) Do some debugging. Start off with a minimal XML document. Show repr(xml_doc). Show repr(zlib_compress_output). In (a cut-down version of) your flex script, use the closest function/method to repr() that you can find to show: event.result, event.result.toString() and the result of writeUTF*(). Make sure you understand the effects of everything that can happen after zlib.compress(). Reading the docs carefully may help.
(2) Look at how you can get raw bytes out of event.result.
HTH,
John
|
Uncompress Zlib string in using ByteArrays
|
I have a web application developed in Adobe Flex 3 and Python 2.5 (deployed on Google App Engine). A RESTful web service has been created in Python and its results are currently in an XML format which is being read by Flex using the HttpService object.
Now the main objective is to compress the XML so that there is as less a time between the HttpService send() method and result events. I looked up Python docs and managed to use zlib.compress() to compress the XML result.
Then I set the HttpService result type from "xml" to "text" and tried using ByteArrays to uncompress the string back to XML. Here's where I failed. I am doing something like this:
var byteArray:ByteArray = new ByteArray();
byteArray.writeUTF( event.result.toString() );
byteArray.uncompress();
var xmlResult:XML = byteArray.readUTF();
Its throwing an exception at byteArray.uncompress() and says unable to uncompress the byteArray. Also when I trace the length of the byteArray it gets 0.
Unable to figure out what I'm doing wrong. All help is appreciated.
-- Edit --
The code:
# compressing the xml result in Python
print zlib.compress(xmlResult)
# decompresisng it in AS3
var byteArray:ByteArray = new ByteArray();
byteArray.writeUTF( event.result.toString() );
byteArray.uncompress()
Event is of type ResultEvent.
The error:
Error: Error #2058: There was an error decompressing the data.
The error could be because the value of byteArray.bytesAvailable = 0 which means the raw bytes python generated hasn't been written into byteArray properly..
-- Sri
|
[
"What is byteArray.writeUTF( event.result.toString() ); supposed to do? The result of zlib.compress() is neither unicode nor \"UTF\" (meaningless without a number after it!?); it is binary aka raw bytes; you should neither decode it nor encode it nor apply any other transformation to it. The receiver should decompress immediately the raw bytes that it receives, in order to recover the data that was passed to zlib.compress().\nUpdate What documentation do you have to support the notion that byteArray.uncompress() is expecting a true zlib stream and not a deflate stream (i.e. a zlib stream after you've snipped the first 2 bytes and the last 4)?\nThe Flex 3 documentation of ByteArray gives this example:\nbytes.uncompress(CompressionAlgorithm.DEFLATE);\nbut unhelpfully doesn't say what the default (if any) is. If there is a default, it's not documented anywhere obvious, so it would be a very good idea for you to use\nbytes.uncompress(CompressionAlgorithm.ZLIB);\nto make it obvious what you intend.\nAND the docs talk about a writeUTFBytes method, not a writeUTF method. Are you sure that you copy/pasted the exact receiver code in your question?\nUpdate 2\nThanks for the URL. Looks like I got hold of the \"help\", not the real docs :=(. A couple of points:\n(1) Yes, there is an explicit inflate() method. However uncompress DOES have an algorithm arg; it can be either CompressionAlgorithm.ZLIB (the default) or CompressionAlgorithm.DEFLATE ... interestingly the latter is however only available in Adobe Air, not in Flash Player. At least we know the uncompress() call appears OK, and we can get back to the problem of getting the raw bytes onto the wire and off again into a ByteArray instance.\n(2) More importantly, there are both writeUTF (Writes a UTF-8 string to the byte stream. The length of the UTF-8 string in bytes is written first, as a 16-bit integer, followed by the bytes representing the characters of the string) and writeUTFBytes (Writes a UTF-8 string to the byte stream. Similar to the writeUTF() method, but writeUTFBytes() does not prefix the string with a 16-bit length word).\nWhatever the merits of supplying UTF8-encoded bytes (nil, IMHO), you don't want a 2-byte length prefix there; using writeUTF() is guaranteed to cause uncompress() to bork.\nGetting it on to the wire: using Python print on binary data doesn't seem like a good idea (unless sys.stdout has been nobbled to run in raw mode, which you didn't show in your code).\nLikewise doing event.result.toString() getting a string (similar to a Python unicode object, yes/no?) -- with what and then encoding it in UTF-8 seem rather unlikely to work.\nGiven I didn't know that flex existed until today, I really can't help you effectively. Here are some further suggestions towards self-sufficiency in case nobody who knows more flex comes along soon:\n(1) Do some debugging. Start off with a minimal XML document. Show repr(xml_doc). Show repr(zlib_compress_output). In (a cut-down version of) your flex script, use the closest function/method to repr() that you can find to show: event.result, event.result.toString() and the result of writeUTF*(). Make sure you understand the effects of everything that can happen after zlib.compress(). Reading the docs carefully may help.\n(2) Look at how you can get raw bytes out of event.result.\nHTH,\nJohn\n"
] |
[
2
] |
[] |
[] |
[
"actionscript_3",
"apache_flex",
"compression",
"python",
"zlib"
] |
stackoverflow_0001830665_actionscript_3_apache_flex_compression_python_zlib.txt
|
Q:
Python - Exists a function that is called when an object does not implement a function?
In Smalltalk there is a message DoesNotUnderstand that is called when an object does not understand a message (this is, when the object does not have the message sent implemented).
So, I like to know if in python there is a function that does the same thing.
In this example:
class MyObject:
def __init__(self):
print "MyObject created"
anObject = MyObject() # prints: MyObject created
anObject.DoSomething() # raise an Exception
So, can I add a method to MyObject so I can know when DoSomething is intented to be called?
PS: Sorry for my poor English.
A:
Here is a proposition for what you want to do:
class callee:
def __init__(self, name):
self.name = name
def __call__(self):
print self.name, "has been called"
class A:
def __getattr__(self, attr):
return callee(attr)
a = A()
a.DoSomething()
>>> DoSomething has been called
A:
You are looking for the __getattr__ method. Have a look here.
If you want "total control" of a class, look at the __getattribute__ special method then (here).
A:
Have you looked at object.__getattr__(self, name), or object.__getattribute__(self, name) for new-style classes? (see Special method names, Python language reference)
A:
I don't know why luc had the two separate classes. You can do it all with one class, if you use a closure. Like so:
class A(object):
__ignored_attributes__ = set(["__str__"])
def __getattr__(self, name):
if __name__ in self.__ignored_attributes__:
return None
def fn():
print name, "has been called with self =", self
return fn
a = A()
a.DoSomething()
I added the bit about __ignored_attributes__ because Python was looking up __str__ in the class and that got a little messy.
|
Python - Exists a function that is called when an object does not implement a function?
|
In Smalltalk there is a message DoesNotUnderstand that is called when an object does not understand a message (this is, when the object does not have the message sent implemented).
So, I like to know if in python there is a function that does the same thing.
In this example:
class MyObject:
def __init__(self):
print "MyObject created"
anObject = MyObject() # prints: MyObject created
anObject.DoSomething() # raise an Exception
So, can I add a method to MyObject so I can know when DoSomething is intented to be called?
PS: Sorry for my poor English.
|
[
"Here is a proposition for what you want to do:\nclass callee:\n def __init__(self, name):\n self.name = name\n\n def __call__(self):\n print self.name, \"has been called\"\n\n\nclass A:\n def __getattr__(self, attr):\n return callee(attr)\n\na = A()\n\na.DoSomething()\n>>> DoSomething has been called\n\n",
"You are looking for the __getattr__ method. Have a look here.\nIf you want \"total control\" of a class, look at the __getattribute__ special method then (here).\n",
"Have you looked at object.__getattr__(self, name), or object.__getattribute__(self, name) for new-style classes? (see Special method names, Python language reference)\n",
"I don't know why luc had the two separate classes. You can do it all with one class, if you use a closure. Like so:\nclass A(object):\n __ignored_attributes__ = set([\"__str__\"])\n\n def __getattr__(self, name):\n if __name__ in self.__ignored_attributes__:\n return None\n\n def fn():\n print name, \"has been called with self =\", self\n\n return fn\n\na = A()\na.DoSomething()\n\nI added the bit about __ignored_attributes__ because Python was looking up __str__ in the class and that got a little messy.\n"
] |
[
7,
3,
3,
2
] |
[] |
[] |
[
"function",
"oop",
"python"
] |
stackoverflow_0001820160_function_oop_python.txt
|
Q:
How to load compiled python modules from memory?
I need to read all modules (pre-compiled) from a zipfile (built by py2exe compressed) into memory and then load them all.
I know this can be done by loading direct from the zipfile but I need to load them from memory.
Any ideas? (I'm using python 2.5.2 on windows)
TIA Steve
A:
It depends on what exactly you have as "the module (pre-compiled)". Let's assume it's exactly the contents of a .pyc file, e.g., ciao.pyc as built by:
$ cat>'ciao.py'
def ciao(): return 'Ciao!'
$ python -c'import ciao; print ciao.ciao()'
Ciao!
IOW, having thus built ciao.pyc, say that you now do:
$ python
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> b = open('ciao.pyc', 'rb').read()
>>> len(b)
200
and your goal is to go from that byte string b to an importable module ciao. Here's how:
>>> import marshal
>>> c = marshal.loads(b[8:])
>>> c
<code object <module> at 0x65188, file "ciao.py", line 1>
this is how you get the code object from the .pyc binary contents. Edit: if you're curious, the first 8 bytes are a "magic number" and a timestamp -- not needed here (unless you want to sanity-check them and raise exceptions if warranted, but that seems outside the scope of the question; marshal.loads will raise anyway if it detects a corrupt string).
Then:
>>> import types
>>> m = types.ModuleType('ciao')
>>> import sys
>>> sys.modules['ciao'] = m
>>> exec c in m.__dict__
i.e: make a new module object, install it in sys.modules, populate it by executing the code object in its __dict__. Edit: the order in which you do the sys.modules insertion and exec matters if and only if you may have circular imports -- but, this is the order Python's own import normally uses, so it's better to mimic it (which has no specific downsides).
You can "make a new module object" in several ways (e.g., from functions in standard library modules such as new and imp), but "call the type to get an instance" is the normal Python way these days, and the normal place to obtain the type from (unless it has a built-in name or you otherwise have it already handy) is from the standard library module types, so that's what I recommend.
Now, finally:
>>> import ciao
>>> ciao.ciao()
'Ciao!'
>>>
...you can import the module and use its functions, classes, and so on. Other import (and from) statements will then find the module as sys.modules['ciao'], so you won't need to repeat this sequence of operations (indeed you don't need this last import statement here if all you want is to ensure the module is available for import from elsewhere -- I'm adding it only to show it works;-).
Edit: If you absolutely must import in this way packages and modules therefrom, rather than "plain modules" as I just showed, that's doable, too, but a bit more complicated. As this answer is already pretty long, and I hope you can simplify your life by sticking to plain modules for this purpose, I'm going to shirk that part of the answer;-).
Also note that this may or may not do what you want in cases of "loading the same module from memory multiple times" (this rebuilds the module each time; you might want to check sys.modules and just skip everything if the module's already there) and in particular when such repeated "load from memory" occurs from multiple threads (needing locks -- but, a better architecture is to have a single dedicated thread devoted to performing the task, with other modules communicating with it via a Queue).
Finally, there's no discussion of how to install this functionality as a transparent "import hook" which automagically gets involved in the mechanisms of the import statement internals themselves -- that's feasible, too, but not exactly what you're asking about, so here, too, I hope you can simplify your life by doing things the simple way instead, as this answer outlines.
A:
Compiled Python file consist of
magic number (4 bytes) to determine type and version of Python,
timestamp (4 bytes) to check whether we have newer source,
marshaled code object.
To load module you have to create module object with imp.new_module(), execute unmashaled code in new module's namespace and put it in sys.modules. Below in sample implementation:
import sys, imp, marshal
def load_compiled_from_memory(name, filename, data, ispackage=False):
if data[:4]!=imp.get_magic():
raise ImportError('Bad magic number in %s' % filename)
# Ignore timestamp in data[4:8]
code = marshal.loads(data[8:])
imp.acquire_lock() # Required in threaded applications
try:
mod = imp.new_module(name)
sys.modules[name] = mod # To handle circular and submodule imports
# it should come before exec.
try:
mod.__file__ = filename # Is not so important.
# For package you have to set mod.__path__ here.
# Here I handle simple cases only.
if ispackage:
mod.__path__ = [name.replace('.', '/')]
exec code in mod.__dict__
except:
del sys.modules[name]
raise
finally:
imp.release_lock()
return mod
Update: the code is updated to handle packages properly.
Note that you have to install import hook to handle imports inside loaded modules. One way to do this is adding your finder into sys.meta_path. See PEP302 for more information.
|
How to load compiled python modules from memory?
|
I need to read all modules (pre-compiled) from a zipfile (built by py2exe compressed) into memory and then load them all.
I know this can be done by loading direct from the zipfile but I need to load them from memory.
Any ideas? (I'm using python 2.5.2 on windows)
TIA Steve
|
[
"It depends on what exactly you have as \"the module (pre-compiled)\". Let's assume it's exactly the contents of a .pyc file, e.g., ciao.pyc as built by:\n$ cat>'ciao.py'\ndef ciao(): return 'Ciao!' \n$ python -c'import ciao; print ciao.ciao()'\nCiao!\n\nIOW, having thus built ciao.pyc, say that you now do:\n$ python\nPython 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> b = open('ciao.pyc', 'rb').read()\n>>> len(b)\n200\n\nand your goal is to go from that byte string b to an importable module ciao. Here's how:\n>>> import marshal\n>>> c = marshal.loads(b[8:])\n>>> c\n<code object <module> at 0x65188, file \"ciao.py\", line 1>\n\nthis is how you get the code object from the .pyc binary contents. Edit: if you're curious, the first 8 bytes are a \"magic number\" and a timestamp -- not needed here (unless you want to sanity-check them and raise exceptions if warranted, but that seems outside the scope of the question; marshal.loads will raise anyway if it detects a corrupt string).\nThen:\n>>> import types\n>>> m = types.ModuleType('ciao')\n>>> import sys\n>>> sys.modules['ciao'] = m\n>>> exec c in m.__dict__\n\ni.e: make a new module object, install it in sys.modules, populate it by executing the code object in its __dict__. Edit: the order in which you do the sys.modules insertion and exec matters if and only if you may have circular imports -- but, this is the order Python's own import normally uses, so it's better to mimic it (which has no specific downsides).\nYou can \"make a new module object\" in several ways (e.g., from functions in standard library modules such as new and imp), but \"call the type to get an instance\" is the normal Python way these days, and the normal place to obtain the type from (unless it has a built-in name or you otherwise have it already handy) is from the standard library module types, so that's what I recommend.\nNow, finally:\n>>> import ciao\n>>> ciao.ciao()\n'Ciao!'\n>>> \n\n...you can import the module and use its functions, classes, and so on. Other import (and from) statements will then find the module as sys.modules['ciao'], so you won't need to repeat this sequence of operations (indeed you don't need this last import statement here if all you want is to ensure the module is available for import from elsewhere -- I'm adding it only to show it works;-).\nEdit: If you absolutely must import in this way packages and modules therefrom, rather than \"plain modules\" as I just showed, that's doable, too, but a bit more complicated. As this answer is already pretty long, and I hope you can simplify your life by sticking to plain modules for this purpose, I'm going to shirk that part of the answer;-).\nAlso note that this may or may not do what you want in cases of \"loading the same module from memory multiple times\" (this rebuilds the module each time; you might want to check sys.modules and just skip everything if the module's already there) and in particular when such repeated \"load from memory\" occurs from multiple threads (needing locks -- but, a better architecture is to have a single dedicated thread devoted to performing the task, with other modules communicating with it via a Queue).\nFinally, there's no discussion of how to install this functionality as a transparent \"import hook\" which automagically gets involved in the mechanisms of the import statement internals themselves -- that's feasible, too, but not exactly what you're asking about, so here, too, I hope you can simplify your life by doing things the simple way instead, as this answer outlines.\n",
"Compiled Python file consist of\n\nmagic number (4 bytes) to determine type and version of Python,\ntimestamp (4 bytes) to check whether we have newer source,\nmarshaled code object.\n\nTo load module you have to create module object with imp.new_module(), execute unmashaled code in new module's namespace and put it in sys.modules. Below in sample implementation:\nimport sys, imp, marshal\n\ndef load_compiled_from_memory(name, filename, data, ispackage=False):\n if data[:4]!=imp.get_magic():\n raise ImportError('Bad magic number in %s' % filename)\n # Ignore timestamp in data[4:8]\n code = marshal.loads(data[8:])\n imp.acquire_lock() # Required in threaded applications\n try:\n mod = imp.new_module(name)\n sys.modules[name] = mod # To handle circular and submodule imports \n # it should come before exec.\n try:\n mod.__file__ = filename # Is not so important.\n # For package you have to set mod.__path__ here. \n # Here I handle simple cases only.\n if ispackage:\n mod.__path__ = [name.replace('.', '/')]\n exec code in mod.__dict__\n except:\n del sys.modules[name]\n raise\n finally:\n imp.release_lock()\n return mod\n\nUpdate: the code is updated to handle packages properly.\nNote that you have to install import hook to handle imports inside loaded modules. One way to do this is adding your finder into sys.meta_path. See PEP302 for more information.\n"
] |
[
33,
10
] |
[] |
[] |
[
"module",
"python"
] |
stackoverflow_0001830727_module_python.txt
|
Q:
Boost.Python: __init__ accepting None argument
I have a C++ value type wrapped with Boost.Python which has a concept of a NULL value. The relevant parts of the wrapper code appear as follows:
class_<TCurrency> currency( "TCurrency" )
.def( init<long>() )
.def( init<const std::string&>() )
<...>;
Currently, trying to create a NULL instance in Python by passing None to the __init__() method causes the C++ ctor accepting a const string reference to be called with an invalid reference. (&arg == NULL)
Is it possible to trap the case where None is being passed to a constructor and handle it gracefully or at least to throw a meaningful exception before my program crashes?
Using Boost 1.36 and Python 2.6.2.
A:
Adding an init<void*> overload will pass NULL if None is used, but I'm not sure how this could affect other ctors in corner cases. I also don't get the same None to string const& conversion that you mention, if I leave init<void*> out. Using Boost.Python 1.37 and Python 2.6.2.
Example:
#include <iostream>
#include <string>
#include <boost/python.hpp>
struct A {
#define BODY { std::cout << __PRETTY_FUNCTION__ << '\n'; }
A() BODY
A(long) BODY
A(std::string const&) BODY
A(void* p) BODY
#undef BODY
};
BOOST_PYTHON_MODULE(ex) {
using namespace boost::python;
class_<A>("A")
.def(init<long>())
.def(init<std::string const&>())
.def(init<void*>())
;
}
>>> import ex
>>> ex.A()
A::A()
<ex.A object at 0x839bf7c>
>>> ex.A(42)
A::A(long int)
<ex.A object at 0x839bfcc>
>>> ex.A("abc")
A::A(const std::string&)
<ex.A object at 0x839bf7c>
>>> ex.A(None)
A::A(void*)
<ex.A object at 0x839bfcc>
If init<void*> is left out:
>>> ex.A(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
A.__init__(A, NoneType)
did not match C++ signature:
__init__(_object*, std::string)
__init__(_object*, long)
__init__(_object*)
|
Boost.Python: __init__ accepting None argument
|
I have a C++ value type wrapped with Boost.Python which has a concept of a NULL value. The relevant parts of the wrapper code appear as follows:
class_<TCurrency> currency( "TCurrency" )
.def( init<long>() )
.def( init<const std::string&>() )
<...>;
Currently, trying to create a NULL instance in Python by passing None to the __init__() method causes the C++ ctor accepting a const string reference to be called with an invalid reference. (&arg == NULL)
Is it possible to trap the case where None is being passed to a constructor and handle it gracefully or at least to throw a meaningful exception before my program crashes?
Using Boost 1.36 and Python 2.6.2.
|
[
"Adding an init<void*> overload will pass NULL if None is used, but I'm not sure how this could affect other ctors in corner cases. I also don't get the same None to string const& conversion that you mention, if I leave init<void*> out. Using Boost.Python 1.37 and Python 2.6.2.\nExample:\n#include <iostream>\n#include <string>\n\n#include <boost/python.hpp>\n\n\nstruct A {\n#define BODY { std::cout << __PRETTY_FUNCTION__ << '\\n'; }\n A() BODY\n A(long) BODY\n A(std::string const&) BODY\n A(void* p) BODY\n#undef BODY\n};\n\nBOOST_PYTHON_MODULE(ex) {\nusing namespace boost::python;\nclass_<A>(\"A\")\n .def(init<long>())\n .def(init<std::string const&>())\n .def(init<void*>())\n;\n}\n\n\n>>> import ex\n>>> ex.A()\nA::A()\n<ex.A object at 0x839bf7c>\n>>> ex.A(42)\nA::A(long int)\n<ex.A object at 0x839bfcc>\n>>> ex.A(\"abc\")\nA::A(const std::string&)\n<ex.A object at 0x839bf7c>\n>>> ex.A(None)\nA::A(void*)\n<ex.A object at 0x839bfcc>\n\nIf init<void*> is left out:\n\n>>> ex.A(None)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nBoost.Python.ArgumentError: Python argument types in\n A.__init__(A, NoneType)\ndid not match C++ signature:\n __init__(_object*, std::string)\n __init__(_object*, long)\n __init__(_object*)\n\n"
] |
[
2
] |
[] |
[] |
[
"boost_python",
"crash",
"python"
] |
stackoverflow_0001830902_boost_python_crash_python.txt
|
Q:
Pythonic List Comprehension
This seems like a common task, alter some elements of an array, but my solution didn't feel very pythonic. Is there a better way to build urls with list comprehension?
links = re.findall(r"(?:https?://|www\.|https?://www\.)[\S]+", text)
if len(links) == 0:
return text
urls = []
for link in links:
if link[0:4] == "www.":
link = "http://" + link
urls.append(link)
Maybe something like
links = re.findall(r"(?:https?://|www\.|https?://www\.)[\S]+", text)
if len(links) == 0:
return text
urls = map(lambda x : something(x), links)
A:
If you want to go with list comprehensions, use:
urls = ['http://' + link if link.startswith('www.') else link for link in links]
But I actually think that the more verbose way of looping through the links that you used is easier to read. "Shorter" does not always equal "better" or "more readable".
A:
["http://"+link if link[0:4]=='www.' else link for link in links]
or
[link[0:4]=='www.' and "http://"+link or link for link in links]
Notes:
("http://"+link if link[0:4]=='www.' else link) - this is ternary operator like ?: in C
(link[0:4]=='www.' and "http://"+link or link) - this has the same meaning.
On another subject: I would test for http://, not for www. Domains don't have to start with www. For instance, http://stackoverflow.com.
A:
You'll probably be better off using built-in Python functionality for dealing with urls. Assuming you stay with your current regex, I think you could rewrite this as:
from urlparse import urlsplit, urlunsplit
links = re.findall("(?:https?://|www\.|https?://www\.)[\S]+", text)
urls = [urlunsplit(urlsplit(link, 'http')) for link links]
This should come out to the same thing as what you're currently doing. Also keep in mind that finding URLs using a regex is somewhat risky, ie this will return www.google.com! with the exclamation mark.
A:
Alternatively:
def addHttp(url):
if url[0:4] == "www.":
url = "http://" + url
return url
urls = map(addHttp, links)
this is longer than using list comprehensions and the ternary operator, but IMHO it is more readable since the function name describes what it is doing, so the code is self-documenting. It is also easier to refactor e.g. if you decide to follow yu_sha's advice and not test explicitly for "www".
|
Pythonic List Comprehension
|
This seems like a common task, alter some elements of an array, but my solution didn't feel very pythonic. Is there a better way to build urls with list comprehension?
links = re.findall(r"(?:https?://|www\.|https?://www\.)[\S]+", text)
if len(links) == 0:
return text
urls = []
for link in links:
if link[0:4] == "www.":
link = "http://" + link
urls.append(link)
Maybe something like
links = re.findall(r"(?:https?://|www\.|https?://www\.)[\S]+", text)
if len(links) == 0:
return text
urls = map(lambda x : something(x), links)
|
[
"If you want to go with list comprehensions, use:\nurls = ['http://' + link if link.startswith('www.') else link for link in links]\n\nBut I actually think that the more verbose way of looping through the links that you used is easier to read. \"Shorter\" does not always equal \"better\" or \"more readable\".\n",
"[\"http://\"+link if link[0:4]=='www.' else link for link in links]\n\nor \n[link[0:4]=='www.' and \"http://\"+link or link for link in links]\n\n\nNotes:\n (\"http://\"+link if link[0:4]=='www.' else link) - this is ternary operator like ?: in C\n(link[0:4]=='www.' and \"http://\"+link or link) - this has the same meaning. \n\nOn another subject: I would test for http://, not for www. Domains don't have to start with www. For instance, http://stackoverflow.com.\n",
"You'll probably be better off using built-in Python functionality for dealing with urls. Assuming you stay with your current regex, I think you could rewrite this as:\nfrom urlparse import urlsplit, urlunsplit\n\nlinks = re.findall(\"(?:https?://|www\\.|https?://www\\.)[\\S]+\", text)\nurls = [urlunsplit(urlsplit(link, 'http')) for link links]\n\nThis should come out to the same thing as what you're currently doing. Also keep in mind that finding URLs using a regex is somewhat risky, ie this will return www.google.com! with the exclamation mark.\n",
"Alternatively:\ndef addHttp(url):\n if url[0:4] == \"www.\":\n url = \"http://\" + url\n return url\n\nurls = map(addHttp, links)\n\nthis is longer than using list comprehensions and the ternary operator, but IMHO it is more readable since the function name describes what it is doing, so the code is self-documenting. It is also easier to refactor e.g. if you decide to follow yu_sha's advice and not test explicitly for \"www\".\n"
] |
[
4,
1,
1,
0
] |
[] |
[] |
[
"list_comprehension",
"python"
] |
stackoverflow_0001831129_list_comprehension_python.txt
|
Q:
Performing operations on a NumPy arrray but masking values along the diagonal from these operations
as I can perform operations on arrays so that does nothing on the diagonal
is calculated such that all but the diagonal
array ([[0., 1.37, 1., 1.37, 1., 1.37, 1.]
[1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1.37]
[1. , 1.37, 0. , 1.37, 2. , 2.37, 2. ]
[1.37, 1.73, 1.37, 0. , 1.37, 1.73, 2.37]
[1. , 2.37, 2. , 1.37, 0. , 1.37, 2. ]
[1.37, 1.73, 2.37, 1.73, 1.37, 0. , 1.37]
[1. , 1.37, 2. , 2.37, 2. , 1.37, 0. ]])
to avoid the NaN value, but retained the value zero on the diagonal in all responses
A:
I wonder if masked arrays might do what you want, e.g.,
import numpy as NP
A = NP.random.random_integers(0, 9, 16).reshape(4, 4)
dg = NP.r_[ [NP.nan] * 4 ] # proper syntax is 'nan' not 'NaN'
dg = NP.diag(dg)
A += dg # a 4x4 array w/ NaNs down the main diagonal
NP.sum(A, axis=1) # doesn't work, gives: array([ NaN, NaN, NaN, NaN])
from numpy import ma as MA
Am = **MA.masked_invalid**(A)
NP.sum(Am, axis=1) # now it works (treats 'nan' as 0)
The other way to do this of is, of course, to first convert the NaNs to 0s then
mask the 0s:
NP.nan_to_num(A)
MA.masked_equal(A, 0)
Finally, it's often efficient to mask and convert the NaNs in one step:
MA.fix_invalid(A)
Pretty straightforward, just keep in mind that 'ma' might not yet be in your namespace and also that these functions deal with 'NaNs' and 'infs', which is usually what you want.
A:
>>> arr = [
... [0., 1.37, 1., 1.37, 1., 1.37, 1.],
... [1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1.37],
... [1. , 1.37, 0. , 1.37, 2. , 2.37, 2. ],
... [1.37, 1.73, 1.37, 0. , 1.37, 1.73, 2.37],
... [1. , 2.37, 2. , 1.37, 0. , 1.37, 2. ],
... [1.37, 1.73, 2.37, 1.73, 1.37, 0. , 1.37],
... [1. , 1.37, 2. , 2.37, 2. , 1.37, 0. ]
... ]
>>> for i in range(6):
... for y in range(6):
... if (i <> y):
... print arr[i][y]*arr[y][i]
...
1.8769
1.0
1.8769
1.0
1.8769
1.8769
1.8769
2.9929
5.6169
2.9929
1.0
1.8769
1.8769
4.0
5.6169
1.8769
2.9929
1.8769
1.8769
2.9929
1.0
5.6169
4.0
1.8769
1.8769
1.8769
2.9929
5.6169
2.9929
1.8769
Depends on what you need to calculate
A:
Do your calculation as normal and then
myarray[arange(len(array)), arange(len(array))] = 0.
A:
Can you just do the calculation as normal, then afterwards set the diagonal back to zero?
|
Performing operations on a NumPy arrray but masking values along the diagonal from these operations
|
as I can perform operations on arrays so that does nothing on the diagonal
is calculated such that all but the diagonal
array ([[0., 1.37, 1., 1.37, 1., 1.37, 1.]
[1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1.37]
[1. , 1.37, 0. , 1.37, 2. , 2.37, 2. ]
[1.37, 1.73, 1.37, 0. , 1.37, 1.73, 2.37]
[1. , 2.37, 2. , 1.37, 0. , 1.37, 2. ]
[1.37, 1.73, 2.37, 1.73, 1.37, 0. , 1.37]
[1. , 1.37, 2. , 2.37, 2. , 1.37, 0. ]])
to avoid the NaN value, but retained the value zero on the diagonal in all responses
|
[
"I wonder if masked arrays might do what you want, e.g.,\nimport numpy as NP\nA = NP.random.random_integers(0, 9, 16).reshape(4, 4)\ndg = NP.r_[ [NP.nan] * 4 ] # proper syntax is 'nan' not 'NaN'\ndg = NP.diag(dg)\nA += dg # a 4x4 array w/ NaNs down the main diagonal\nNP.sum(A, axis=1) # doesn't work, gives: array([ NaN, NaN, NaN, NaN]) \nfrom numpy import ma as MA\nAm = **MA.masked_invalid**(A)\nNP.sum(Am, axis=1) # now it works (treats 'nan' as 0)\n\nThe other way to do this of is, of course, to first convert the NaNs to 0s then\nmask the 0s:\nNP.nan_to_num(A)\nMA.masked_equal(A, 0)\n\nFinally, it's often efficient to mask and convert the NaNs in one step:\nMA.fix_invalid(A)\n\nPretty straightforward, just keep in mind that 'ma' might not yet be in your namespace and also that these functions deal with 'NaNs' and 'infs', which is usually what you want.\n",
">>> arr = [\n... [0., 1.37, 1., 1.37, 1., 1.37, 1.],\n... [1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1.37],\n... [1. , 1.37, 0. , 1.37, 2. , 2.37, 2. ],\n... [1.37, 1.73, 1.37, 0. , 1.37, 1.73, 2.37],\n... [1. , 2.37, 2. , 1.37, 0. , 1.37, 2. ],\n... [1.37, 1.73, 2.37, 1.73, 1.37, 0. , 1.37],\n... [1. , 1.37, 2. , 2.37, 2. , 1.37, 0. ]\n... ]\n>>> for i in range(6):\n... for y in range(6):\n... if (i <> y):\n... print arr[i][y]*arr[y][i]\n...\n1.8769\n1.0\n1.8769\n1.0\n1.8769\n1.8769\n1.8769\n2.9929\n5.6169\n2.9929\n1.0\n1.8769\n1.8769\n4.0\n5.6169\n1.8769\n2.9929\n1.8769\n1.8769\n2.9929\n1.0\n5.6169\n4.0\n1.8769\n1.8769\n1.8769\n2.9929\n5.6169\n2.9929\n1.8769\n\nDepends on what you need to calculate\n",
"Do your calculation as normal and then\nmyarray[arange(len(array)), arange(len(array))] = 0.\n\n",
"Can you just do the calculation as normal, then afterwards set the diagonal back to zero?\n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"arrays",
"numpy",
"python",
"scipy"
] |
stackoverflow_0001803860_arrays_numpy_python_scipy.txt
|
Q:
Review my Django Model - Need lots of suggestions
I am pulling a variety of information sources to build up a profile of a person. Once I do this I want to the flexibility to look at a person in a different ways. I don't have a lot of expierience in django so I would like a critique (be gentle) of my model. Admittedly even as I coded this I'm thinking redundancy (against DRY) but I would like to know what others think. FWIW - this data was pulled not created - so maybe I shouldn't keep it all but dropping data seems bad..
Specifically I want to know if the use of ManyToMany is appropriate or would you just KISS and leave each entry as it's own without any ManyToMany business. Long term I think KISS would make updating it simple (a basic for loop) but is there a tradeoff with being able to query a person (say based on location_description or job_function). Anyway I would appreciate some input.
class Person(models.Model):
"""This simply builds a notes user"""
aliases = models.ManyToManyField(Aliases) #Hmm this is list..
assistant = models.CharField(max_length = 255, blank = True)
cell_phone = models.CharField(max_lenth = 16, blank = True)
city = models.ManyToManyField(City)
country = models.ManyToManyField(County)
department = models.ManyToManyField(Department)
departmeht_number = models.ManyToManyField(Department_Number)
division_code = models.ManyToManyField(Division_Code)
email = models.EmailField(max_length = 50)
functional_area = models.ManyToManyField(Functional_Area)
# jpeg = models.
job_classification = models.ManyToManyField(Job_Classification)
job_classification_code = models.ManyToManyField(Job_Classification_Code)
last_name = models.CharField(max_length = 255)
location_description = models.ManyToManyField(Location_Description)
location_path = models.ManyToManyField(Location_Path)
mail_address = models.CharField(max_length = 255, blank = True)
mail_domain = models.ManyToManyField(Mail_Domain)
mail_file = models.CharField(max_length = 255, blank = True)
mail_server = models.ManyToManyField(Mail_Server)
match_pct = models.CharField(max_lenth = 6)
name = models.CharField(max_length = 255)
name_reverse = models.CharField(max_length = 255)
nickname = models.CharField(max_length = 32)
notes_url = models.URLField()
# object_class = models.
office_phone = models.CharField(max_length = 255, blank = True)
other_phone = models.CharField(max_length = 255, blank = True)
position = models.ManyToManyField(Position)
section = models.ManyToManyField(Section)
section_code = models.ManyToManyField(SectionCode)
shift = models.ManyToManyField(Shift)
state = models.ManyToManyFiedl(State)
supervisor = models.ManyToManyField(Supervisor)
supervisor_reverse = models.ManyToManyField(Supervisor_reverse)
uid = models.CharField(max_length = 128)
def __unicode__(self):
return str(self.name)
A:
__unicode__ should return unicode
def __unicode__(self):
return u'%s' %self.name
Django provides a emailfield for complete adresses:
mail = models.EmailField()
I think, a address model might be sense-full. A person could have several addresses (work, home,...)
edit
I just saw, you are using emailfield.
What is this for:
mail_address = models.CharField(max_length = 255, blank = True)
mail_domain = models.ManyToManyField(Mail_Domain)
mail_file = models.CharField(max_length = 255, blank = True)
mail_server = models.ManyToManyField(Mail_Server)
?
edit
You dont have to use ManyToManyFields all the time. Check out ForeignKey, OneToOneField and the generic framework
A:
It seems to me that many of your ManyToMany relations should be replaced by properties of the target model.
For example, you've got city and country as separate relations. That means that you might end up with a user having city = ['Paris', 'London', 'New York'] and country = ['USA', 'France', 'UK'].
Instead I think you should set up a locations ManyToMany relation pointing to a model consisting of city and country properties.
Same with department and department_number, job_classification and job_classification_code, location_description and location_path, etc.
Edit: In some cases you might be able to use ForeignKey instead of ManyToMany. Perhaps a user can only belong to one city and country?
Position and supervisor will likely be some of the trickier relations, because position should point to a department/unit and is_supervisor should likely be a property of a position. That is, you only need to point to a position as the supervisor(s) would be retrieved from other users' positions.
Edit: Example: If person A works in dept X and person B also works in dept X, but as a manager, then person A is supervised by person B.
Edit: It can be tempting to assume that a department can only have one manager or that a manager can only manage one department. I would advice against this as organizations often have all kinds of special cases. Think about scenarios like when a manager leaves the company, will the department be without manager for a while or will another manager temporarily take over, thus keeping two manager positions.
A:
I'd make subordinate field and remove supervisor.
subordinates = models.ManyToManyField('self', related_name='supervisors', through=Position)
This way supervisors will be an automatic reverse lookup field and there will be a record of Position that connects supervisor with the subordinate
edit: actually I'd also suggest to carefully think of re-designing your models. Maybe you won't need as many as you suggest.
Looks like you have "department", "company" (if you need to track multiple companies), "position", "location" and "person"... Decide what big entities to keep, then think of where exactly each field belongs and how to link up the "big" objects that will translate to tables.
It will probably be best to make subordinate-supervisor relation between Position objects, because people come and go, but positon are more permanent. So I'd have:
class Position:
title = models.CharField() #product manager, engineer, etc.
employee = models.ForeignKey(Person, related_name='positions')
subordinates = models.ManyToManyField('self', related_name='supervisors')
of if you don't need multiple supervisors per position, use
supervisor = models.ForeignKey('self', related_name='subordinates')
Even though now there is not subordiantes field, it will be accessible as previously through related name.
Where does location belong?
If you decide that both Person and Department must have location, then you might think of Generic relations, which are albeit not as easy to work with as "regular ones", but you can also get away with adding "type" to location ('private/business') and then use either Location.company or Location.residence_owner and avoid using generic relations.
A:
Here's a few thoughts.
I think you should create separate models for department and job_classification and so on. For example
class department(models.Model):
name = Models.CharField(max_length=100)
number = Models.IntegerField
and then have a ManyToManyField to the department. Otherwise, if you have a person with department = ['HR', 'Finance'] and department_number = [12, 5], I don't think there's any way to tell which department number represents which department.
I would find the model easier to read if the fields were grouped by what they describe, rather than ordered alphabetically. E.G I think name, nickname, last_name should be defined together.
Finally, perhaps Alias should be a seperate model, with a ForeignKey to Person, since only one person should have any particular alias.
A:
I would also suggest that you use a separate model for employment. Use a foreign key back to your Person object. You can add as many records to that table as necessary.
Same suggestion goes for the mail_* fields as well.
|
Review my Django Model - Need lots of suggestions
|
I am pulling a variety of information sources to build up a profile of a person. Once I do this I want to the flexibility to look at a person in a different ways. I don't have a lot of expierience in django so I would like a critique (be gentle) of my model. Admittedly even as I coded this I'm thinking redundancy (against DRY) but I would like to know what others think. FWIW - this data was pulled not created - so maybe I shouldn't keep it all but dropping data seems bad..
Specifically I want to know if the use of ManyToMany is appropriate or would you just KISS and leave each entry as it's own without any ManyToMany business. Long term I think KISS would make updating it simple (a basic for loop) but is there a tradeoff with being able to query a person (say based on location_description or job_function). Anyway I would appreciate some input.
class Person(models.Model):
"""This simply builds a notes user"""
aliases = models.ManyToManyField(Aliases) #Hmm this is list..
assistant = models.CharField(max_length = 255, blank = True)
cell_phone = models.CharField(max_lenth = 16, blank = True)
city = models.ManyToManyField(City)
country = models.ManyToManyField(County)
department = models.ManyToManyField(Department)
departmeht_number = models.ManyToManyField(Department_Number)
division_code = models.ManyToManyField(Division_Code)
email = models.EmailField(max_length = 50)
functional_area = models.ManyToManyField(Functional_Area)
# jpeg = models.
job_classification = models.ManyToManyField(Job_Classification)
job_classification_code = models.ManyToManyField(Job_Classification_Code)
last_name = models.CharField(max_length = 255)
location_description = models.ManyToManyField(Location_Description)
location_path = models.ManyToManyField(Location_Path)
mail_address = models.CharField(max_length = 255, blank = True)
mail_domain = models.ManyToManyField(Mail_Domain)
mail_file = models.CharField(max_length = 255, blank = True)
mail_server = models.ManyToManyField(Mail_Server)
match_pct = models.CharField(max_lenth = 6)
name = models.CharField(max_length = 255)
name_reverse = models.CharField(max_length = 255)
nickname = models.CharField(max_length = 32)
notes_url = models.URLField()
# object_class = models.
office_phone = models.CharField(max_length = 255, blank = True)
other_phone = models.CharField(max_length = 255, blank = True)
position = models.ManyToManyField(Position)
section = models.ManyToManyField(Section)
section_code = models.ManyToManyField(SectionCode)
shift = models.ManyToManyField(Shift)
state = models.ManyToManyFiedl(State)
supervisor = models.ManyToManyField(Supervisor)
supervisor_reverse = models.ManyToManyField(Supervisor_reverse)
uid = models.CharField(max_length = 128)
def __unicode__(self):
return str(self.name)
|
[
"__unicode__ should return unicode\ndef __unicode__(self):\n return u'%s' %self.name\n\nDjango provides a emailfield for complete adresses:\nmail = models.EmailField()\n\nI think, a address model might be sense-full. A person could have several addresses (work, home,...)\nedit\nI just saw, you are using emailfield.\nWhat is this for:\nmail_address = models.CharField(max_length = 255, blank = True)\nmail_domain = models.ManyToManyField(Mail_Domain)\nmail_file = models.CharField(max_length = 255, blank = True)\nmail_server = models.ManyToManyField(Mail_Server)\n\n?\nedit\nYou dont have to use ManyToManyFields all the time. Check out ForeignKey, OneToOneField and the generic framework\n",
"It seems to me that many of your ManyToMany relations should be replaced by properties of the target model.\nFor example, you've got city and country as separate relations. That means that you might end up with a user having city = ['Paris', 'London', 'New York'] and country = ['USA', 'France', 'UK'].\nInstead I think you should set up a locations ManyToMany relation pointing to a model consisting of city and country properties.\nSame with department and department_number, job_classification and job_classification_code, location_description and location_path, etc.\nEdit: In some cases you might be able to use ForeignKey instead of ManyToMany. Perhaps a user can only belong to one city and country?\nPosition and supervisor will likely be some of the trickier relations, because position should point to a department/unit and is_supervisor should likely be a property of a position. That is, you only need to point to a position as the supervisor(s) would be retrieved from other users' positions. \nEdit: Example: If person A works in dept X and person B also works in dept X, but as a manager, then person A is supervised by person B.\nEdit: It can be tempting to assume that a department can only have one manager or that a manager can only manage one department. I would advice against this as organizations often have all kinds of special cases. Think about scenarios like when a manager leaves the company, will the department be without manager for a while or will another manager temporarily take over, thus keeping two manager positions.\n",
"I'd make subordinate field and remove supervisor.\n subordinates = models.ManyToManyField('self', related_name='supervisors', through=Position)\n\nThis way supervisors will be an automatic reverse lookup field and there will be a record of Position that connects supervisor with the subordinate\nedit: actually I'd also suggest to carefully think of re-designing your models. Maybe you won't need as many as you suggest.\nLooks like you have \"department\", \"company\" (if you need to track multiple companies), \"position\", \"location\" and \"person\"... Decide what big entities to keep, then think of where exactly each field belongs and how to link up the \"big\" objects that will translate to tables.\nIt will probably be best to make subordinate-supervisor relation between Position objects, because people come and go, but positon are more permanent. So I'd have:\nclass Position:\n title = models.CharField() #product manager, engineer, etc.\n employee = models.ForeignKey(Person, related_name='positions')\n subordinates = models.ManyToManyField('self', related_name='supervisors')\n\nof if you don't need multiple supervisors per position, use\n supervisor = models.ForeignKey('self', related_name='subordinates')\n\nEven though now there is not subordiantes field, it will be accessible as previously through related name.\nWhere does location belong?\nIf you decide that both Person and Department must have location, then you might think of Generic relations, which are albeit not as easy to work with as \"regular ones\", but you can also get away with adding \"type\" to location ('private/business') and then use either Location.company or Location.residence_owner and avoid using generic relations.\n",
"Here's a few thoughts.\nI think you should create separate models for department and job_classification and so on. For example\nclass department(models.Model):\n name = Models.CharField(max_length=100)\n number = Models.IntegerField\n\nand then have a ManyToManyField to the department. Otherwise, if you have a person with department = ['HR', 'Finance'] and department_number = [12, 5], I don't think there's any way to tell which department number represents which department.\nI would find the model easier to read if the fields were grouped by what they describe, rather than ordered alphabetically. E.G I think name, nickname, last_name should be defined together.\nFinally, perhaps Alias should be a seperate model, with a ForeignKey to Person, since only one person should have any particular alias.\n",
"I would also suggest that you use a separate model for employment. Use a foreign key back to your Person object. You can add as many records to that table as necessary. \nSame suggestion goes for the mail_* fields as well.\n"
] |
[
5,
4,
2,
2,
1
] |
[] |
[] |
[
"coding_style",
"django",
"django_models",
"python"
] |
stackoverflow_0001829489_coding_style_django_django_models_python.txt
|
Q:
python Encoding Problem?
I read from source.sql ( sql script ) file
INSERT INTO `Tbl_abc` VALUES (1111, 2222, 'CLEMENT', 'taya', 'MME', 'GΓ©rant', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 4688, 0, NULL, NULL, 'MAILLOT 01/02/09', 'MAILLOT 01/04/09', NULL, NULL);
And write to dest.sql With my list formated
I met the problem with encoding for example:
GΓ©rant= G\xc3\xa9rant
WHAT I AM TRYING
def DataMigration(dest, source, tbl_name, return_data=True):
'''
'''
data = []
for ln in codecs.open(source, 'r', "utf-8").xreadlines():
replace1 = ln.replace("INSERT INTO `"+tbl_name+"` VALUES (", "")
replace2 = replace1.replace(");", "")
list_replace = replace2.split(',')
s = list_replace
data.append(list_replace)
if return_data == True:
ouputdata = [d for d in data if d[1] == ' 0' and d[6]==' 0']
return ouputdata
if return_data == False:
return data
I print
print DataMigration('dest.sql', '.source.sql', 'Tbl_abc', False)
OUTPUT
[['1111', ' 2222', " 'CLEMENT'", " 'taya'", " 'MME'", " 'G\xc3\xa9rant'", ' NULL', ' NULL', ' NULL', ' NULL', ' NULL', ' NULL', ' NULL', ' 4688', ' 0', ' NULL', ' NULL', " 'MAILLOT 01/04/09'", " 'MAILLOT 01/04/09'", ' NULL', ' NULL']]
But My Ouput file still has the problem.Any Could help me ?
A:
Please use .encode("utf-8"), when you write to .sql file too.
open the file
fileObj = codecs.open( "someFile", "r", "utf-8" )
lets say you read it
data=fileOjb.read()
... do something on data
open("newfile","w").write(data.encode("utf-8"))
A:
Hi check encoding of your file .sql maybe it is not utf-8!
A:
Store your working data internally in Python as Unicode (use decode on read), and always write out using encode.
In your instance, you need to know the encoding of your database to know the correct output encoding.
|
python Encoding Problem?
|
I read from source.sql ( sql script ) file
INSERT INTO `Tbl_abc` VALUES (1111, 2222, 'CLEMENT', 'taya', 'MME', 'GΓ©rant', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 4688, 0, NULL, NULL, 'MAILLOT 01/02/09', 'MAILLOT 01/04/09', NULL, NULL);
And write to dest.sql With my list formated
I met the problem with encoding for example:
GΓ©rant= G\xc3\xa9rant
WHAT I AM TRYING
def DataMigration(dest, source, tbl_name, return_data=True):
'''
'''
data = []
for ln in codecs.open(source, 'r', "utf-8").xreadlines():
replace1 = ln.replace("INSERT INTO `"+tbl_name+"` VALUES (", "")
replace2 = replace1.replace(");", "")
list_replace = replace2.split(',')
s = list_replace
data.append(list_replace)
if return_data == True:
ouputdata = [d for d in data if d[1] == ' 0' and d[6]==' 0']
return ouputdata
if return_data == False:
return data
I print
print DataMigration('dest.sql', '.source.sql', 'Tbl_abc', False)
OUTPUT
[['1111', ' 2222', " 'CLEMENT'", " 'taya'", " 'MME'", " 'G\xc3\xa9rant'", ' NULL', ' NULL', ' NULL', ' NULL', ' NULL', ' NULL', ' NULL', ' 4688', ' 0', ' NULL', ' NULL', " 'MAILLOT 01/04/09'", " 'MAILLOT 01/04/09'", ' NULL', ' NULL']]
But My Ouput file still has the problem.Any Could help me ?
|
[
"Please use .encode(\"utf-8\"), when you write to .sql file too.\nopen the file\nfileObj = codecs.open( \"someFile\", \"r\", \"utf-8\" )\n\nlets say you read it \ndata=fileOjb.read()\n\n... do something on data\nopen(\"newfile\",\"w\").write(data.encode(\"utf-8\"))\n\n",
"Hi check encoding of your file .sql maybe it is not utf-8!\n",
"Store your working data internally in Python as Unicode (use decode on read), and always write out using encode.\nIn your instance, you need to know the encoding of your database to know the correct output encoding. \n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001831378_python.txt
|
Q:
Getting data from the database with python(on Django framework)
ordinarily if I were writing a sql statement to this I would do something like this,
SELECT * FROM (django_baseaccount LEFT JOIN django_account ON django_baseaccount.user_id = django_account.baseaccount_ptr_id)
LEFT JOIN django_address ON django_account.baseaccount_ptr_id = django_address.user_id;name
how do I put this into the Djagno way of querying the database using the API, i.e.
TradeDownloads.objects.filter(online=1)[:6]
My models
BASE ACCOUNT
class BaseAccount(models.Model):
user = models.ForeignKey(User, unique=True)
def __unicode__(self):
"""
Return the unicode representation of this customer, which is the user's
full name, if set, otherwise, the user's username
"""
fn = self.user.get_full_name()
if fn:
return fn
return self.user.username
def user_name(self):
"""
Returns the full name of the related user object
"""
return self.user.get_full_name()
def email(self):
"""
Return the email address of the related user object
"""
return self.user.email
ACCOUNT
class Account(BaseAccount):
"""
The account is an extension of the Django user and serves as the profile
object in user.get_profile() for shop purchases and sessions
"""
telephone = models.CharField(max_length=32)
default_address = models.ForeignKey(Address, related_name='billing_account', blank=True, null=True)
security_question = models.ForeignKey(SecurityQuestion)
security_answer = models.CharField(max_length=200)
how_heard = models.CharField("How did you hear about us?", max_length=100)
feedback = models.TextField(blank=True)
opt_in = models.BooleanField("Subscribe to mailing list", help_text="Please tick here if you would like to receive updates from %s" % Site.objects.get_current().name)
temporary = models.BooleanField()
def has_placed_orders(self):
"""
Returns True if the user has placed at least one order, False otherwise
"""
return self.order_set.count() > 0
def get_last_order(self):
"""
Returns the latest order that this customer has placed. If no orders
have been placed, then None is returned
"""
try:
return self.order_set.all().order_by('-date')[0]
except IndexError:
return None
def get_currency(self):
"""
Get the currency for this customer. If global currencies are enabled
(settings.ENABLE_GLOBAL_CURRENCIES) then this function will return
the currency related to their default address, otherwise, it returns
the site default
"""
if settings.ENABLE_GLOBAL_CURRENCIES:
return self.default_address.country.currency
return Currency.get_default_currency()
currency = property(get_currency)
def get_gateway_currency(self):
"""
Get the currency that an order will be put through protx with. If protx
currencies are enabled (settings.ENABLE_PROTX_CURRENCIES), then the
currency will be the same returned by get_currency, otherwise, the
site default is used
"""
if settings.ENABLE_PROTX_CURRENCIES and settings.ENABLE_GLOBAL_CURRENCIES:
return self.currency
return Currency.get_default_currency()
gateway_currency = property(get_gateway_currency)
ADDRESS
class Address(models.Model):
"""
This class encapsulates the data required for postage and payment mechanisms
across the site. Each address is associated with a single store account
"""
trade_user = models.BooleanField("Are you a stockist of N Products", help_text="Please here if you are a Stockist")
company_name = models.CharField(max_length=32, blank=True)
line1 = models.CharField(max_length=200)
line2 = models.CharField(max_length=200, blank=True)
line3 = models.CharField(max_length=200, blank=True)
city = models.CharField(max_length=32)
county = models.CharField(max_length=32)
postcode = models.CharField(max_length=12)
country = models.ForeignKey(Country)
account = models.ForeignKey('Account')
class Meta:
"""
Django meta options
verbose_name_plural = "Addresses"
"""
verbose_name_plural = "Addresses"
def __unicode__(self):
"""
The unicode representation of this address, the postcode plus the county
"""
return ', '.join((self.postcode, str(self.county)))
def line_list(self):
"""
Return a list of all of this objects address lines that are not blank,
in the natural order that you'd expect to see them. This is useful for
outputting to a template with the aid of python String.join()
"""
return [val for val in (self.line1, self.line2, self.line3, self.city, self.county, self.postcode, self.country.name) if val]
A:
"ordinarily if I were writing a sql statement"
Welcome to ORM. You're not writing SQL so remove this from the question. Do not ever post SQL and ask how to translate SQL into ORM. Translating SQL limits your ability to learn. Stop doing it.
Write down what the result is supposed to be.
It appears that you are getting all Account objects. Period.
At some point in a view function or template you want to get an Address, also.
for a in Account.objects.all():
a.default_address # this is the address that SQL brought in via a "join".
That's it. Please actually do all the examples in the Django tutorial. Actually type the code from the examples and see how it works.
All "join" operations are SQL workarounds. They're a weird SQL-ism, and have nothing to do with the underlying objects. So stop using SQL terminology to describe what you want.
A:
Django provides a clean way to fall-back to native SQL for complex queries see the official documentation: Performing raw SQL queries
A:
Forget the SQL. What do you want to achieve from this query? What do you want to do with the results?
You haven't posted your models. Do they have the foreign keys defined? Can you just do a simple query and use select_related() to get the joined objects?
Edited to add What was wrong with the answer given the previous time you asked this question?
Edited again but everyone has shown you how to get the item via the foreign key! Forget the id, you don't need it. If you have an Account object a, you just do a.default_address to get the actual Address object that is related. If that doesn't work, then you're not posting the right models, as that will definitely work with the models you have posted.
|
Getting data from the database with python(on Django framework)
|
ordinarily if I were writing a sql statement to this I would do something like this,
SELECT * FROM (django_baseaccount LEFT JOIN django_account ON django_baseaccount.user_id = django_account.baseaccount_ptr_id)
LEFT JOIN django_address ON django_account.baseaccount_ptr_id = django_address.user_id;name
how do I put this into the Djagno way of querying the database using the API, i.e.
TradeDownloads.objects.filter(online=1)[:6]
My models
BASE ACCOUNT
class BaseAccount(models.Model):
user = models.ForeignKey(User, unique=True)
def __unicode__(self):
"""
Return the unicode representation of this customer, which is the user's
full name, if set, otherwise, the user's username
"""
fn = self.user.get_full_name()
if fn:
return fn
return self.user.username
def user_name(self):
"""
Returns the full name of the related user object
"""
return self.user.get_full_name()
def email(self):
"""
Return the email address of the related user object
"""
return self.user.email
ACCOUNT
class Account(BaseAccount):
"""
The account is an extension of the Django user and serves as the profile
object in user.get_profile() for shop purchases and sessions
"""
telephone = models.CharField(max_length=32)
default_address = models.ForeignKey(Address, related_name='billing_account', blank=True, null=True)
security_question = models.ForeignKey(SecurityQuestion)
security_answer = models.CharField(max_length=200)
how_heard = models.CharField("How did you hear about us?", max_length=100)
feedback = models.TextField(blank=True)
opt_in = models.BooleanField("Subscribe to mailing list", help_text="Please tick here if you would like to receive updates from %s" % Site.objects.get_current().name)
temporary = models.BooleanField()
def has_placed_orders(self):
"""
Returns True if the user has placed at least one order, False otherwise
"""
return self.order_set.count() > 0
def get_last_order(self):
"""
Returns the latest order that this customer has placed. If no orders
have been placed, then None is returned
"""
try:
return self.order_set.all().order_by('-date')[0]
except IndexError:
return None
def get_currency(self):
"""
Get the currency for this customer. If global currencies are enabled
(settings.ENABLE_GLOBAL_CURRENCIES) then this function will return
the currency related to their default address, otherwise, it returns
the site default
"""
if settings.ENABLE_GLOBAL_CURRENCIES:
return self.default_address.country.currency
return Currency.get_default_currency()
currency = property(get_currency)
def get_gateway_currency(self):
"""
Get the currency that an order will be put through protx with. If protx
currencies are enabled (settings.ENABLE_PROTX_CURRENCIES), then the
currency will be the same returned by get_currency, otherwise, the
site default is used
"""
if settings.ENABLE_PROTX_CURRENCIES and settings.ENABLE_GLOBAL_CURRENCIES:
return self.currency
return Currency.get_default_currency()
gateway_currency = property(get_gateway_currency)
ADDRESS
class Address(models.Model):
"""
This class encapsulates the data required for postage and payment mechanisms
across the site. Each address is associated with a single store account
"""
trade_user = models.BooleanField("Are you a stockist of N Products", help_text="Please here if you are a Stockist")
company_name = models.CharField(max_length=32, blank=True)
line1 = models.CharField(max_length=200)
line2 = models.CharField(max_length=200, blank=True)
line3 = models.CharField(max_length=200, blank=True)
city = models.CharField(max_length=32)
county = models.CharField(max_length=32)
postcode = models.CharField(max_length=12)
country = models.ForeignKey(Country)
account = models.ForeignKey('Account')
class Meta:
"""
Django meta options
verbose_name_plural = "Addresses"
"""
verbose_name_plural = "Addresses"
def __unicode__(self):
"""
The unicode representation of this address, the postcode plus the county
"""
return ', '.join((self.postcode, str(self.county)))
def line_list(self):
"""
Return a list of all of this objects address lines that are not blank,
in the natural order that you'd expect to see them. This is useful for
outputting to a template with the aid of python String.join()
"""
return [val for val in (self.line1, self.line2, self.line3, self.city, self.county, self.postcode, self.country.name) if val]
|
[
"\"ordinarily if I were writing a sql statement\"\nWelcome to ORM. You're not writing SQL so remove this from the question. Do not ever post SQL and ask how to translate SQL into ORM. Translating SQL limits your ability to learn. Stop doing it.\nWrite down what the result is supposed to be.\nIt appears that you are getting all Account objects. Period.\nAt some point in a view function or template you want to get an Address, also. \nfor a in Account.objects.all():\n a.default_address # this is the address that SQL brought in via a \"join\".\n\nThat's it. Please actually do all the examples in the Django tutorial. Actually type the code from the examples and see how it works.\nAll \"join\" operations are SQL workarounds. They're a weird SQL-ism, and have nothing to do with the underlying objects. So stop using SQL terminology to describe what you want.\n",
"Django provides a clean way to fall-back to native SQL for complex queries see the official documentation: Performing raw SQL queries\n",
"Forget the SQL. What do you want to achieve from this query? What do you want to do with the results? \nYou haven't posted your models. Do they have the foreign keys defined? Can you just do a simple query and use select_related() to get the joined objects?\nEdited to add What was wrong with the answer given the previous time you asked this question?\nEdited again but everyone has shown you how to get the item via the foreign key! Forget the id, you don't need it. If you have an Account object a, you just do a.default_address to get the actual Address object that is related. If that doesn't work, then you're not posting the right models, as that will definitely work with the models you have posted.\n"
] |
[
8,
2,
2
] |
[] |
[] |
[
"django",
"mysql",
"python",
"sql"
] |
stackoverflow_0001831980_django_mysql_python_sql.txt
|
Q:
Python 3: Best string compression method to minimize the size of a sqlite3 db
I recently created a script that parses several web proxy logs into a tidy sqlite3 db file that is working great for me... with one snag. the file size. I have been pressed to use this format (a sqlite3 db) and python handles it natively like a champ, so my question is this... what is the best form of string compression that I can use for db entries when file size is the sole concern. zlib? base-n? Klingon?
Any advice would help me loads, again just string compression for characters that are compliant for URLs.
A:
Here is a page with an SQLite extension to provide compression.
This extension provides a function that can be called on individual fields.
Here is some of the example text from the page
create a test table
sqlite> create table test(name varchar(20),surname varchar(20));
insert into test table some text by compressing text, you can also compress binary
content and insert it into a blob field
sqlite> insert into test values(mycompress('This is a sample text'),mycompress('This is a
sample text'));
this shows nothing because our data is in binary format and compressed
sqlite> select * from test;
following works, it uncompresses the data
sqlite> select myuncompress(name),myuncompress(surname) from test;
A:
what sort of parsing do you do before you put it in the database? I get the impression that it is fairly simple with a single table holding each entry - if not then my apologies.
Compression is all about removing duplication, and in a log file most of the duplication is between entries rather than within each entry so compressing each entry individually is not going to be a huge win.
This is off the top of my head so feel free to shoot it down in flames, but I would consider breaking the table into a set of smaller tables holding the individual parts of the entry. A log entry would then mostly consist of a timestamp (as DATE type rather than a string) plus a set of indexes into other tables (e.g. requesting IP, request type, requested URL, browser type etc.)
This would have a trade-off of course, since it would make the database a lot more complex to maintain, but on the other hand it would enable meaningful queries such as "show me all the unique IPs that requested page X in the last week".
A:
Instead of inserting compression/decompression code into your program, you could store the table itself on a compressed drive.
|
Python 3: Best string compression method to minimize the size of a sqlite3 db
|
I recently created a script that parses several web proxy logs into a tidy sqlite3 db file that is working great for me... with one snag. the file size. I have been pressed to use this format (a sqlite3 db) and python handles it natively like a champ, so my question is this... what is the best form of string compression that I can use for db entries when file size is the sole concern. zlib? base-n? Klingon?
Any advice would help me loads, again just string compression for characters that are compliant for URLs.
|
[
"Here is a page with an SQLite extension to provide compression.\nThis extension provides a function that can be called on individual fields.\nHere is some of the example text from the page \n\ncreate a test table \nsqlite> create table test(name varchar(20),surname varchar(20)); \ninsert into test table some text by compressing text, you can also compress binary\n content and insert it into a blob field\nsqlite> insert into test values(mycompress('This is a sample text'),mycompress('This is a\n sample text')); \nthis shows nothing because our data is in binary format and compressed\nsqlite> select * from test;\nfollowing works, it uncompresses the data\nsqlite> select myuncompress(name),myuncompress(surname) from test;\n\n",
"what sort of parsing do you do before you put it in the database? I get the impression that it is fairly simple with a single table holding each entry - if not then my apologies. \nCompression is all about removing duplication, and in a log file most of the duplication is between entries rather than within each entry so compressing each entry individually is not going to be a huge win.\nThis is off the top of my head so feel free to shoot it down in flames, but I would consider breaking the table into a set of smaller tables holding the individual parts of the entry. A log entry would then mostly consist of a timestamp (as DATE type rather than a string) plus a set of indexes into other tables (e.g. requesting IP, request type, requested URL, browser type etc.)\nThis would have a trade-off of course, since it would make the database a lot more complex to maintain, but on the other hand it would enable meaningful queries such as \"show me all the unique IPs that requested page X in the last week\".\n",
"Instead of inserting compression/decompression code into your program, you could store the table itself on a compressed drive.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"compression",
"python",
"sqlite"
] |
stackoverflow_0001829256_compression_python_sqlite.txt
|
Q:
Python SOAP client library using a HTTPS connection with keys
I want to query a SOAP service that requires the use of keys.
I could write a SOAP client myself making use of httplib's HTTPSConnection, I'm pretty sure that would work, but it means I have to write a load of XML. Is there a nicer way to do this? Perhaps getting an existing SOAP library to use a HTTPSConnection object.
I found an example from 2001 based on an old version of SOAPpy (not SOAPy) but I think the SOAPpy library has changed since then.
A:
See twisted.web.xmlrpc.Proxy. The url argument knows about HTTPS:
url - The URL to which to post method calls. Calls will be made over SSL if the scheme is HTTPS.
This twisted doc page claims
From the point of view of a Twisted developer, there is little difference between XML-RPC support and SOAP support.
Following the example there, it should not be difficult to make SOAP HTTPS calls. Note that twisted tends to be different from other Python networking frameworks, and has a significant learning curve.
For PKI HTTPS support, see validate-ssl-certificates-with-python. It looks like there are some limitations, hopefully the Twisted API will cater to your needs.
|
Python SOAP client library using a HTTPS connection with keys
|
I want to query a SOAP service that requires the use of keys.
I could write a SOAP client myself making use of httplib's HTTPSConnection, I'm pretty sure that would work, but it means I have to write a load of XML. Is there a nicer way to do this? Perhaps getting an existing SOAP library to use a HTTPSConnection object.
I found an example from 2001 based on an old version of SOAPpy (not SOAPy) but I think the SOAPpy library has changed since then.
|
[
"See twisted.web.xmlrpc.Proxy. The url argument knows about HTTPS:\n\nurl - The URL to which to post method calls. Calls will be made over SSL if the scheme is HTTPS.\n\nThis twisted doc page claims \n\nFrom the point of view of a Twisted developer, there is little difference between XML-RPC support and SOAP support.\n\nFollowing the example there, it should not be difficult to make SOAP HTTPS calls. Note that twisted tends to be different from other Python networking frameworks, and has a significant learning curve.\nFor PKI HTTPS support, see validate-ssl-certificates-with-python. It looks like there are some limitations, hopefully the Twisted API will cater to your needs.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"soap"
] |
stackoverflow_0001832433_python_soap.txt
|
Q:
What does Python's builtin __build_class__ do?
In Python 3.1, there is a new builtin function I don't know in the builtins module:
__build_class__(...)
__build_class__(func, name, *bases, metaclass=None, **kwds) -> class
Internal helper function used by the class statement.
What does this function do? Why must it be in builtins if it's internal? What is the difference to the type(name, bases, dict) function?
A:
Compiling the PEP 3115 metaclass
Guido van Rossum said:
The PEP proposes that the class
statement accepts keyword arguments,
*args, and **kwds syntax as well as positional bases. This is a bit messy
to compile and execute, but we already
have this, of course, in the code for
calling regular functions.
So I think it would be acceptable to
this into a call to a new (hidden)
built-in function, named
__build_class__. Then that this class definition:
class C(A, B, metaclass=M, other=42, *more_bases, *more_kwds):
...
would translate into this:
C = __build_class__(<func>, 'C', A, B, metaclass=M, other=42,
*more_bases, *more_kwds)
where <func> is a function object for
the class body.
|
What does Python's builtin __build_class__ do?
|
In Python 3.1, there is a new builtin function I don't know in the builtins module:
__build_class__(...)
__build_class__(func, name, *bases, metaclass=None, **kwds) -> class
Internal helper function used by the class statement.
What does this function do? Why must it be in builtins if it's internal? What is the difference to the type(name, bases, dict) function?
|
[
"Compiling the PEP 3115 metaclass\nGuido van Rossum said:\n\nThe PEP proposes that the class\n statement accepts keyword arguments,\n *args, and **kwds syntax as well as positional bases. This is a bit messy\n to compile and execute, but we already\n have this, of course, in the code for\n calling regular functions.\nSo I think it would be acceptable to\n this into a call to a new (hidden)\n built-in function, named\n __build_class__. Then that this class definition:\n class C(A, B, metaclass=M, other=42, *more_bases, *more_kwds):\n ...\n\nwould translate into this:\n C = __build_class__(<func>, 'C', A, B, metaclass=M, other=42,\n*more_bases, *more_kwds)\n\nwhere <func> is a function object for\n the class body.\n\n"
] |
[
32
] |
[] |
[] |
[
"metaclass",
"python",
"python_3.x"
] |
stackoverflow_0001832997_metaclass_python_python_3.x.txt
|
Q:
How to refer to the local module in Python?
Let's say we have a module m:
var = None
def get_var():
return var
def set_var(v):
var = v
This will not work as expected, because set_var() will not store v in the module-wide var. It will create a local variable var instead.
So I need a way of referring the module m from within set_var(), which itself is a member of module m. How should I do this?
A:
def set_var(v):
global var
var = v
The global keyword will allow you to change global variables from within in a function.
A:
As Jeffrey Aylesworth's answer shows, you don't actually need a reference to the local module to achieve the OP's aim. The global keyword can achieve this aim.
However for the sake of answering the OP title, How to refer to the local module in Python?:
import sys
var = None
def set_var(v):
sys.modules[__name__].var = v
def get_var():
return var
A:
As a follow up to Jeffrey's answer, I would like to add that, in Python 3, you can more generally access a variable from the closest enclosing scope:
def set_local_var():
var = None
def set_var(v):
nonlocal var
var = v
return (var, set_var)
# Test:
(my_var, my_set) = set_local_var()
print my_var # None
my_set(3)
print my_var # Should now be 3
(Caveat: I have not tested this, as I don't have Python 3.)
|
How to refer to the local module in Python?
|
Let's say we have a module m:
var = None
def get_var():
return var
def set_var(v):
var = v
This will not work as expected, because set_var() will not store v in the module-wide var. It will create a local variable var instead.
So I need a way of referring the module m from within set_var(), which itself is a member of module m. How should I do this?
|
[
"def set_var(v):\n global var\n var = v\n\nThe global keyword will allow you to change global variables from within in a function.\n",
"As Jeffrey Aylesworth's answer shows, you don't actually need a reference to the local module to achieve the OP's aim. The global keyword can achieve this aim.\nHowever for the sake of answering the OP title, How to refer to the local module in Python?:\nimport sys\n\nvar = None\n\ndef set_var(v):\n sys.modules[__name__].var = v\n\ndef get_var():\n return var\n\n",
"As a follow up to Jeffrey's answer, I would like to add that, in Python 3, you can more generally access a variable from the closest enclosing scope:\ndef set_local_var():\n\n var = None\n\n def set_var(v):\n nonlocal var \n var = v\n\n return (var, set_var)\n\n# Test:\n(my_var, my_set) = set_local_var()\nprint my_var # None\nmy_set(3)\nprint my_var # Should now be 3\n\n(Caveat: I have not tested this, as I don't have Python 3.)\n"
] |
[
10,
9,
3
] |
[] |
[] |
[
"import",
"module",
"package",
"python"
] |
stackoverflow_0001832626_import_module_package_python.txt
|
Q:
Why _mysql.co that compiled on one Mac doesn't work on another?
I want to use Python-MySQLDB library on Mac so I have compiled the source code to get the _mysql.so under Mac10.5 with my Intel iMac (i386)
This _mysql.co works in 2 of my iMacs and another Macbook. But that's it, it doesn't work in any other Macs.
Does this mean some machine specific info got compiled into the file?
A:
If you've only built one architecture (i386 / PPC) then it won't work on Macs with the opposite architecture. Are the machines that don't work PPC machines, by any chance?
Sometimes build configurations are set up to build only the current architecture by default - I haven't build Python-MySQLDB so I'm not sure if this is the case here, but it's worth checking.
You can find out which architectures have been built with the 'file' command in Terminal.
(Incidentally do you mean ".so"? I'm not familiar with ".co" files.)
A:
Perform a file check against the _mysql.so file:
% file _mysql.so
_mysql.so: Mach-O 64-bit bundle x86_64
Make sure that it is compiled for the right architecture on the Macs on which it is not working. If you are trying to use it on any PowerPC (PPC) Macs, you will need to re-compile MySQLDB as a Universal binary.
For example, a Universal binary (such as the pre-installed version of Python) would look like this:
% file /usr/bin/python
/usr/bin/python: Mach-O universal binary with 3 architectures
/usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64
/usr/bin/python (for architecture i386): Mach-O executable i386
/usr/bin/python (for architecture ppc7400): Mach-O executable ppc
So to answer your question: Yes, it seems like you might have compiled the module without Universal support, however I can't answer this definitively without more information.
|
Why _mysql.co that compiled on one Mac doesn't work on another?
|
I want to use Python-MySQLDB library on Mac so I have compiled the source code to get the _mysql.so under Mac10.5 with my Intel iMac (i386)
This _mysql.co works in 2 of my iMacs and another Macbook. But that's it, it doesn't work in any other Macs.
Does this mean some machine specific info got compiled into the file?
|
[
"If you've only built one architecture (i386 / PPC) then it won't work on Macs with the opposite architecture. Are the machines that don't work PPC machines, by any chance?\nSometimes build configurations are set up to build only the current architecture by default - I haven't build Python-MySQLDB so I'm not sure if this is the case here, but it's worth checking.\nYou can find out which architectures have been built with the 'file' command in Terminal.\n(Incidentally do you mean \".so\"? I'm not familiar with \".co\" files.)\n",
"Perform a file check against the _mysql.so file:\n% file _mysql.so\n_mysql.so: Mach-O 64-bit bundle x86_64\n\nMake sure that it is compiled for the right architecture on the Macs on which it is not working. If you are trying to use it on any PowerPC (PPC) Macs, you will need to re-compile MySQLDB as a Universal binary.\nFor example, a Universal binary (such as the pre-installed version of Python) would look like this:\n% file /usr/bin/python\n/usr/bin/python: Mach-O universal binary with 3 architectures\n/usr/bin/python (for architecture x86_64): Mach-O 64-bit executable x86_64\n/usr/bin/python (for architecture i386): Mach-O executable i386\n/usr/bin/python (for architecture ppc7400): Mach-O executable ppc\n\nSo to answer your question: Yes, it seems like you might have compiled the module without Universal support, however I can't answer this definitively without more information. \n"
] |
[
2,
1
] |
[] |
[] |
[
"compilation",
"mysql",
"python"
] |
stackoverflow_0001831979_compilation_mysql_python.txt
|
Q:
how can I save a form with ModelMultipleChoiceField?
I have a model Calendar and in a form I want to be able to create multiple instances of it.
Here are my models:
class Event(models.Model):
user = models.ForeignKey(User)
class Group(models.Model):
name = models.CharField(_('Name'), max_length=80)
events = models.ManyToManyField(Event, through='Calendar')
class Calendar(models.Model):
event = models.ForeignKey(Event)
group = models.ForeignKey(Group)
class CalendarInline(admin.TabularInline):
model = Calendar
extra = 1
class GroupAdmin(admin.ModelAdmin):
inlines = (CalendarInline,)
Here is how I try to code my form:
class AddEventToGroupForm(ModelForm):
group = ModelMultipleChoiceField(queryset=Group.objects.all(), widget=SelectMultiple())
def save(self):
for g in self:
g.save()
class Meta:
model = Calendar
fields = ('group',)
And here is a part of my view:
e = Event.objects.get(id=event_id)
calentry = Calendar(event=e)
if request.POST:
f = AddEventToGroupForm(data=request.POST, instance=calentry)
if f.is_valid():
f.save()
If I try to submit that form, I get:
AttributeError at /groups/add_event/7/
'BoundField' object has no attribute 'save'
What is the proper way to create multiple instances of Calendar in this
situation?
A:
That's not how to deal with many-to-many relationships in forms. You can't iterate through fields in a form and save them, it really doesn't work that way.
In this form, there's only one field, which happens to have multiple values. The thing to do here is to iterate through the values of this field, which you'll find in the cleaned_data dictionary (when the form is valid).
So, in your view, you do something like:
if f.is_valid():
for group in f.cleaned_data['group']:
calentry.groups.add(group)
Note you're not 'saving' the AddEventToGroupForm form at all. I would make it a standard forms.Form, rather than a ModelForm, as you're not really depending on any of the ModelForm functionality.
|
how can I save a form with ModelMultipleChoiceField?
|
I have a model Calendar and in a form I want to be able to create multiple instances of it.
Here are my models:
class Event(models.Model):
user = models.ForeignKey(User)
class Group(models.Model):
name = models.CharField(_('Name'), max_length=80)
events = models.ManyToManyField(Event, through='Calendar')
class Calendar(models.Model):
event = models.ForeignKey(Event)
group = models.ForeignKey(Group)
class CalendarInline(admin.TabularInline):
model = Calendar
extra = 1
class GroupAdmin(admin.ModelAdmin):
inlines = (CalendarInline,)
Here is how I try to code my form:
class AddEventToGroupForm(ModelForm):
group = ModelMultipleChoiceField(queryset=Group.objects.all(), widget=SelectMultiple())
def save(self):
for g in self:
g.save()
class Meta:
model = Calendar
fields = ('group',)
And here is a part of my view:
e = Event.objects.get(id=event_id)
calentry = Calendar(event=e)
if request.POST:
f = AddEventToGroupForm(data=request.POST, instance=calentry)
if f.is_valid():
f.save()
If I try to submit that form, I get:
AttributeError at /groups/add_event/7/
'BoundField' object has no attribute 'save'
What is the proper way to create multiple instances of Calendar in this
situation?
|
[
"That's not how to deal with many-to-many relationships in forms. You can't iterate through fields in a form and save them, it really doesn't work that way.\nIn this form, there's only one field, which happens to have multiple values. The thing to do here is to iterate through the values of this field, which you'll find in the cleaned_data dictionary (when the form is valid).\nSo, in your view, you do something like:\nif f.is_valid():\n for group in f.cleaned_data['group']:\n calentry.groups.add(group)\n\nNote you're not 'saving' the AddEventToGroupForm form at all. I would make it a standard forms.Form, rather than a ModelForm, as you're not really depending on any of the ModelForm functionality.\n"
] |
[
2
] |
[] |
[] |
[
"django",
"django_forms",
"multiple_instances",
"python",
"save"
] |
stackoverflow_0001833275_django_django_forms_multiple_instances_python_save.txt
|
Q:
Javascript + python url-en/decoding problem
Hi there im kinda stucked with the url encoding between python and javascript, i hope you can help me out :S
Javascript:
encodeURIComponent('lΓ΄l');
-> "l%C3%B4l"
Python:
import urllib
test = container.REQUEST.form.get('test')
print test
print urllib.unquote(test)
-> "lΓΕ½l"
-> "lΓΕ½l"
Javascript encodes "lΓ΄l" twice however python does that once with it, i dunno how to escape from there because i receive anyway throgh the Prototype HTTP GET request "l%C3%B4l" instead of "l%F4l"
Best Regards
Bny
**edit
its on a zope webserver
A:
zope already url-decodes it - issue is that you're getting a utf-8 bytestring and printing it on a non-utf-8 terminal. Try decoding the string.
x = 'l\xc3\xb4l'
unicode_x = x.decode('utf-8')
print unicode_x
|
Javascript + python url-en/decoding problem
|
Hi there im kinda stucked with the url encoding between python and javascript, i hope you can help me out :S
Javascript:
encodeURIComponent('lΓ΄l');
-> "l%C3%B4l"
Python:
import urllib
test = container.REQUEST.form.get('test')
print test
print urllib.unquote(test)
-> "lΓΕ½l"
-> "lΓΕ½l"
Javascript encodes "lΓ΄l" twice however python does that once with it, i dunno how to escape from there because i receive anyway throgh the Prototype HTTP GET request "l%C3%B4l" instead of "l%F4l"
Best Regards
Bny
**edit
its on a zope webserver
|
[
"zope already url-decodes it - issue is that you're getting a utf-8 bytestring and printing it on a non-utf-8 terminal. Try decoding the string.\nx = 'l\\xc3\\xb4l'\nunicode_x = x.decode('utf-8')\nprint unicode_x\n\n"
] |
[
1
] |
[] |
[] |
[
"javascript",
"python",
"urlencode",
"zope"
] |
stackoverflow_0001833776_javascript_python_urlencode_zope.txt
|
Q:
Installing TortoiseHG on Gnome in Ubuntu 9.10?
I followed the following steps to install TortoiseHG on Ubuntu 9.10 using the following document:
http://bitbucket.org/tortoisehg/stable/wiki/nautilus
I get the following error in my ~/.xsession-errors
evolution-alarm-notify-Message: Tue Dec 1 23:28:26 2009
sys:1: GtkWarning: Refusing to add non-unique action 'HgNautilus::00None' to action group 'DirExtensionsMenuGroup'
sys:1: GtkWarning: gtk_action_get_name: assertion `GTK_IS_ACTION (action)' failed
sys:1: GtkWarning: gtk_ui_manager_add_ui: assertion `name != NULL || type == GTK_UI_MANAGER_SEPARATOR' failed
sys:1: GtkWarning: Refusing to add non-unique action 'HgNautilus::01clone' to action group 'DirExtensionsMenuGroup'
sys:1: GtkWarning: Refusing to add non-unique action 'HgNautilus::02init' to action group 'DirExtensionsMenuGroup'
sys:1: GtkWarning: Refusing to add non-unique action 'HgNautilus::03userconfig' to action group 'DirExtensionsMenuGroup'
sys:1: GtkWarning: Refusing to add non-unique action 'HgNautilus::05about' to action group 'DirExtensionsMenuGroup'
Traceback (most recent call last):
File "/usr/bin/hgtk", line 44, in <module>
sys.exit(hggtk.hgtk.dispatch(sys.argv[1:]))
File "/usr/lib/pymodules/python2.6/hggtk/hgtk.py", line 29, in dispatch
u = _ui.ui(traceback='--traceback' in args)
TypeError: __init__() got an unexpected keyword argument 'traceback'
Does anyone know how to make this work? Meanwhile I'll be using the command line. Thanks.
A:
It appears you are using Mercurial 1.2.1, which does not have the refactoring done in revision 6b5522cb2ad2. That means that you cannot use the latest version of TortoiseHg with such an old version of Mercurial.
I suggest updating Mercurial to a newer version or use an older version of TortoiseHg.
|
Installing TortoiseHG on Gnome in Ubuntu 9.10?
|
I followed the following steps to install TortoiseHG on Ubuntu 9.10 using the following document:
http://bitbucket.org/tortoisehg/stable/wiki/nautilus
I get the following error in my ~/.xsession-errors
evolution-alarm-notify-Message: Tue Dec 1 23:28:26 2009
sys:1: GtkWarning: Refusing to add non-unique action 'HgNautilus::00None' to action group 'DirExtensionsMenuGroup'
sys:1: GtkWarning: gtk_action_get_name: assertion `GTK_IS_ACTION (action)' failed
sys:1: GtkWarning: gtk_ui_manager_add_ui: assertion `name != NULL || type == GTK_UI_MANAGER_SEPARATOR' failed
sys:1: GtkWarning: Refusing to add non-unique action 'HgNautilus::01clone' to action group 'DirExtensionsMenuGroup'
sys:1: GtkWarning: Refusing to add non-unique action 'HgNautilus::02init' to action group 'DirExtensionsMenuGroup'
sys:1: GtkWarning: Refusing to add non-unique action 'HgNautilus::03userconfig' to action group 'DirExtensionsMenuGroup'
sys:1: GtkWarning: Refusing to add non-unique action 'HgNautilus::05about' to action group 'DirExtensionsMenuGroup'
Traceback (most recent call last):
File "/usr/bin/hgtk", line 44, in <module>
sys.exit(hggtk.hgtk.dispatch(sys.argv[1:]))
File "/usr/lib/pymodules/python2.6/hggtk/hgtk.py", line 29, in dispatch
u = _ui.ui(traceback='--traceback' in args)
TypeError: __init__() got an unexpected keyword argument 'traceback'
Does anyone know how to make this work? Meanwhile I'll be using the command line. Thanks.
|
[
"It appears you are using Mercurial 1.2.1, which does not have the refactoring done in revision 6b5522cb2ad2. That means that you cannot use the latest version of TortoiseHg with such an old version of Mercurial.\nI suggest updating Mercurial to a newer version or use an older version of TortoiseHg.\n"
] |
[
2
] |
[] |
[] |
[
"gnome",
"mercurial",
"python",
"tortoisehg",
"ubuntu"
] |
stackoverflow_0001830705_gnome_mercurial_python_tortoisehg_ubuntu.txt
|
Q:
Confirmation of Successful HTTP Download in Python
Is there a easy and reliable way to confirm that a web download completed successfully to download using Python or WGET [for large files]? I want to make sure the file downloaded in its entirety before performing another action.
A:
Given many (most in practice, I believe) HTTP/1.1 header sections, you can get an expectation about how long the entity body is. If you have that expectation, you can decide if you got all the entity data. See RFC 2616 section 4.4 for full details, but essentially:
sometimes the content-length accurately reflects the length of the entity body
sometimes there can be no entity body, depending on the response code or if the response is responding to a HEAD request
sometimes the request is transfer encoded; and there is some marker in the HTTP data which says 'I'm done now' (Transfer-Encoding: chunked)
and sometimes, the message is officially done when the connection closes (in which case, you cannot differentiate between getting the whole thing and being cut off early)
In all cases but the last one, you can tell if you've got the whole thing or not. I don't know if any tool in particular (wget or an existing python library) gives you an easily interpretable signal that your response was or wasn't truncated.
A:
HTTP doesn't provide a way to check that.
The way used when distributing large files is, after the download, calculate the md5sum of the file and compare it with the md5sum provided by the server.
Example, that's how ubuntu does to distribute and check their CD downloads. https://help.ubuntu.com/community/HowToMD5SUM
|
Confirmation of Successful HTTP Download in Python
|
Is there a easy and reliable way to confirm that a web download completed successfully to download using Python or WGET [for large files]? I want to make sure the file downloaded in its entirety before performing another action.
|
[
"Given many (most in practice, I believe) HTTP/1.1 header sections, you can get an expectation about how long the entity body is. If you have that expectation, you can decide if you got all the entity data. See RFC 2616 section 4.4 for full details, but essentially:\n\nsometimes the content-length accurately reflects the length of the entity body\nsometimes there can be no entity body, depending on the response code or if the response is responding to a HEAD request\nsometimes the request is transfer encoded; and there is some marker in the HTTP data which says 'I'm done now' (Transfer-Encoding: chunked)\nand sometimes, the message is officially done when the connection closes (in which case, you cannot differentiate between getting the whole thing and being cut off early)\n\nIn all cases but the last one, you can tell if you've got the whole thing or not. I don't know if any tool in particular (wget or an existing python library) gives you an easily interpretable signal that your response was or wasn't truncated.\n",
"HTTP doesn't provide a way to check that.\nThe way used when distributing large files is, after the download, calculate the md5sum of the file and compare it with the md5sum provided by the server.\nExample, that's how ubuntu does to distribute and check their CD downloads. https://help.ubuntu.com/community/HowToMD5SUM\n"
] |
[
3,
2
] |
[] |
[] |
[
"python",
"wget"
] |
stackoverflow_0001834004_python_wget.txt
|
Q:
Python check windows server version
I need to log the current windows version in my python application for reporting purposes, but the built in functions I've found so far cant tell the difference between Windows client and server versions:
os.sys.getwindowsversion()
(6, 0, 6002, 2, 'Service Pack 2')
platform.release()
'Vista'
platform.win32_ver()
('Vista', '6.0.6002', 'SP2', 'Multiprocessor Free')
These functions return the same values on Windows Vista and Windows Server 2008 (Since they share the same version number).
Is there any way to get the correct windows version?
A:
You could use the GetVersionEx Win32 API and check the value of wProductType to differentiate.
Check out the Python for Windows extension package.
VER_NT_DOMAIN_CONTROLLER 0x0000002
The system is a domain controller and
the operating system is Windows Server
2008, Windows Server 2003, or Windows
2000 Server.
VER_NT_SERVER 0x0000003
The operating system is Windows Server
2008, Windows Server 2003, or Windows
2000 Server.
Note that a server that is also a
domain controller is reported as
VER_NT_DOMAIN_CONTROLLER, not
VER_NT_SERVER.
VER_NT_WORKSTATION 0x0000001
The operating system is Windows Vista,
Windows XP Professional, Windows XP
Home Edition, or Windows 2000
Professional.
A:
Try fetching it using WMI Win32_OperatingSystem class (ProductType is 3 on server systems). Scriptomatic can generate Python code for that.
|
Python check windows server version
|
I need to log the current windows version in my python application for reporting purposes, but the built in functions I've found so far cant tell the difference between Windows client and server versions:
os.sys.getwindowsversion()
(6, 0, 6002, 2, 'Service Pack 2')
platform.release()
'Vista'
platform.win32_ver()
('Vista', '6.0.6002', 'SP2', 'Multiprocessor Free')
These functions return the same values on Windows Vista and Windows Server 2008 (Since they share the same version number).
Is there any way to get the correct windows version?
|
[
"You could use the GetVersionEx Win32 API and check the value of wProductType to differentiate.\nCheck out the Python for Windows extension package.\n\nVER_NT_DOMAIN_CONTROLLER 0x0000002\nThe system is a domain controller and\n the operating system is Windows Server\n 2008, Windows Server 2003, or Windows\n 2000 Server.\nVER_NT_SERVER 0x0000003\nThe operating system is Windows Server\n 2008, Windows Server 2003, or Windows\n 2000 Server.\nNote that a server that is also a\n domain controller is reported as\n VER_NT_DOMAIN_CONTROLLER, not\n VER_NT_SERVER.\nVER_NT_WORKSTATION 0x0000001\nThe operating system is Windows Vista,\n Windows XP Professional, Windows XP\n Home Edition, or Windows 2000\n Professional.\n\n",
"Try fetching it using WMI Win32_OperatingSystem class (ProductType is 3 on server systems). Scriptomatic can generate Python code for that. \n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"windows"
] |
stackoverflow_0001834446_python_windows.txt
|
Q:
Does a File Object Automatically Close when its Reference Count Hits Zero?
I was under the impression that file objects are immediately closed when their reference counts hit 0, hence the line:
foo = open('foo').read()
would get you the file's contents and immediately close the file. However, after reading the answer to Is close() necessary when using iterator on a Python file object I get the impression that this does not happen, and that calling .close() on a file object is always necessary.
Does the line above do what I think it's doing and even if it does, is it the Pythonic thing to do?
A:
The answer is in the link you provided.
Garbage collector will close file when it destroys file object, but:
you don't really have control over when it happens.
While CPython uses reference counting to deterministically release resources
(so you can predict when object will be destroyed) other versions don't have to.
For example both Jython or IronPython use JVM and .NET garbage collector which
release (and finalize) objects only when there is need to recover memory
and might not do that for some object until the end of the program.
And even for CPython GC algorithm may change in the future as reference counting
isn't very efficient.
if exception is thrown when closing file on file object destruction,
you can't really do anything about it because you won't know.
A:
If you want to be sure, I'd write the code like this:
from __future__ import with_statement
with open('foo') as f:
foo = f.read()
That way, your file closes as expected, even with exceptions.
Much later: here is some code with import dis to show how the compiler treats these differently.
>>> def foo(filename):
... with open(filename) as f:
... return f.read()
...
>>> def bar(filename):
... return open(filename).read()
...
>>> from dis import dis
>>>
>>> dis(foo)
2 0 LOAD_GLOBAL 0 (open)
3 LOAD_FAST 0 (filename)
6 CALL_FUNCTION 1
9 DUP_TOP
10 LOAD_ATTR 1 (__exit__)
13 ROT_TWO
14 LOAD_ATTR 2 (__enter__)
17 CALL_FUNCTION 0
20 STORE_FAST 1 (_[1])
23 SETUP_FINALLY 23 (to 49)
26 LOAD_FAST 1 (_[1])
29 DELETE_FAST 1 (_[1])
32 STORE_FAST 2 (f)
3 35 LOAD_FAST 2 (f)
38 LOAD_ATTR 3 (read)
41 CALL_FUNCTION 0
44 RETURN_VALUE
45 POP_BLOCK
46 LOAD_CONST 0 (None)
>> 49 WITH_CLEANUP
50 END_FINALLY
51 LOAD_CONST 0 (None)
54 RETURN_VALUE
>>> dis(bar)
2 0 LOAD_GLOBAL 0 (open)
3 LOAD_FAST 0 (filename)
6 CALL_FUNCTION 1
9 LOAD_ATTR 1 (read)
12 CALL_FUNCTION 0
15 RETURN_VALUE
A:
For the cpython implementation of python: yes, it is guaranteed to be closed when its reference count goes to zero.
For python as an abstract language (e.g., including Jython, IronPython, etc): no, it is not guaranteed to be closed. In particular, an implementation of Python may choose not to use reference counting, but to use some other form of GC.
References:
http://docs.python.org/c-api/typeobj.html#tp_dealloc
http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/
A:
No, Python optimize deleting unused objects so It may never close your file (OK at the end of your script at exit it will cleanup).
@ hughdbrown have pointed out nice solution.
|
Does a File Object Automatically Close when its Reference Count Hits Zero?
|
I was under the impression that file objects are immediately closed when their reference counts hit 0, hence the line:
foo = open('foo').read()
would get you the file's contents and immediately close the file. However, after reading the answer to Is close() necessary when using iterator on a Python file object I get the impression that this does not happen, and that calling .close() on a file object is always necessary.
Does the line above do what I think it's doing and even if it does, is it the Pythonic thing to do?
|
[
"The answer is in the link you provided.\nGarbage collector will close file when it destroys file object, but:\n\nyou don't really have control over when it happens.\nWhile CPython uses reference counting to deterministically release resources\n(so you can predict when object will be destroyed) other versions don't have to.\nFor example both Jython or IronPython use JVM and .NET garbage collector which\nrelease (and finalize) objects only when there is need to recover memory\nand might not do that for some object until the end of the program.\nAnd even for CPython GC algorithm may change in the future as reference counting\nisn't very efficient.\nif exception is thrown when closing file on file object destruction,\nyou can't really do anything about it because you won't know.\n\n",
"If you want to be sure, I'd write the code like this:\nfrom __future__ import with_statement\n\nwith open('foo') as f:\n foo = f.read()\n\nThat way, your file closes as expected, even with exceptions.\n\nMuch later: here is some code with import dis to show how the compiler treats these differently.\n>>> def foo(filename):\n... with open(filename) as f:\n... return f.read()\n... \n>>> def bar(filename):\n... return open(filename).read()\n... \n>>> from dis import dis\n>>> \n>>> dis(foo)\n 2 0 LOAD_GLOBAL 0 (open)\n 3 LOAD_FAST 0 (filename)\n 6 CALL_FUNCTION 1\n 9 DUP_TOP \n 10 LOAD_ATTR 1 (__exit__)\n 13 ROT_TWO \n 14 LOAD_ATTR 2 (__enter__)\n 17 CALL_FUNCTION 0\n 20 STORE_FAST 1 (_[1])\n 23 SETUP_FINALLY 23 (to 49)\n 26 LOAD_FAST 1 (_[1])\n 29 DELETE_FAST 1 (_[1])\n 32 STORE_FAST 2 (f)\n\n 3 35 LOAD_FAST 2 (f)\n 38 LOAD_ATTR 3 (read)\n 41 CALL_FUNCTION 0\n 44 RETURN_VALUE \n 45 POP_BLOCK \n 46 LOAD_CONST 0 (None)\n >> 49 WITH_CLEANUP \n 50 END_FINALLY \n 51 LOAD_CONST 0 (None)\n 54 RETURN_VALUE \n>>> dis(bar)\n 2 0 LOAD_GLOBAL 0 (open)\n 3 LOAD_FAST 0 (filename)\n 6 CALL_FUNCTION 1\n 9 LOAD_ATTR 1 (read)\n 12 CALL_FUNCTION 0\n 15 RETURN_VALUE \n\n",
"For the cpython implementation of python: yes, it is guaranteed to be closed when its reference count goes to zero.\nFor python as an abstract language (e.g., including Jython, IronPython, etc): no, it is not guaranteed to be closed. In particular, an implementation of Python may choose not to use reference counting, but to use some other form of GC.\nReferences:\n\nhttp://docs.python.org/c-api/typeobj.html#tp_dealloc\nhttp://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/\n\n",
"No, Python optimize deleting unused objects so It may never close your file (OK at the end of your script at exit it will cleanup).\n@ hughdbrown have pointed out nice solution.\n"
] |
[
33,
27,
12,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001834556_python.txt
|
Q:
split a comma separated list with links in with beautifulsoup
I've got a comma separated list in a table cell in an HTML document, but some of items in the list are linked:
<table>
<tr>
<td>Names</td>
<td>Fred, John, Barry, <a href="http://www.example.com/">Roger</a>, James</td>
</tr>
</table>
I've been using beautiful soup to parse the html, and I can get to the table, but what is the best way to split it and return a data structure roughly like:
[
{'name':'Fred'},
{'name':'John'},
{'name':'Barry'},
{'name':'Roger', 'url':'http://www.example.com/'},
{'name':'James'},
]
A:
This is one way you could do it:
import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup('''<table>
<tr>
<td>Names</td>
<td>Fred, John, Barry, <a href="http://www.example.com/">Roger</a>, James</td>
</tr>
</table>''')
result = []
for tag in soup.table.findAll('td')[1]:
if isinstance(tag, BeautifulSoup.NavigableString):
for name in tag.string.split(','):
name = name.strip()
if name:
result.append({ 'name': name })
else:
result.append({ 'name': tag.string.strip(), 'url': tag["href"] })
print result
|
split a comma separated list with links in with beautifulsoup
|
I've got a comma separated list in a table cell in an HTML document, but some of items in the list are linked:
<table>
<tr>
<td>Names</td>
<td>Fred, John, Barry, <a href="http://www.example.com/">Roger</a>, James</td>
</tr>
</table>
I've been using beautiful soup to parse the html, and I can get to the table, but what is the best way to split it and return a data structure roughly like:
[
{'name':'Fred'},
{'name':'John'},
{'name':'Barry'},
{'name':'Roger', 'url':'http://www.example.com/'},
{'name':'James'},
]
|
[
"This is one way you could do it:\nimport BeautifulSoup\n\nsoup = BeautifulSoup.BeautifulSoup('''<table>\n <tr>\n <td>Names</td>\n <td>Fred, John, Barry, <a href=\"http://www.example.com/\">Roger</a>, James</td>\n </tr>\n</table>''')\n\nresult = []\nfor tag in soup.table.findAll('td')[1]:\n if isinstance(tag, BeautifulSoup.NavigableString):\n for name in tag.string.split(','):\n name = name.strip()\n if name:\n result.append({ 'name': name })\n else:\n result.append({ 'name': tag.string.strip(), 'url': tag[\"href\"] })\n\nprint result\n\n"
] |
[
10
] |
[] |
[] |
[
"beautifulsoup",
"html_parsing",
"python"
] |
stackoverflow_0001834779_beautifulsoup_html_parsing_python.txt
|
Q:
Serving simple image with App Engine django patch?
How the heck do i serve a simple img without all that MediaGenerator nonsense, in Django on App Engine?
I am using app engine patch.
I got layout like this:
django_app_engine_project_folder
my_app
Where should my folder for my media be? In my_app? Or do I put everything in the top media folder?
I want to do something like this in my HTML template...
<img src="/site_media/my_image.jpg" />
Note that /media prefix is already beign used for admin media.
A:
Well it seems that using app.yaml works out:
- url: /my_app/media/
static_dir: my_app/media
Which allows me to refer to image a.jpg in folder my_app/media with a url like:
<img src="/my_app/media/a.jpg" />
|
Serving simple image with App Engine django patch?
|
How the heck do i serve a simple img without all that MediaGenerator nonsense, in Django on App Engine?
I am using app engine patch.
I got layout like this:
django_app_engine_project_folder
my_app
Where should my folder for my media be? In my_app? Or do I put everything in the top media folder?
I want to do something like this in my HTML template...
<img src="/site_media/my_image.jpg" />
Note that /media prefix is already beign used for admin media.
|
[
"Well it seems that using app.yaml works out:\n- url: /my_app/media/\n static_dir: my_app/media\n\nWhich allows me to refer to image a.jpg in folder my_app/media with a url like:\n<img src=\"/my_app/media/a.jpg\" />\n\n"
] |
[
2
] |
[] |
[] |
[
"app_engine_patch",
"django",
"python"
] |
stackoverflow_0001834610_app_engine_patch_django_python.txt
|
Q:
Qt QFileDialog QSizePolicy of sidebar
With a QFileDialog I'm trying to change the size of the side bar in a QFileDialog. I want it to have a larger width. I was looking at dir(QtGui.QFileDialog) which shows a plethora of functions/methods and dir(QtGui.QSizePolicy) which seemed like the right choice. I've not been able to manipulate the size of the side bar though.
print 'sizePolicy: ', self.sizePolicy()
urls = [ QtCore.QUrl("file:"), QtCore.QUrl("file:///usr/home/")]
self.fileBrowser.setSidebarUrls( urls )
Returns // sizePolicy:
It seems to average out the length of the names to create the width of the side bar. Anyone know a way around this? Size policy returns back a QSizePolicy object, but I don't know how to manipulate the side bar's size.
Thanks!
A:
I would suggest using find_children and then maybe qobject_cast to get the sidebar object and the manipulate it directly.
|
Qt QFileDialog QSizePolicy of sidebar
|
With a QFileDialog I'm trying to change the size of the side bar in a QFileDialog. I want it to have a larger width. I was looking at dir(QtGui.QFileDialog) which shows a plethora of functions/methods and dir(QtGui.QSizePolicy) which seemed like the right choice. I've not been able to manipulate the size of the side bar though.
print 'sizePolicy: ', self.sizePolicy()
urls = [ QtCore.QUrl("file:"), QtCore.QUrl("file:///usr/home/")]
self.fileBrowser.setSidebarUrls( urls )
Returns // sizePolicy:
It seems to average out the length of the names to create the width of the side bar. Anyone know a way around this? Size policy returns back a QSizePolicy object, but I don't know how to manipulate the side bar's size.
Thanks!
|
[
"I would suggest using find_children and then maybe qobject_cast to get the sidebar object and the manipulate it directly. \n"
] |
[
0
] |
[] |
[] |
[
"pyqt",
"python",
"qt",
"resize"
] |
stackoverflow_0001241893_pyqt_python_qt_resize.txt
|
Q:
python regex escape characters
We have:
>>> str
'exit\r\ndrwxr-xr-x 2 root root 0 Jan 1 2000
\x1b[1;34mbin\x1b[0m\r\ndrwxr-xr-x 3 root root
0 Jan 1 2000 \x1b[1;34mlib\x1b[0m\r\ndrwxr-xr-x 10 root
root 0 Jan 1 1970 \x1b[1;34mlocal\x1b[0m\r\ndrwxr-xr-x
2 root root 0 Jan 1 2000 \x1b[1;34msbin\x1b[0m\r\ndrwxr-xr-x
5 root root 0 Jan 1 2000 \x1b[1;34mshare\x1b[0m\r\n# exit\r\n'
>>> print str
exit
drwxr-xr-x 2 root root 0 Jan 1 2000 bin
drwxr-xr-x 3 root root 0 Jan 1 2000 lib
drwxr-xr-x 10 root root 0 Jan 1 1970 local
drwxr-xr-x 2 root root 0 Jan 1 2000 sbin
drwxr-xr-x 5 root root 0 Jan 1 2000 share
# exit
I want to get rid of all the '\xblah[0m' nonsense using regexp. I've tried
re.sub(str, r'(\x.*m)', '')
But that hasn't done the trick. Any ideas?
A:
You have a few issues:
You're passing arguments to re.sub in the wrong order wrong. It should be:
re.sub(regexp_pattern, replacement, source_string)
The string doesn't contain "\x". That "\x1b" is the escape character, and it's a single character.
As interjay pointed out, you want ".*?" rather than ".*", because otherwise it will match everything from the first escape through the last "m".
The correct call to re.sub is:
print re.sub('\x1b.*?m', '', s)
Alternatively, you could use:
print re.sub('\x1b[^m]*m', '', s)
A:
You need the following changes:
Escape the backslash
Switch to non-greedy matching. Otherwise, everything between the first \x and the last m will be removed, which will be a problem when there is more than one occurrence.
The order of arguments is incorrect
Result:
re.sub(r'(\\x.*?m)', '', str)
A:
These are ANSI terminal codes. They're signalled by an ESC (byte 27, seen in Python as \x1B) followed by [, then some ;-separated parameters and finally a letter to specify which command it is. (m is a colour change.)
The parameters are usually numbers so for this simple case you could get rid of them with:
ansisequence= re.compile(r'\x1B\[[^A-Za-z]*[A-Za-z]')
ansisequence.sub('', string)
Technically for some (non-colour-related) control codes they could be general strings, which makes the parsing annoying. It's rare you'd meet these, but if you did I guess you'd have to use something complicated like:
\x1B\[((\d+|"[^"]*")(;(\d+|"[^"]*"))*)?[A-Za-z]
Best would be to persuade whatever's generating the string that you're not an ANSI terminal so it shouldnt include colour codes in its output.
A:
Try running ls --color=never -l instead, and you won't get the ANSI escape codes in the first place.
A:
Here is a pyparsing solution to your problem, with a general parsing expression for those pesky escape sequences. By transforming the initial string with a suppressed expression, this returns a string stripped of all matches of the expression.
s = \
'exit\r\ndrwxr-xr-x 2 root root 0 Jan 1 2000 ' \
'\x1b[1;34mbin\x1b[0m\r\ndrwxr-xr-x 3 root root ' \
'0 Jan 1 2000 \x1b[1;34mlib\x1b[0m\r\ndrwxr-xr-x 10 root ' \
'root 0 Jan 1 1970 \x1b[1;34mlocal\x1b[0m\r\ndrwxr-xr-x ' \
'2 root root 0 Jan 1 2000 \x1b[1;34msbin\x1b[0m\r\ndrwxr-xr-x ' \
'5 root root 0 Jan 1 2000 \x1b[1;34mshare\x1b[0m\r\n# exit\r\n' \
from pyparsing import (Literal, Word, nums, Combine,
delimitedList, oneOf, alphas, Suppress)
ESC = Literal('\x1b')
integer = Word(nums)
escapeSeq = Combine(ESC + '[' + delimitedList(integer,';') + oneOf(list(alphas)))
s_prime = Suppress(escapeSeq).transformString(s)
print s_prime
This prints your desired output, as stored in s_prime.
|
python regex escape characters
|
We have:
>>> str
'exit\r\ndrwxr-xr-x 2 root root 0 Jan 1 2000
\x1b[1;34mbin\x1b[0m\r\ndrwxr-xr-x 3 root root
0 Jan 1 2000 \x1b[1;34mlib\x1b[0m\r\ndrwxr-xr-x 10 root
root 0 Jan 1 1970 \x1b[1;34mlocal\x1b[0m\r\ndrwxr-xr-x
2 root root 0 Jan 1 2000 \x1b[1;34msbin\x1b[0m\r\ndrwxr-xr-x
5 root root 0 Jan 1 2000 \x1b[1;34mshare\x1b[0m\r\n# exit\r\n'
>>> print str
exit
drwxr-xr-x 2 root root 0 Jan 1 2000 bin
drwxr-xr-x 3 root root 0 Jan 1 2000 lib
drwxr-xr-x 10 root root 0 Jan 1 1970 local
drwxr-xr-x 2 root root 0 Jan 1 2000 sbin
drwxr-xr-x 5 root root 0 Jan 1 2000 share
# exit
I want to get rid of all the '\xblah[0m' nonsense using regexp. I've tried
re.sub(str, r'(\x.*m)', '')
But that hasn't done the trick. Any ideas?
|
[
"You have a few issues:\n\nYou're passing arguments to re.sub in the wrong order wrong. It should be:\nre.sub(regexp_pattern, replacement, source_string)\nThe string doesn't contain \"\\x\". That \"\\x1b\" is the escape character, and it's a single character.\nAs interjay pointed out, you want \".*?\" rather than \".*\", because otherwise it will match everything from the first escape through the last \"m\".\n\nThe correct call to re.sub is:\nprint re.sub('\\x1b.*?m', '', s)\n\nAlternatively, you could use:\nprint re.sub('\\x1b[^m]*m', '', s)\n\n",
"You need the following changes:\n\nEscape the backslash\nSwitch to non-greedy matching. Otherwise, everything between the first \\x and the last m will be removed, which will be a problem when there is more than one occurrence.\nThe order of arguments is incorrect\n\nResult:\nre.sub(r'(\\\\x.*?m)', '', str)\n\n",
"These are ANSI terminal codes. They're signalled by an ESC (byte 27, seen in Python as \\x1B) followed by [, then some ;-separated parameters and finally a letter to specify which command it is. (m is a colour change.)\nThe parameters are usually numbers so for this simple case you could get rid of them with:\nansisequence= re.compile(r'\\x1B\\[[^A-Za-z]*[A-Za-z]')\nansisequence.sub('', string)\n\nTechnically for some (non-colour-related) control codes they could be general strings, which makes the parsing annoying. It's rare you'd meet these, but if you did I guess you'd have to use something complicated like:\n\\x1B\\[((\\d+|\"[^\"]*\")(;(\\d+|\"[^\"]*\"))*)?[A-Za-z]\n\nBest would be to persuade whatever's generating the string that you're not an ANSI terminal so it shouldnt include colour codes in its output.\n",
"Try running ls --color=never -l instead, and you won't get the ANSI escape codes in the first place.\n",
"Here is a pyparsing solution to your problem, with a general parsing expression for those pesky escape sequences. By transforming the initial string with a suppressed expression, this returns a string stripped of all matches of the expression.\ns = \\\n'exit\\r\\ndrwxr-xr-x 2 root root 0 Jan 1 2000 ' \\\n'\\x1b[1;34mbin\\x1b[0m\\r\\ndrwxr-xr-x 3 root root ' \\\n'0 Jan 1 2000 \\x1b[1;34mlib\\x1b[0m\\r\\ndrwxr-xr-x 10 root ' \\\n'root 0 Jan 1 1970 \\x1b[1;34mlocal\\x1b[0m\\r\\ndrwxr-xr-x ' \\\n'2 root root 0 Jan 1 2000 \\x1b[1;34msbin\\x1b[0m\\r\\ndrwxr-xr-x ' \\\n'5 root root 0 Jan 1 2000 \\x1b[1;34mshare\\x1b[0m\\r\\n# exit\\r\\n' \\\n\nfrom pyparsing import (Literal, Word, nums, Combine, \n delimitedList, oneOf, alphas, Suppress)\n\nESC = Literal('\\x1b')\ninteger = Word(nums)\nescapeSeq = Combine(ESC + '[' + delimitedList(integer,';') + oneOf(list(alphas)))\n\ns_prime = Suppress(escapeSeq).transformString(s)\n\nprint s_prime\n\nThis prints your desired output, as stored in s_prime.\n"
] |
[
12,
3,
3,
2,
1
] |
[] |
[] |
[
"ansi_escape",
"python",
"regex"
] |
stackoverflow_0001833873_ansi_escape_python_regex.txt
|
Q:
Compile IP2Location Python extension for Windows 7
I want to compile / install the IP2Location Python extension found here:
www.ip2location.com/python.aspx
I tried following the instructions at these sites:
eli.thegreenplace.net/2008/06/28/compiling-python-extensions-with-distutils-and-mingw/
boodebr.org/main/python/build-windows-extensions
But I am getting no where. The problem is the Python extension relies on another C library:
www.ip2location.com/c.aspx
When I try to compile this library in cygwin I get the following output:
make all-recursive
make[1]: Entering directory `/home/ty/Python-IP2Location/C-IP2Location-3.0.0'
Making all in libIP2Location
make[2]: Entering directory `/home/ty/Python-IP2Location/C-IP2Location-3.0.0/li
bIP2Location'
/bin/sh ../libtool --tag=CC --mode=link gcc -mno-cygwin -IiMath/ -g -O2 -modul
e -no-undefined -avoid-version -o libIP2Location.la -rpath /cygdrive/c/MinGW/li
b libIP2Location_la-IP2Location.lo libIP2Location_la-imath.lo
libtool: link: rm -fr .libs/libIP2Location.dll.a
libtool: link: gcc -mno-cygwin -shared .libs/libIP2Location_la-IP2Location.o .l
ibs/libIP2Location_la-imath.o -mno-cygwin -o .libs/libIP2Location.dll -Wl,-
-enable-auto-image-base -Xlinker --out-implib -Xlinker .libs/libIP2Location.dll.
a
.libs/libIP2Location_la-IP2Location.o: In function `IP2Location_ip2no':
/home/ty/Python-IP2Location/C-IP2Location-3.0.0/libIP2Location/IP2Location.c:71
8: undefined reference to `_inet_addr@4'
Creating library file: .libs/libIP2Location.dll.a
collect2: ld returned 1 exit status
make[2]: *** [libIP2Location.la] Error 1
make[2]: Leaving directory `/home/ty/Python-IP2Location/C-IP2Location-3.0.0/lib
IP2Location'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/ty/Python-IP2Location/C-IP2Location-3.0.0'
make: *** [all] Error 2
I'm running python 2.6.3 on Windows 7 32-bit.
I have MS Visual Studio 2008 (though no idea how to use it) and of course cygwin / MinGW.
Any help or pointers would be greatly appreciated.
A:
OK, so the full solution is:
download stdint.h and put it in the IP2Location C Library folder: http://msinttypes.googlecode.com/svn/trunk/stdint.h
open a dos prompt and execute "C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"
from the same dos prompt execute "nmake /f Makefile.win"
cd to the Python extension folder and execute "set LINK=/nod:msvcrt.lib"
lastly do the standard "python setup.py install"
The credit for the "set LINK=/nod:msvcrt.lib" advice goes to Tim Roberts of Providenza & Boekelheide, Inc (probo.com). -- he was kind enough to answer my cry for help on the python win32 mailing list. Thanks Tim!
A:
Try adding -lws2_32 option to linking command.
BTW, there is another pure Python library to get country from IP.
|
Compile IP2Location Python extension for Windows 7
|
I want to compile / install the IP2Location Python extension found here:
www.ip2location.com/python.aspx
I tried following the instructions at these sites:
eli.thegreenplace.net/2008/06/28/compiling-python-extensions-with-distutils-and-mingw/
boodebr.org/main/python/build-windows-extensions
But I am getting no where. The problem is the Python extension relies on another C library:
www.ip2location.com/c.aspx
When I try to compile this library in cygwin I get the following output:
make all-recursive
make[1]: Entering directory `/home/ty/Python-IP2Location/C-IP2Location-3.0.0'
Making all in libIP2Location
make[2]: Entering directory `/home/ty/Python-IP2Location/C-IP2Location-3.0.0/li
bIP2Location'
/bin/sh ../libtool --tag=CC --mode=link gcc -mno-cygwin -IiMath/ -g -O2 -modul
e -no-undefined -avoid-version -o libIP2Location.la -rpath /cygdrive/c/MinGW/li
b libIP2Location_la-IP2Location.lo libIP2Location_la-imath.lo
libtool: link: rm -fr .libs/libIP2Location.dll.a
libtool: link: gcc -mno-cygwin -shared .libs/libIP2Location_la-IP2Location.o .l
ibs/libIP2Location_la-imath.o -mno-cygwin -o .libs/libIP2Location.dll -Wl,-
-enable-auto-image-base -Xlinker --out-implib -Xlinker .libs/libIP2Location.dll.
a
.libs/libIP2Location_la-IP2Location.o: In function `IP2Location_ip2no':
/home/ty/Python-IP2Location/C-IP2Location-3.0.0/libIP2Location/IP2Location.c:71
8: undefined reference to `_inet_addr@4'
Creating library file: .libs/libIP2Location.dll.a
collect2: ld returned 1 exit status
make[2]: *** [libIP2Location.la] Error 1
make[2]: Leaving directory `/home/ty/Python-IP2Location/C-IP2Location-3.0.0/lib
IP2Location'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/home/ty/Python-IP2Location/C-IP2Location-3.0.0'
make: *** [all] Error 2
I'm running python 2.6.3 on Windows 7 32-bit.
I have MS Visual Studio 2008 (though no idea how to use it) and of course cygwin / MinGW.
Any help or pointers would be greatly appreciated.
|
[
"OK, so the full solution is:\n\ndownload stdint.h and put it in the IP2Location C Library folder: http://msinttypes.googlecode.com/svn/trunk/stdint.h\nopen a dos prompt and execute \"C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\vcvarsall.bat\"\nfrom the same dos prompt execute \"nmake /f Makefile.win\"\ncd to the Python extension folder and execute \"set LINK=/nod:msvcrt.lib\"\nlastly do the standard \"python setup.py install\"\n\nThe credit for the \"set LINK=/nod:msvcrt.lib\" advice goes to Tim Roberts of Providenza & Boekelheide, Inc (probo.com). -- he was kind enough to answer my cry for help on the python win32 mailing list. Thanks Tim!\n",
"Try adding -lws2_32 option to linking command.\nBTW, there is another pure Python library to get country from IP.\n"
] |
[
2,
1
] |
[] |
[] |
[
"c",
"python",
"windows"
] |
stackoverflow_0001815689_c_python_windows.txt
|
Q:
In Python, is the idiom "from Module import ClassName" typical?
Since I prefer small files, I typically place a single "public" class per Python module. I name the module with the same name as the class it contains. So for example, the class ToolSet would be defined in ToolSet.py.
Within a package, if another module needs to instanciate an object of class ToolSet, I use:
from ToolSet import ToolSet
...
toolSet = ToolSet()
instead of:
import ToolSet
...
toolSet = ToolSet.ToolSet()
I do this to reduce "stutter" (I prefer to have stutter at the top of the file than within my code.)
Is this a correct idiom?
Here is a related question. Within a package, I often have a small number of classes that I would like to expose to the outside world. These I import inside the __init__.py for that package. For example, if ToolSet is in package UI and I want to expose it, I would put the following in UI/__init__.py :
from ToolSet import ToolSet
So that, from an external module I can write
import UI
...
toolSet = UI.ToolSet()
Again, is this pythonic?
A:
To answer your first question, that is the idiom I use, and its use is supported by PEP8 the python style guide
it's okay to say this though:
from subprocess import Popen, PIPE
I like it as it reduces typing and makes sure that things go wrong immediately the file is run (say you mis-spelt an import) rather than some time later when a function using the import is run.
Eg suppose the module Thing doesn't have a Thyng member
from Thing import Thyng
Goes wrong immediately you run the .py file, whereas
import Thing
# ...
def fn():
Thing.Thyng()
Doesn't go wrong until you run fn()
As for your second question, I think that is also good practice. It often happens to me when I factor a single large.py into a directory with an __init__.py and implementation files. Importing things into the __init__.py keeps the interface the same. It is common practice in the standard libraries too.
A:
Yes. Both are idiomatic Python in my opinion.
I tend to use the from module import name form for some modules in the standard library, such as datetime, but mostly for closely related modules, or names that are frequently used in the module. For example, I typically import ORM classes in this way.
I tend to use the import module form for some standard modules (especially os and os.path) and for names that are not very distinctive (like database.session and cherrypy.session being two different kind of sessions) and for name that are used infrequently where the mention of the module name improves readability.
In the end, there are a few rules of thumb (such as import os.path), but which form to use is largely a matter of judgement, taste and experience.
A:
To address if it is pythonic, take a look at what is generally the definitive answer on the internet: http://effbot.org/zone/import-confusion.htm
Also take a look at ~unutbu's link which discusses this in greater detail.
A:
I use from itertools import chain, ifilter, islice, izip all the time, because it allows me to program as though those were built-in methods, which to my way of thinking they really ought to be.
Once, in a frenzy of misguided correctness, I went through a big block of code and replaced from datetime import datetime with import datetime. This was a good example of Mark Twain's observation that a man who picks up a rat by the tail learns something that can be learned no other way. It certainly set me straight on why it's OK to use from x import y.
|
In Python, is the idiom "from Module import ClassName" typical?
|
Since I prefer small files, I typically place a single "public" class per Python module. I name the module with the same name as the class it contains. So for example, the class ToolSet would be defined in ToolSet.py.
Within a package, if another module needs to instanciate an object of class ToolSet, I use:
from ToolSet import ToolSet
...
toolSet = ToolSet()
instead of:
import ToolSet
...
toolSet = ToolSet.ToolSet()
I do this to reduce "stutter" (I prefer to have stutter at the top of the file than within my code.)
Is this a correct idiom?
Here is a related question. Within a package, I often have a small number of classes that I would like to expose to the outside world. These I import inside the __init__.py for that package. For example, if ToolSet is in package UI and I want to expose it, I would put the following in UI/__init__.py :
from ToolSet import ToolSet
So that, from an external module I can write
import UI
...
toolSet = UI.ToolSet()
Again, is this pythonic?
|
[
"To answer your first question, that is the idiom I use, and its use is supported by PEP8 the python style guide\n\nit's okay to say this though:\nfrom subprocess import Popen, PIPE\n\nI like it as it reduces typing and makes sure that things go wrong immediately the file is run (say you mis-spelt an import) rather than some time later when a function using the import is run.\nEg suppose the module Thing doesn't have a Thyng member\nfrom Thing import Thyng\n\nGoes wrong immediately you run the .py file, whereas\nimport Thing\n# ...\ndef fn():\n Thing.Thyng()\n\nDoesn't go wrong until you run fn()\nAs for your second question, I think that is also good practice. It often happens to me when I factor a single large.py into a directory with an __init__.py and implementation files. Importing things into the __init__.py keeps the interface the same. It is common practice in the standard libraries too.\n",
"Yes. Both are idiomatic Python in my opinion.\nI tend to use the from module import name form for some modules in the standard library, such as datetime, but mostly for closely related modules, or names that are frequently used in the module. For example, I typically import ORM classes in this way.\nI tend to use the import module form for some standard modules (especially os and os.path) and for names that are not very distinctive (like database.session and cherrypy.session being two different kind of sessions) and for name that are used infrequently where the mention of the module name improves readability.\nIn the end, there are a few rules of thumb (such as import os.path), but which form to use is largely a matter of judgement, taste and experience.\n",
"To address if it is pythonic, take a look at what is generally the definitive answer on the internet: http://effbot.org/zone/import-confusion.htm\nAlso take a look at ~unutbu's link which discusses this in greater detail.\n",
"I use from itertools import chain, ifilter, islice, izip all the time, because it allows me to program as though those were built-in methods, which to my way of thinking they really ought to be. \nOnce, in a frenzy of misguided correctness, I went through a big block of code and replaced from datetime import datetime with import datetime. This was a good example of Mark Twain's observation that a man who picks up a rat by the tail learns something that can be learned no other way. It certainly set me straight on why it's OK to use from x import y.\n"
] |
[
5,
0,
0,
0
] |
[] |
[] |
[
"import",
"python"
] |
stackoverflow_0001835014_import_python.txt
|
Q:
How to do scheduled sending of email with django-mailer
I'm making a django app that needs to be able to make emails and then send these out at a given time. I was thinking i could use django-mailer to put things in que and then send it of. But even though theire sample case list, lists that this is a feature, I cant seem to find out how.
What I need is to be able to set a 'when_to_send' field in the message model of django-mailer, and when the cron job fires the send_mail function this needs to filter out the ones that has a 'when_to_send' date that is greater than the current time...
def send_all():
"""
Send all eligible messages in the queue.
"""
lock = FileLock("send_mail")
logging.debug("acquiring lock...")
try:
lock.acquire(LOCK_WAIT_TIMEOUT)
except AlreadyLocked:
logging.debug("lock already in place. quitting.")
return
except LockTimeout:
logging.debug("waiting for the lock timed out. quitting.")
return
logging.debug("acquired.")
start_time = time.time()
dont_send = 0
deferred = 0
sent = 0
try:
for message in prioritize():
if DontSendEntry.objects.has_address(message.to_address):
logging.info("skipping email to %s as on don't send list " % message.to_address)
MessageLog.objects.log(message, 2) # @@@ avoid using literal result code
message.delete()
dont_send += 1
else:
try:
logging.info("sending message '%s' to %s" % (message.subject.encode("utf-8"), message.to_address.encode("utf-8")))
core_send_mail(message.subject, message.message_body, message.from_address, [message.to_address])
MessageLog.objects.log(message, 1) # @@@ avoid using literal result code
message.delete()
sent += 1
except (socket_error, smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused, smtplib.SMTPAuthenticationError), err:
message.defer()
logging.info("message deferred due to failure: %s" % err)
MessageLog.objects.log(message, 3, log_message=str(err)) # @@@ avoid using literal result code
deferred += 1
finally:
logging.debug("releasing lock...")
lock.release()
logging.debug("released.")
logging.info("")
logging.info("%s sent; %s deferred; %s don't send" % (sent, deferred, dont_send))
logging.info("done in %.2f seconds" % (time.time() - start_time))
Anyone see how to customize this function to don't send email's where the message.when_to_send field is greater than the current time?
A:
You need to implement the cron job for django-mailer:
* * * * * (cd $PINAX; /usr/local/bin/python2.5 manage.py send_mail >> $PINAX/cron_mail.log 2>&1)
And then in engine.py line 96:
# Get rid of "while True:"
while not Message.objects.all():
# Get rid of logging.debug("sleeping for %s seconds before checking queue again" % EMPTY_QUEUE_SLEEP)
# Get rid of sleep
send_all()
A:
You can just add another clause to the conditionals under your message processing loop (you will also need to import datetime at the top of your file):
for message in prioritize():
if DontSendEntry.objects.has_address(message.to_address):
logging.info("skipping email to %s as on don't send list " % message.to_address)
MessageLog.objects.log(message, 2) # @@@ avoid using literal result code
message.delete()
dont_send += 1
elif message.when_to_send > datetime.datetime.now():
continue
else:
try:
... the rest of your code ...
|
How to do scheduled sending of email with django-mailer
|
I'm making a django app that needs to be able to make emails and then send these out at a given time. I was thinking i could use django-mailer to put things in que and then send it of. But even though theire sample case list, lists that this is a feature, I cant seem to find out how.
What I need is to be able to set a 'when_to_send' field in the message model of django-mailer, and when the cron job fires the send_mail function this needs to filter out the ones that has a 'when_to_send' date that is greater than the current time...
def send_all():
"""
Send all eligible messages in the queue.
"""
lock = FileLock("send_mail")
logging.debug("acquiring lock...")
try:
lock.acquire(LOCK_WAIT_TIMEOUT)
except AlreadyLocked:
logging.debug("lock already in place. quitting.")
return
except LockTimeout:
logging.debug("waiting for the lock timed out. quitting.")
return
logging.debug("acquired.")
start_time = time.time()
dont_send = 0
deferred = 0
sent = 0
try:
for message in prioritize():
if DontSendEntry.objects.has_address(message.to_address):
logging.info("skipping email to %s as on don't send list " % message.to_address)
MessageLog.objects.log(message, 2) # @@@ avoid using literal result code
message.delete()
dont_send += 1
else:
try:
logging.info("sending message '%s' to %s" % (message.subject.encode("utf-8"), message.to_address.encode("utf-8")))
core_send_mail(message.subject, message.message_body, message.from_address, [message.to_address])
MessageLog.objects.log(message, 1) # @@@ avoid using literal result code
message.delete()
sent += 1
except (socket_error, smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused, smtplib.SMTPAuthenticationError), err:
message.defer()
logging.info("message deferred due to failure: %s" % err)
MessageLog.objects.log(message, 3, log_message=str(err)) # @@@ avoid using literal result code
deferred += 1
finally:
logging.debug("releasing lock...")
lock.release()
logging.debug("released.")
logging.info("")
logging.info("%s sent; %s deferred; %s don't send" % (sent, deferred, dont_send))
logging.info("done in %.2f seconds" % (time.time() - start_time))
Anyone see how to customize this function to don't send email's where the message.when_to_send field is greater than the current time?
|
[
"You need to implement the cron job for django-mailer:\n* * * * * (cd $PINAX; /usr/local/bin/python2.5 manage.py send_mail >> $PINAX/cron_mail.log 2>&1)\n\nAnd then in engine.py line 96:\n # Get rid of \"while True:\"\n while not Message.objects.all():\n # Get rid of logging.debug(\"sleeping for %s seconds before checking queue again\" % EMPTY_QUEUE_SLEEP)\n # Get rid of sleep\n send_all()\n\n",
"You can just add another clause to the conditionals under your message processing loop (you will also need to import datetime at the top of your file):\n for message in prioritize():\n if DontSendEntry.objects.has_address(message.to_address):\n logging.info(\"skipping email to %s as on don't send list \" % message.to_address)\n MessageLog.objects.log(message, 2) # @@@ avoid using literal result code\n message.delete()\n dont_send += 1\n elif message.when_to_send > datetime.datetime.now():\n continue\n else:\n try:\n ... the rest of your code ...\n\n"
] |
[
4,
0
] |
[] |
[] |
[
"django",
"django_mailer",
"email",
"python",
"schedule"
] |
stackoverflow_0001177088_django_django_mailer_email_python_schedule.txt
|
Q:
Problem with variable scoping in Python
This problem is partly due to my lack of completely understanding scoping in python, so I'll need to review that. Either way, here is a seriously trivial piece of code that keeps crashing on my Django test app.
Here's a snippet:
@login_required
def someview(request):
try:
usergroup = request.user.groups.all()[0].name
except:
HttpResponseRedirect('/accounts/login')
if 'client' in usergroup:
stafflist = ProxyUserModel.objects.filter(groups__name='staff')
No brain surgery here, the problem is I get an error such as the following:
File "/usr/local/django/myapp/views.py", line 18, in someview
if 'client' in usergroup:
UnboundLocalError: local variable 'usergroup' referenced before assignment
My question here is, why is usergroup unbound? If it's unbound, that means the try statement had an exception thrown at which point an HttpResponseRedirect should happen, but it never does. Instead I get an HTTP 500 error back, which is slightly confusing.
Yes I can write smarter code and ensure that the user logging in definitely has a group associated with them. But this isn't a production app, I'm just trying to understand / learn Python/Django. Why exactly is the above happening when a user that's not associated with a group logs in instead of a redirect to a login page?
In this case I'm intentionally logging in as a user that isn't part of a group. That means that the above code should throw an IndexError exception like the following:
>>> somelist = []
>>> print somelist[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
A:
HttpResponseRedirect('/accounts/login')
You're creating it but not returning it. Flow continues to the next line, which references usergroup despite it never having been assigned due to the exception.
The except is also troublesome. In general you should never catch βeverythingβ (except: or except Exception:) as there are lots of odd conditions in there you could be throwing away, making debugging very difficult. Either catch the specific exception subclass that you think is going to happen when the user isn't logged on, or, better, use an if test to see if they're logged on. (It's not really an exceptional condition.)
eg. in Django normally:
if not request.user.is_authenticated():
return HttpResponseRedirect('/accounts/login')
or if your concern is the user isn't in any groups (making the [0] fail):
groups= request.user.groups.all()
if len(groups)==0:
return HttpResponseRedirect('/accounts/login')
usergroup= groups[0].name
A:
Try moving you if 'client' part inside you try block. Either that or define usergroup = None right above the try.
A:
In cases where you have a tryβ¦except suite and you want code to run iff no exceptions have occurred, it's a good habit to write the code as follows:
try:
# code that could fail
except Exception1:
# handle exception1
except Exception2:
# handle exception2
else: # the code-that-could-fail didn't
# here runs the code that depends
# on the success of the try clause
|
Problem with variable scoping in Python
|
This problem is partly due to my lack of completely understanding scoping in python, so I'll need to review that. Either way, here is a seriously trivial piece of code that keeps crashing on my Django test app.
Here's a snippet:
@login_required
def someview(request):
try:
usergroup = request.user.groups.all()[0].name
except:
HttpResponseRedirect('/accounts/login')
if 'client' in usergroup:
stafflist = ProxyUserModel.objects.filter(groups__name='staff')
No brain surgery here, the problem is I get an error such as the following:
File "/usr/local/django/myapp/views.py", line 18, in someview
if 'client' in usergroup:
UnboundLocalError: local variable 'usergroup' referenced before assignment
My question here is, why is usergroup unbound? If it's unbound, that means the try statement had an exception thrown at which point an HttpResponseRedirect should happen, but it never does. Instead I get an HTTP 500 error back, which is slightly confusing.
Yes I can write smarter code and ensure that the user logging in definitely has a group associated with them. But this isn't a production app, I'm just trying to understand / learn Python/Django. Why exactly is the above happening when a user that's not associated with a group logs in instead of a redirect to a login page?
In this case I'm intentionally logging in as a user that isn't part of a group. That means that the above code should throw an IndexError exception like the following:
>>> somelist = []
>>> print somelist[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
|
[
"HttpResponseRedirect('/accounts/login')\n\nYou're creating it but not returning it. Flow continues to the next line, which references usergroup despite it never having been assigned due to the exception.\nThe except is also troublesome. In general you should never catch βeverythingβ (except: or except Exception:) as there are lots of odd conditions in there you could be throwing away, making debugging very difficult. Either catch the specific exception subclass that you think is going to happen when the user isn't logged on, or, better, use an if test to see if they're logged on. (It's not really an exceptional condition.)\neg. in Django normally:\nif not request.user.is_authenticated():\n return HttpResponseRedirect('/accounts/login')\n\nor if your concern is the user isn't in any groups (making the [0] fail):\ngroups= request.user.groups.all()\nif len(groups)==0:\n return HttpResponseRedirect('/accounts/login')\nusergroup= groups[0].name\n\n",
"Try moving you if 'client' part inside you try block. Either that or define usergroup = None right above the try.\n",
"In cases where you have a tryβ¦except suite and you want code to run iff no exceptions have occurred, it's a good habit to write the code as follows:\ntry:\n # code that could fail\nexcept Exception1:\n # handle exception1\nexcept Exception2:\n # handle exception2\nelse: # the code-that-could-fail didn't\n # here runs the code that depends\n # on the success of the try clause\n\n"
] |
[
10,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001835809_django_python.txt
|
Q:
Python universal database interface?
Does there exist, or is there an intention to create, a universal database frontend for Python like Perl's DBI? I am aware of Python's DB-API, but all the separate packages are leaving me somewhat aggravated.
A:
AFAIK there is no one Python module that implements the DB-API to multiple databases and that's pretty much by design: why bring in unneeded functionality and possibly require the underlying database libraries to be installed if you are not going to use them? You can argue with that design decision but that's the way it is. On the other hand, the DB-API attempts to ensure that the API presented by the individual DB adapters is the same (or very close to the same). And then there are ORM modules, like SQLAlchemy that provide a much higher-level abstraction layer. They still require the lower-level DB-API modules, though.
Note, as of 2.5, the Python standard library does include an SQLite3 DB-API, i.e. batteries included.
A:
Well...DBAPI is that frontend:
This API has been defined to encourage similarity between the
Python modules that are used to access databases. By doing this,
we hope to achieve a consistency leading to more easily understood
modules, code that is generally more portable across databases,
and a broader reach of database connectivity from Python.
It has always worked great for me atleast, care to elaborate the problems you are facing?
|
Python universal database interface?
|
Does there exist, or is there an intention to create, a universal database frontend for Python like Perl's DBI? I am aware of Python's DB-API, but all the separate packages are leaving me somewhat aggravated.
|
[
"AFAIK there is no one Python module that implements the DB-API to multiple databases and that's pretty much by design: why bring in unneeded functionality and possibly require the underlying database libraries to be installed if you are not going to use them? You can argue with that design decision but that's the way it is. On the other hand, the DB-API attempts to ensure that the API presented by the individual DB adapters is the same (or very close to the same). And then there are ORM modules, like SQLAlchemy that provide a much higher-level abstraction layer. They still require the lower-level DB-API modules, though.\nNote, as of 2.5, the Python standard library does include an SQLite3 DB-API, i.e. batteries included.\n",
"Well...DBAPI is that frontend:\n\nThis API has been defined to encourage similarity between the\n Python modules that are used to access databases. By doing this,\n we hope to achieve a consistency leading to more easily understood\n modules, code that is generally more portable across databases,\n and a broader reach of database connectivity from Python.\n\nIt has always worked great for me atleast, care to elaborate the problems you are facing?\n"
] |
[
3,
2
] |
[] |
[] |
[
"database",
"python"
] |
stackoverflow_0001836061_database_python.txt
|
Q:
Is close() necessary when using iterator on a Python file object
Is it bad practice to do the following and not explicitly handle a file object and call its close() method?
for line in open('hello.txt'):
print line
NB - this is for versions of Python that do not yet have the with statement.
I ask as the Python documentation seems to recommend this :-
f = open("hello.txt")
try:
for line in f:
print line
finally:
f.close()
Which seems more verbose than necessary.
A:
Close is always necessary when dealing with files, it is not a good idea to leave open file handles all over the place. They will eventually be closed when the file object is garbage collected but you do not know when that will be and in the mean time you will be wasting system resources by holding to file handles you no longer need.
If you are using Python 2.5 and higher the close() can be called for you automatically using the with statement:
from __future__ import with_statement # Only needed in Python 2.5
with open("hello.txt") as f:
for line in f:
print line
This is has the same effect as the code you have:
f = open("hello.txt")
try:
for line in f:
print line
finally:
f.close()
The with statement is direct language support for the Resource Acquisition Is Initialization idiom commonly used in C++. It allows the safe use and clean up of all sorts of resources, for example it can be used to always ensure that database connections are closed or locks are always released like below.
mylock = threading.Lock()
with mylock:
pass # do some thread safe stuff
A:
Actually, the file will be closed when it is garbage collected. See this question for more on how that works.
It is still recommended that you use a try/finally block or a with statement though. If there is an exception when using one of the file object's methods, a reference will be stored in the traceback (which is stored as a global variable) until you clear it or another exception occurs.
Thus, it's bad to rely on garbage collection to close your file for you.
Also, if you've written to the file, you can't guarantee that the changes will be saved to the file until it is closed or flushed.
A:
Strange that for all the discussion in this topic of the importance of freeing system resources, nobody has mentioned what seems to me an obviously more significant reason to close a file deterministically: so that it can be opened again.
There are certainly cases where it doesn't matter. If a file object goes out of scope or gets deleted, the underlying file will get closed. (When it gets closed depends on the specific implementation of Python you're using.) That's generally going to be good enough - if you know exactly when the file variable is going to go out of scope, and if you know that you don't care if the file gets closed deterministically.
But why should you even be troubling yourself with that kind of analysis when the with statement exists?
A:
It's kind of hinted at all over the place, but to make it the most clear, yes, you need to close that file. In Python 2.5 (using future) and in Python 2.6, you no longer need the wordy version:
from __future__ import with_statement
with open("hello.txt") as f:
for line in f:
print line
A:
Upon exit the Python interpreter (or the kernel in the event of a crash) will close the file, but it's still a good practice to close them when you don't need them. For 1 or 2, or 10, files it might not be a problem, but for more it might bring the whole system down.
Most importantly, it is a sign that the person who wrote the code actually cares about his work.
A:
No, I don't believe the longer idiom is necessary, and here is why:
I grepped /usr/lib/python2.6/ for the pattern 'for\s+.*\s+in\s+open\('
and found many examples of
for line in open('hello.txt'):
print line
and so far zero instances of
f = open("hello.txt")
try:
for line in f:
print line
finally:
f.close()
See below for the list of files in the standard library that use the for ... in open idiom.
This naturally leads to the question: If the Python developers accept the shorter idiom in
the standard libraries, how can we be improving anything by using something
different in our own code if our code depends on standard libraries?
I think the answer is, the longer idiom does not improve anything.
I also ran
#!/usr/bin/env python
try:
for i,line in enumerate(open('a')):
print line
raw_input()
if i==5:
break
except Exception:
pass
raw_input()
and checked /proc/PID/fd for when the file descriptor was closed.
It appears that when you break out of the for loop, the file is closed for you.
On the basis of these experiments, I do not believe the long
try...finally...close idiom is necessary.
Here is the result of the grep:
/usr/lib/python2.6/dist-packages/NvidiaDetector/nvidiadetector.py:89:tempList = [ x.strip() for x in open(obsolete).readlines() ]
/usr/lib/python2.6/dist-packages/rpy_io.py:49:for line in open(file).readlines():
/usr/lib/python2.6/dist-packages/setuptools/command/easy_install.py:1376:for line in open(self.filename,'rt'):
/usr/lib/python2.6/dist-packages/GDebi/DscSrcPackage.py:47:for line in open(file):
/usr/lib/python2.6/dist-packages/aptsources/distinfo.py:220:[x.strip() for x in open(value)])
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeCache.py:989:for line in open("/proc/mounts"):
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeAufs.py:100:for line in open("/proc/mounts"):
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeAufs.py:205:for line in open("/proc/mounts"):
/usr/lib/python2.6/dist-packages/DistUpgrade/distinfo.py:220:[x.strip() for x in open(value)])
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeViewKDE.py:826:for c in open(sys.argv[2]).read():
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeConfigParser.py:45:items = [x.strip() for x in open(p)]
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:684:for line in open(cpuinfo):
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:692:for line in open("/proc/mounts"):
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:726:for line in open("/etc/fstab"):
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:762:for line in open(fstab):
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:801:for line in open("/etc/fstab"):
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:874:for line in open(XORG):
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:939:for line in open(os.path.join(modaliasesdir,filename)):
/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeController.py:1307:for line in open(template):
/usr/lib/python2.6/dist-packages/DistUpgrade/xorg_fix_proprietary.py:23:for raw in open(xorg_source):
/usr/lib/python2.6/dist-packages/DistUpgrade/xorg_fix_proprietary.py:58:for line in open(xorg):
/usr/lib/python2.6/dist-packages/DistUpgrade/xorg_fix_proprietary.py:82:for line in open(xorg):
/usr/lib/python2.6/dist-packages/jockey/oslib.py:377:for line in open(self.apt_jockey_source):
/usr/lib/python2.6/dist-packages/jockey/oslib.py:393:for line in open(f):
/usr/lib/python2.6/dist-packages/jockey/backend.py:651:for line in open(path):
/usr/lib/python2.6/dist-packages/jockey/detection.py:277:for line in open(alias_file):
/usr/lib/python2.6/dist-packages/jockey/detection.py:597:for l in open(os.path.join(path, 'uevent')):
/usr/lib/python2.6/dist-packages/apt/cdrom.py:83:for line in open(fname):
/usr/lib/python2.6/dist-packages/problem_report.py:1119:for line in open('/proc/mounts'):
/usr/lib/python2.6/dist-packages/apport/packaging_impl.py:128:for line in open(f):
/usr/lib/python2.6/dist-packages/apport/packaging_impl.py:190:for line in open(sumfile):
/usr/lib/python2.6/dist-packages/apport/packaging_impl.py:641:for l in open('/etc/apt/sources.list'):
/usr/lib/python2.6/dist-packages/apport/hookutils.py:190:for line in open('/proc/asound/cards'):
/usr/lib/python2.6/dist-packages/apport/hookutils.py:290:for line in open('/var/log/syslog'):
/usr/lib/python2.6/dist-packages/apport/hookutils.py:493:mods = [l.split()[0] for l in open(module_list)]
/usr/lib/python2.6/dist-packages/softwareproperties/SoftwareProperties.py:597:for line in open(f):
/usr/lib/python2.6/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py:883:for x in open(tmp.name):
/usr/lib/python2.6/dist-packages/lsb_release.py:253:for line in open('/etc/lsb-release'):
/usr/lib/python2.6/dist-packages/numpy/distutils/system_info.py:815:for d in open(ld_so_conf,'r').readlines():
/usr/lib/python2.6/dist-packages/LanguageSelector/LocaleInfo.py:72:for line in open(languagelist_file):
/usr/lib/python2.6/dist-packages/LanguageSelector/LocaleInfo.py:187:for line in open(environment).readlines():
/usr/lib/python2.6/dist-packages/LanguageSelector/LocaleInfo.py:193:for line in open(environment).readlines():
/usr/lib/python2.6/dist-packages/LanguageSelector/LanguageSelector.py:125:for line in open(fname):
/usr/lib/python2.6/dist-packages/LanguageSelector/LanguageSelector.py:140:for line in open(fname):
/usr/lib/python2.6/dist-packages/LanguageSelector/LanguageSelector.py:171:for line in open(fname):
/usr/lib/python2.6/dist-packages/LanguageSelector/LanguageSelector.py:210:for line in open(fname):
/usr/lib/python2.6/dist-packages/LanguageSelector/macros.py:16:for l in open(file):
/usr/lib/python2.6/dist-packages/LanguageSelector/macros.py:37:for l in open(self.LANGCODE_TO_LOCALE):
/usr/lib/python2.6/dist-packages/LanguageSelector/LangCache.py:94:for l in open(self.BLACKLIST):
/usr/lib/python2.6/dist-packages/LanguageSelector/LangCache.py:99:for l in open(self.LANGCODE_TO_LOCALE):
/usr/lib/python2.6/dist-packages/LanguageSelector/LangCache.py:111:for l in open(self.PACKAGE_DEPENDS):
/usr/lib/python2.6/dist-packages/LanguageSelector/ImSwitch.py:78:for l in open(self.blacklist_file):
A:
Yes, because otherwise you might leak resources.
From the Python docs:
When youβre done with a file, call f.close() to close it and free up any system resources taken up by the open file.
This will happen for you when the program exits, but otherwise Python is keeping around resources it no longer needs up to that point.
A:
You need to close handles so that memory is freed up. Not really needed until dealing with a lot of files at a time.
|
Is close() necessary when using iterator on a Python file object
|
Is it bad practice to do the following and not explicitly handle a file object and call its close() method?
for line in open('hello.txt'):
print line
NB - this is for versions of Python that do not yet have the with statement.
I ask as the Python documentation seems to recommend this :-
f = open("hello.txt")
try:
for line in f:
print line
finally:
f.close()
Which seems more verbose than necessary.
|
[
"Close is always necessary when dealing with files, it is not a good idea to leave open file handles all over the place. They will eventually be closed when the file object is garbage collected but you do not know when that will be and in the mean time you will be wasting system resources by holding to file handles you no longer need.\nIf you are using Python 2.5 and higher the close() can be called for you automatically using the with statement:\nfrom __future__ import with_statement # Only needed in Python 2.5\nwith open(\"hello.txt\") as f:\n for line in f:\n print line\n\nThis is has the same effect as the code you have:\nf = open(\"hello.txt\")\ntry:\n for line in f:\n print line\nfinally:\n f.close()\n\nThe with statement is direct language support for the Resource Acquisition Is Initialization idiom commonly used in C++. It allows the safe use and clean up of all sorts of resources, for example it can be used to always ensure that database connections are closed or locks are always released like below.\nmylock = threading.Lock()\nwith mylock:\n pass # do some thread safe stuff\n\n",
"Actually, the file will be closed when it is garbage collected. See this question for more on how that works. \nIt is still recommended that you use a try/finally block or a with statement though. If there is an exception when using one of the file object's methods, a reference will be stored in the traceback (which is stored as a global variable) until you clear it or another exception occurs. \nThus, it's bad to rely on garbage collection to close your file for you.\nAlso, if you've written to the file, you can't guarantee that the changes will be saved to the file until it is closed or flushed.\n",
"Strange that for all the discussion in this topic of the importance of freeing system resources, nobody has mentioned what seems to me an obviously more significant reason to close a file deterministically: so that it can be opened again.\nThere are certainly cases where it doesn't matter. If a file object goes out of scope or gets deleted, the underlying file will get closed. (When it gets closed depends on the specific implementation of Python you're using.) That's generally going to be good enough - if you know exactly when the file variable is going to go out of scope, and if you know that you don't care if the file gets closed deterministically.\nBut why should you even be troubling yourself with that kind of analysis when the with statement exists?\n",
"It's kind of hinted at all over the place, but to make it the most clear, yes, you need to close that file. In Python 2.5 (using future) and in Python 2.6, you no longer need the wordy version:\nfrom __future__ import with_statement\nwith open(\"hello.txt\") as f:\n for line in f:\n print line\n\n",
"Upon exit the Python interpreter (or the kernel in the event of a crash) will close the file, but it's still a good practice to close them when you don't need them. For 1 or 2, or 10, files it might not be a problem, but for more it might bring the whole system down.\nMost importantly, it is a sign that the person who wrote the code actually cares about his work.\n",
"No, I don't believe the longer idiom is necessary, and here is why:\nI grepped /usr/lib/python2.6/ for the pattern 'for\\s+.*\\s+in\\s+open\\('\nand found many examples of \nfor line in open('hello.txt'):\n print line\n\nand so far zero instances of \nf = open(\"hello.txt\")\ntry:\n for line in f:\n print line\nfinally:\n f.close()\n\nSee below for the list of files in the standard library that use the for ... in open idiom.\nThis naturally leads to the question: If the Python developers accept the shorter idiom in\nthe standard libraries, how can we be improving anything by using something\ndifferent in our own code if our code depends on standard libraries?\nI think the answer is, the longer idiom does not improve anything.\nI also ran \n#!/usr/bin/env python\ntry:\n for i,line in enumerate(open('a')):\n print line\n raw_input()\n if i==5:\n break\nexcept Exception:\n pass\n\nraw_input()\n\nand checked /proc/PID/fd for when the file descriptor was closed. \nIt appears that when you break out of the for loop, the file is closed for you.\nOn the basis of these experiments, I do not believe the long \ntry...finally...close idiom is necessary. \nHere is the result of the grep:\n/usr/lib/python2.6/dist-packages/NvidiaDetector/nvidiadetector.py:89:tempList = [ x.strip() for x in open(obsolete).readlines() ]\n/usr/lib/python2.6/dist-packages/rpy_io.py:49:for line in open(file).readlines():\n/usr/lib/python2.6/dist-packages/setuptools/command/easy_install.py:1376:for line in open(self.filename,'rt'):\n/usr/lib/python2.6/dist-packages/GDebi/DscSrcPackage.py:47:for line in open(file):\n/usr/lib/python2.6/dist-packages/aptsources/distinfo.py:220:[x.strip() for x in open(value)])\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeCache.py:989:for line in open(\"/proc/mounts\"):\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeAufs.py:100:for line in open(\"/proc/mounts\"):\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeAufs.py:205:for line in open(\"/proc/mounts\"):\n/usr/lib/python2.6/dist-packages/DistUpgrade/distinfo.py:220:[x.strip() for x in open(value)])\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeViewKDE.py:826:for c in open(sys.argv[2]).read():\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeConfigParser.py:45:items = [x.strip() for x in open(p)]\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:684:for line in open(cpuinfo):\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:692:for line in open(\"/proc/mounts\"):\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:726:for line in open(\"/etc/fstab\"):\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:762:for line in open(fstab):\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:801:for line in open(\"/etc/fstab\"):\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:874:for line in open(XORG):\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeQuirks.py:939:for line in open(os.path.join(modaliasesdir,filename)):\n/usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeController.py:1307:for line in open(template):\n/usr/lib/python2.6/dist-packages/DistUpgrade/xorg_fix_proprietary.py:23:for raw in open(xorg_source):\n/usr/lib/python2.6/dist-packages/DistUpgrade/xorg_fix_proprietary.py:58:for line in open(xorg):\n/usr/lib/python2.6/dist-packages/DistUpgrade/xorg_fix_proprietary.py:82:for line in open(xorg):\n/usr/lib/python2.6/dist-packages/jockey/oslib.py:377:for line in open(self.apt_jockey_source):\n/usr/lib/python2.6/dist-packages/jockey/oslib.py:393:for line in open(f):\n/usr/lib/python2.6/dist-packages/jockey/backend.py:651:for line in open(path):\n/usr/lib/python2.6/dist-packages/jockey/detection.py:277:for line in open(alias_file):\n/usr/lib/python2.6/dist-packages/jockey/detection.py:597:for l in open(os.path.join(path, 'uevent')):\n/usr/lib/python2.6/dist-packages/apt/cdrom.py:83:for line in open(fname):\n/usr/lib/python2.6/dist-packages/problem_report.py:1119:for line in open('/proc/mounts'):\n/usr/lib/python2.6/dist-packages/apport/packaging_impl.py:128:for line in open(f):\n/usr/lib/python2.6/dist-packages/apport/packaging_impl.py:190:for line in open(sumfile):\n/usr/lib/python2.6/dist-packages/apport/packaging_impl.py:641:for l in open('/etc/apt/sources.list'):\n/usr/lib/python2.6/dist-packages/apport/hookutils.py:190:for line in open('/proc/asound/cards'):\n/usr/lib/python2.6/dist-packages/apport/hookutils.py:290:for line in open('/var/log/syslog'):\n/usr/lib/python2.6/dist-packages/apport/hookutils.py:493:mods = [l.split()[0] for l in open(module_list)]\n/usr/lib/python2.6/dist-packages/softwareproperties/SoftwareProperties.py:597:for line in open(f):\n/usr/lib/python2.6/dist-packages/softwareproperties/gtk/SoftwarePropertiesGtk.py:883:for x in open(tmp.name):\n/usr/lib/python2.6/dist-packages/lsb_release.py:253:for line in open('/etc/lsb-release'):\n/usr/lib/python2.6/dist-packages/numpy/distutils/system_info.py:815:for d in open(ld_so_conf,'r').readlines():\n/usr/lib/python2.6/dist-packages/LanguageSelector/LocaleInfo.py:72:for line in open(languagelist_file):\n/usr/lib/python2.6/dist-packages/LanguageSelector/LocaleInfo.py:187:for line in open(environment).readlines():\n/usr/lib/python2.6/dist-packages/LanguageSelector/LocaleInfo.py:193:for line in open(environment).readlines():\n/usr/lib/python2.6/dist-packages/LanguageSelector/LanguageSelector.py:125:for line in open(fname):\n/usr/lib/python2.6/dist-packages/LanguageSelector/LanguageSelector.py:140:for line in open(fname):\n/usr/lib/python2.6/dist-packages/LanguageSelector/LanguageSelector.py:171:for line in open(fname):\n/usr/lib/python2.6/dist-packages/LanguageSelector/LanguageSelector.py:210:for line in open(fname):\n/usr/lib/python2.6/dist-packages/LanguageSelector/macros.py:16:for l in open(file):\n/usr/lib/python2.6/dist-packages/LanguageSelector/macros.py:37:for l in open(self.LANGCODE_TO_LOCALE):\n/usr/lib/python2.6/dist-packages/LanguageSelector/LangCache.py:94:for l in open(self.BLACKLIST):\n/usr/lib/python2.6/dist-packages/LanguageSelector/LangCache.py:99:for l in open(self.LANGCODE_TO_LOCALE):\n/usr/lib/python2.6/dist-packages/LanguageSelector/LangCache.py:111:for l in open(self.PACKAGE_DEPENDS):\n/usr/lib/python2.6/dist-packages/LanguageSelector/ImSwitch.py:78:for l in open(self.blacklist_file):\n\n",
"Yes, because otherwise you might leak resources.\nFrom the Python docs:\n\nWhen youβre done with a file, call f.close() to close it and free up any system resources taken up by the open file.\n\nThis will happen for you when the program exits, but otherwise Python is keeping around resources it no longer needs up to that point.\n",
"You need to close handles so that memory is freed up. Not really needed until dealing with a lot of files at a time.\n"
] |
[
82,
21,
13,
7,
6,
5,
3,
2
] |
[] |
[] |
[
"file",
"iterator",
"python"
] |
stackoverflow_0001832528_file_iterator_python.txt
|
Q:
Python, PowerShell, or Other?
What are the advantages of Python, PowerShell, and other scripting environments? We would like to standardize our scripting and are currently using bat and cmd files as the standard. I think Python would be a better option than these, but am also researching PowerShell and other scripting tools.
The scripts would be used to trigger processes such as wget etc to call web services, or other applications/tools that need to run in a specific order with specific parameters.
We primarily work with the Windows stack, but there is a good chance we will need to support Unix in the future.
A:
Python works as a great, all-purpose tool if you're looking to replace CMD and BAT scripts on your Windows boxes, and can also be written to run scripts on your (L)inux boxes, too. It's a great, flexible language and can handle many tasks you throw at it.
That being said, PowerShell is an amazingly versatile tool for administering all manner of Windows boxes; it has all the power of .NET, with many more interfaces into MS products such as Exchange and Active Directory, which are a timesaver. Depending on your situation, you may get more use of of PS than other scripting languages just because of the interfaces available to MS products, and I know MS seems to have made a commitment to providing those APIs in a lot of products. PowerShell comes installed on all current versions of Windows (Windows 7+, Windows Server 2008+), and is fairly easily installed on older versions.
To address your edit that your scripts will be used to launch other processes, I think in that case either of the tools fit the bill. I would recommend PS if you plan on adding any admin-ish tasks to the scripts rather than just service calls, but if you stick to what you described, Python is good.
A:
We would like to standardize our scripting and are currently using bat and cmd files as the standard.
It sounds like Windows is your predominate environment.
If so, PowerShell would be much better than Python.
PowerShell is included with Windows
Server 2008. No need to
deploy/install Python runtime on
every new server that rolls in.
The entire Microsoft server related software (Exchange, Systems Center, etc) is transitioning to PowerShell cmdlets for functionality and extensions
3rd party vendors (e.g. SCOM plugins) will also use PowerShell scripts/cmdlets to expose functionality
I have more experience with Python than PowerShell but the writing is on the wall as far as the Microsoft ecosystem is concerned: go with PowerShell. Otherwise, you'll just be going against the grain and constantly interop-ing between Python and everyone else's cmdlets.
Just because you can code import win32com.client in Python does not put it on equal footing with PowerShell in the Windows environment.
A:
IronPython has access to all of the same .NET assemblies as any other .NET language for writing system dependent scripts on Windows. But the same knowledge of Python can be used to write similar scripts on Linux, Solaris, BSD, or OS/X. If you use the standard C Python on Windows, then you can access any COM objects and it is straightforward to translate VBA examples into Python code. The SPAMBayes Outlook plugin is a good example of how far you can go with that. http://spambayes.sourceforge.net/
Python's best feature is the "batteries included" standard library, and even though this is not distributed with IronPython, much of it will work if you just point IronPython to the installed library folder from CPython. In fact, most pure Python libraries, i.e. no compiled C or C++ modules, will work fine with IronPython. On Windows, you also have the choice of installing Python through Cygwin.com which then allows you to use a lot of modules that are normally considered UNIX-only. This can be of use if you have to maintain cross-platform scripts and you prefer consistency rather than special case coding for each OS.
And if you should need to leverage some Java classes, then Jython allows you to use the same Python language that you know to leverage this. Combine this with a nice message queuing system like RabbitMQ, and you can have Python, Jython and IronPython scripts on multiple machines all cooperating in getting the job done.
There is also a huge selection of 3rd party Python modules out there and you could spend several months trawling through delicious.com before you run out of new discoveries. This means that when you need something not part of standard Python libraries, a bit of Googling often comes up with a solution.
Some useful Python modules for scripting to replace bash, CMD and BAT files are PEXPECT http://www.noah.org/wiki/Pexpect and Python WMI http://timgolden.me.uk/python/wmi/index.html
But, in the end, Python also works just fine for simple straightforward scripts that don't need any special features... yet!
A:
If all you do is spawning a lot of system specific programs with no or little programming logic behind then OS specific shell might be a better choice than a full general purpose programming language.
A:
The questions is kind of vague, but Python is much more portable than PowerShell; however, Python isn't that prevalent on Windows. But on the other hand, I don't believe PowerShell scripts will work on a Windows machine that doesn't have PowerShell. Meaning they may not work in the old fashioned cmd shell. I think you'll find more documentation and libraries for Python as well.
PowerShell is more like Bash than it is a programming language like Python.
Maybe you could explain what you want to do with your scripts and you'll probably get better answers.
A:
One advantage to Python is the availability of third-party libraries and an extensive built-in standard library. You can do a lot of powerful operations quickly and easily with Python on a variety of operating systems and environments. That's one reason we use Python here at the office not only as a scripting language but for all of our database backend applications as well.
We also use it for XML and HTML scraping, using ElementTree and BeautifulSoup, which are very powerful and flexible Python-specific libraries for this sort of work.
A:
I find it sad no one yet mentioend good ol' Perl.
A:
If you are working with web based scripting, then ActiveState's ActivePython seems to have a lot of support for Windows specific API's that would suit you and it has tons of great portable libraries for doing web based work.
|
Python, PowerShell, or Other?
|
What are the advantages of Python, PowerShell, and other scripting environments? We would like to standardize our scripting and are currently using bat and cmd files as the standard. I think Python would be a better option than these, but am also researching PowerShell and other scripting tools.
The scripts would be used to trigger processes such as wget etc to call web services, or other applications/tools that need to run in a specific order with specific parameters.
We primarily work with the Windows stack, but there is a good chance we will need to support Unix in the future.
|
[
"Python works as a great, all-purpose tool if you're looking to replace CMD and BAT scripts on your Windows boxes, and can also be written to run scripts on your (L)inux boxes, too. It's a great, flexible language and can handle many tasks you throw at it.\nThat being said, PowerShell is an amazingly versatile tool for administering all manner of Windows boxes; it has all the power of .NET, with many more interfaces into MS products such as Exchange and Active Directory, which are a timesaver. Depending on your situation, you may get more use of of PS than other scripting languages just because of the interfaces available to MS products, and I know MS seems to have made a commitment to providing those APIs in a lot of products. PowerShell comes installed on all current versions of Windows (Windows 7+, Windows Server 2008+), and is fairly easily installed on older versions.\nTo address your edit that your scripts will be used to launch other processes, I think in that case either of the tools fit the bill. I would recommend PS if you plan on adding any admin-ish tasks to the scripts rather than just service calls, but if you stick to what you described, Python is good.\n",
"\nWe would like to standardize our scripting and are currently using bat and cmd files as the standard.\n\nIt sounds like Windows is your predominate environment.\nIf so, PowerShell would be much better than Python. \n\nPowerShell is included with Windows\nServer 2008. No need to\ndeploy/install Python runtime on\nevery new server that rolls in.\nThe entire Microsoft server related software (Exchange, Systems Center, etc) is transitioning to PowerShell cmdlets for functionality and extensions\n3rd party vendors (e.g. SCOM plugins) will also use PowerShell scripts/cmdlets to expose functionality\n\nI have more experience with Python than PowerShell but the writing is on the wall as far as the Microsoft ecosystem is concerned: go with PowerShell. Otherwise, you'll just be going against the grain and constantly interop-ing between Python and everyone else's cmdlets.\nJust because you can code import win32com.client in Python does not put it on equal footing with PowerShell in the Windows environment.\n",
"IronPython has access to all of the same .NET assemblies as any other .NET language for writing system dependent scripts on Windows. But the same knowledge of Python can be used to write similar scripts on Linux, Solaris, BSD, or OS/X. If you use the standard C Python on Windows, then you can access any COM objects and it is straightforward to translate VBA examples into Python code. The SPAMBayes Outlook plugin is a good example of how far you can go with that. http://spambayes.sourceforge.net/ \nPython's best feature is the \"batteries included\" standard library, and even though this is not distributed with IronPython, much of it will work if you just point IronPython to the installed library folder from CPython. In fact, most pure Python libraries, i.e. no compiled C or C++ modules, will work fine with IronPython. On Windows, you also have the choice of installing Python through Cygwin.com which then allows you to use a lot of modules that are normally considered UNIX-only. This can be of use if you have to maintain cross-platform scripts and you prefer consistency rather than special case coding for each OS.\nAnd if you should need to leverage some Java classes, then Jython allows you to use the same Python language that you know to leverage this. Combine this with a nice message queuing system like RabbitMQ, and you can have Python, Jython and IronPython scripts on multiple machines all cooperating in getting the job done.\nThere is also a huge selection of 3rd party Python modules out there and you could spend several months trawling through delicious.com before you run out of new discoveries. This means that when you need something not part of standard Python libraries, a bit of Googling often comes up with a solution. \nSome useful Python modules for scripting to replace bash, CMD and BAT files are PEXPECT http://www.noah.org/wiki/Pexpect and Python WMI http://timgolden.me.uk/python/wmi/index.html\nBut, in the end, Python also works just fine for simple straightforward scripts that don't need any special features... yet!\n",
"If all you do is spawning a lot of system specific programs with no or little programming logic behind then OS specific shell might be a better choice than a full general purpose programming language.\n",
"The questions is kind of vague, but Python is much more portable than PowerShell; however, Python isn't that prevalent on Windows. But on the other hand, I don't believe PowerShell scripts will work on a Windows machine that doesn't have PowerShell. Meaning they may not work in the old fashioned cmd shell. I think you'll find more documentation and libraries for Python as well.\nPowerShell is more like Bash than it is a programming language like Python.\nMaybe you could explain what you want to do with your scripts and you'll probably get better answers.\n",
"One advantage to Python is the availability of third-party libraries and an extensive built-in standard library. You can do a lot of powerful operations quickly and easily with Python on a variety of operating systems and environments. That's one reason we use Python here at the office not only as a scripting language but for all of our database backend applications as well.\nWe also use it for XML and HTML scraping, using ElementTree and BeautifulSoup, which are very powerful and flexible Python-specific libraries for this sort of work.\n",
"I find it sad no one yet mentioend good ol' Perl. \n",
"If you are working with web based scripting, then ActiveState's ActivePython seems to have a lot of support for Windows specific API's that would suit you and it has tons of great portable libraries for doing web based work.\n"
] |
[
46,
20,
15,
3,
2,
2,
2,
1
] |
[] |
[] |
[
"powershell",
"python",
"scripting"
] |
stackoverflow_0001834850_powershell_python_scripting.txt
|
Q:
Subprocess Popen and PIPE in Python
The following code prints an empty line as an output which is false.
The problem is not in the permissions, since I tested the command with 777 permissions for the pdf -file. How can you fix the command to give a right output?
import subprocess
from subprocess import PIPE, Popen
output = Popen(['pdftotext', '/home/aal/Desktop/lkn_pdf/appa.pdf'], stdout=PIPE).communicate()[0]
A:
pdftotext creates a file by default. To send the result to standard output, use:
pdftotext file.pdf -
or in Python:
output = Popen(['pdftotext', '/home/aal/Desktop/lkn_pdf/appa.pdf', '-'], stdout=PIPE).communicate()[0]
|
Subprocess Popen and PIPE in Python
|
The following code prints an empty line as an output which is false.
The problem is not in the permissions, since I tested the command with 777 permissions for the pdf -file. How can you fix the command to give a right output?
import subprocess
from subprocess import PIPE, Popen
output = Popen(['pdftotext', '/home/aal/Desktop/lkn_pdf/appa.pdf'], stdout=PIPE).communicate()[0]
|
[
"pdftotext creates a file by default. To send the result to standard output, use:\npdftotext file.pdf -\n\nor in Python:\noutput = Popen(['pdftotext', '/home/aal/Desktop/lkn_pdf/appa.pdf', '-'], stdout=PIPE).communicate()[0]\n\n"
] |
[
6
] |
[] |
[] |
[
"pipe",
"popen",
"python",
"subprocess"
] |
stackoverflow_0001836588_pipe_popen_python_subprocess.txt
|
Q:
Can I remove leading zeros in a url in django?
Am redirecting urls from a legacy site, which gets me to a url like this:
http://example.com/blog/01/detail
I would like to automatically remove the leading zeros from these urls (seems it doesn't matter how many zeros are in there 001 0001 000001 work) so that the page redirects to:
http://example.com/blog/1/detail
Is there a simple way to go about doing this in django ? (Or, via the .htaccess redirect?)
URL code:
url(u'^blog/(?P<object_id>\d+)/detail$',
list_detail.object_detail,
{ 'queryset' : Blog.objects.all(), },
name='blog_detail',)
.htaccess (being redirected):
RewriteRule ^blog-([0-9]+) http://example.com/blog/$1 [R=301]
Would I need some middleware or is there an easy way to do this in the urls.py file ?
A:
You can fix it by eiditing either the urls.py regex or the .htaccess regex:
In Django
'^blog/0*(?P<object_id>\d+)/detail$'
In .htaccess
RewriteRule ^blog-0*([0-9]+) http://example.com/blog/$1 [R=301]
A:
Perhaps
url(u'^blog/0*(?P<object_id>\d+)/detail$',
list_detail.object_detail,
{ 'queryset' : Blog.objects.all(), },
name='blog_detail',)
|
Can I remove leading zeros in a url in django?
|
Am redirecting urls from a legacy site, which gets me to a url like this:
http://example.com/blog/01/detail
I would like to automatically remove the leading zeros from these urls (seems it doesn't matter how many zeros are in there 001 0001 000001 work) so that the page redirects to:
http://example.com/blog/1/detail
Is there a simple way to go about doing this in django ? (Or, via the .htaccess redirect?)
URL code:
url(u'^blog/(?P<object_id>\d+)/detail$',
list_detail.object_detail,
{ 'queryset' : Blog.objects.all(), },
name='blog_detail',)
.htaccess (being redirected):
RewriteRule ^blog-([0-9]+) http://example.com/blog/$1 [R=301]
Would I need some middleware or is there an easy way to do this in the urls.py file ?
|
[
"You can fix it by eiditing either the urls.py regex or the .htaccess regex:\nIn Django\n'^blog/0*(?P<object_id>\\d+)/detail$'\n\nIn .htaccess\nRewriteRule ^blog-0*([0-9]+) http://example.com/blog/$1 [R=301]\n\n",
"Perhaps\nurl(u'^blog/0*(?P<object_id>\\d+)/detail$', \n list_detail.object_detail,\n { 'queryset' : Blog.objects.all(), },\n name='blog_detail',)\n\n"
] |
[
3,
1
] |
[] |
[] |
[
".htaccess",
"django",
"python"
] |
stackoverflow_0001836721_.htaccess_django_python.txt
|
Q:
Need a zip of Python 2.6 for windows
Not the source codes, thats the only thing i seem to find. I can't install py2.6 because it would overtake 2.5 and cause mayor mess in my pc.
A:
How would it overtake 2.5? You can install both in parallel, just make sure that you unselect the option to "Register Extensions" during the install of 2.6.
I have several Python installations on my PC in parallel, one of them my "standard" one that I expect to run when I doubleclick on a .py file, and the other one to invoke manually if I need it.
I have found, though, that sometimes file associations are lost completely after installing a new version without the "Register Extensions" option set. In that case just run a "repair installation" with your preferred standard version, and you should be good to go.
A:
I have Pythons 2.3, 2.4, 2.5, 2.6, and 3.1 all installed on my PC. Download the .msi from python.org, and install it.
|
Need a zip of Python 2.6 for windows
|
Not the source codes, thats the only thing i seem to find. I can't install py2.6 because it would overtake 2.5 and cause mayor mess in my pc.
|
[
"How would it overtake 2.5? You can install both in parallel, just make sure that you unselect the option to \"Register Extensions\" during the install of 2.6.\nI have several Python installations on my PC in parallel, one of them my \"standard\" one that I expect to run when I doubleclick on a .py file, and the other one to invoke manually if I need it.\nI have found, though, that sometimes file associations are lost completely after installing a new version without the \"Register Extensions\" option set. In that case just run a \"repair installation\" with your preferred standard version, and you should be good to go.\n",
"I have Pythons 2.3, 2.4, 2.5, 2.6, and 3.1 all installed on my PC. Download the .msi from python.org, and install it.\n"
] |
[
8,
2
] |
[] |
[] |
[
"python",
"zip"
] |
stackoverflow_0001835930_python_zip.txt
|
Q:
How do ldexp and frexp work in python?
The python frexp and ldexp functions splits floats into mantissa and exponent.
Do anybody know if this process exposes the actual float structure, or if it requires python to do expensive logarithmic calls?
A:
Python 2.6's math.frexp just calls the underlying C library frexp directly. We must assume that the C library simply uses the float representation's parts directly instead of calculating if avaliable (IEEE 754).
static PyObject *
math_frexp(PyObject *self, PyObject *arg)
{
int i;
double x = PyFloat_AsDouble(arg);
if (x == -1.0 && PyErr_Occurred())
return NULL;
/* deal with special cases directly, to sidestep platform
differences */
if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
i = 0;
}
else {
PyFPE_START_PROTECT("in math_frexp", return 0);
x = frexp(x, &i);
PyFPE_END_PROTECT(x);
}
return Py_BuildValue("(di)", x, i);
}
PyDoc_STRVAR(math_frexp_doc,
"frexp(x)\n"
"\n"
"Return the mantissa and exponent of x, as pair (m, e).\n"
"m is a float and e is an int, such that x = m * 2.**e.\n"
"If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.");
A:
As for speed, here is a quick comparison
$ python -m timeit -c 'from math import frexp' 'frexp(1.1)'
100000 loops, best of 3: 3.7 usec per loop
$ python -m timeit -c 'from math import log' 'log(1.1)'
100000 loops, best of 3: 3.7 usec per loop
$ python -m timeit -c 'from math import ldexp' 'ldexp(1.1,2)'
100000 loops, best of 3: 3.5 usec per loop
So there isn't a lot of difference detectable in python between frexp, log and ldexp in terms of speed. Not sure that tells you anything about the implementation though!
A:
This is a question you can easily answer yourself:
$ python
>>> import math
>>> help(math.frexp)
Help on built-in function frexp in module math:
Notice the built-in. It's in C.
>>> import urllib
>>> help(urllib.urlopen)
Help on function urlopen in module urllib:
No built-in here. It's in Python.
|
How do ldexp and frexp work in python?
|
The python frexp and ldexp functions splits floats into mantissa and exponent.
Do anybody know if this process exposes the actual float structure, or if it requires python to do expensive logarithmic calls?
|
[
"Python 2.6's math.frexp just calls the underlying C library frexp directly. We must assume that the C library simply uses the float representation's parts directly instead of calculating if avaliable (IEEE 754).\nstatic PyObject *\nmath_frexp(PyObject *self, PyObject *arg)\n{\n int i;\n double x = PyFloat_AsDouble(arg);\n if (x == -1.0 && PyErr_Occurred())\n return NULL;\n /* deal with special cases directly, to sidestep platform\n differences */\n if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {\n i = 0;\n }\n else { \n PyFPE_START_PROTECT(\"in math_frexp\", return 0);\n x = frexp(x, &i);\n PyFPE_END_PROTECT(x);\n }\n return Py_BuildValue(\"(di)\", x, i);\n}\n\nPyDoc_STRVAR(math_frexp_doc,\n\"frexp(x)\\n\"\n\"\\n\"\n\"Return the mantissa and exponent of x, as pair (m, e).\\n\"\n\"m is a float and e is an int, such that x = m * 2.**e.\\n\"\n\"If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.\");\n\n",
"As for speed, here is a quick comparison\n$ python -m timeit -c 'from math import frexp' 'frexp(1.1)'\n100000 loops, best of 3: 3.7 usec per loop\n\n$ python -m timeit -c 'from math import log' 'log(1.1)'\n100000 loops, best of 3: 3.7 usec per loop\n\n$ python -m timeit -c 'from math import ldexp' 'ldexp(1.1,2)'\n100000 loops, best of 3: 3.5 usec per loop\n\nSo there isn't a lot of difference detectable in python between frexp, log and ldexp in terms of speed. Not sure that tells you anything about the implementation though! \n",
"This is a question you can easily answer yourself:\n$ python\n>>> import math\n>>> help(math.frexp)\nHelp on built-in function frexp in module math:\n\nNotice the built-in. It's in C.\n>>> import urllib\n>>> help(urllib.urlopen)\nHelp on function urlopen in module urllib:\n\nNo built-in here. It's in Python.\n"
] |
[
5,
1,
1
] |
[] |
[] |
[
"exponent",
"floating_point",
"ieee_754",
"mantissa",
"python"
] |
stackoverflow_0001834825_exponent_floating_point_ieee_754_mantissa_python.txt
|
Q:
Similarity Between Users Based On Votes
lets say i have a set of users, a set of songs, and a set of votes on each song:
=========== =========== =======
User Song Vote
=========== =========== =======
user1 song1 [score]
user1 song2 [score]
user1 song3 [score]
user2 song1 [score]
user2 song2 [score]
user2 song3 [score]
user3 song1 [score]
user3 song2 [score]
user3 song3 [score]
user-n song-n [score]
=========== =========== =======
whats the most efficient way to calculate user similarity based on song-votes? is there a better way than iterating over every user and every vote for every song?
A:
There are two common metrics that can be used to find similarities between users:
Euclidean Distance, that is exactly what you are thinking: imagine a n-dimensional graph that has for each axis a song that is reviewed by two involved users (u1 and *u2) and the value on its axis is the score. You can easily calculate similarity using the formula:
for every song reviewed by u1 and u2, calculate pow(u1.song.score - u2.song.score, 2) and add all together into sum_of_powers. Similarity coefficient is then given by 1 / 1 + (sqrt(sum_of_powers)).
Pearson Correlation (or correlation coefficient): it's a better approach that finds how much two data sets are related one with another. This approach uses more complex formulas and a little of statistics background, check it here: wiki. You will have a graph for every couple of users, then you plot points according to scores.. for example if aSong has been voted 2 from u1 and 4 from u2 it will plot the point (2,4) (assuming that user1 is x-axis and u2 is y-axis).
Just to clarify, you use linear regression to find two coefficients A and B, that describe the line that minimizes the distance from all the points of the graph. This line has this formula:y = Ax + B. If two sets are similar points should be near to the main diagonal so A should tend to 1 while B to 0. Don't assume this explaination as complete or as a reference because it lacks soundness and typical math formalism, it just to give you an idea.
EDIT:
like written by others, more complex algorithms to cluster data exist, like k-means but I suggest you to start from easy ones (actually you should need something more difficult just when you realize that results are not enough).
A:
I recommend the book Programming Collective Intelligence from Toby Segaran. Chapter 3 describes different clustering methods like Hierarchical Clustering and K-means Clustering.
The source code for the examples is available here
A:
If you want the most accurate results, then no, you'd have to iterate over everything.
If your database is large enough, you could just take a statistical sampling, say taking between 1,000 -10,000 users and matching against that.
You would also be better off to add some more tables to the database, store the results, and only update it every so often, instead of calculating this on the fly.
A:
Ilya Grigorik did a series on recommendation algorithms, though he was focusing on Ruby. It appears to be under the machine learning section in his archives, but there isn't a direct section link.
A:
I think a lot of people on here are missing the simplicity of the question. He didn't say anything about creating a rating prediction system. He just wants to compute the similarity between each user's song rating behavior and each other user's song rating behavior. The Pearson correlation coefficient gives exactly that. Yes, you must iterate over every user/user pair.
EDIT:
After thinking about this a little more:
Pearson is great if you want the similarity between two users' tastes, but not their level of "opinionatedness"... one user who rates a series of songs 4, 5, and 6 will correlate perfectly with another user who rates the same songs 3, 6, and 9. In other words, they have the same "taste" (they would rank the songs in the same order), but the second user is much more opinionated. In other other words, the correlation coefficient treats any two rating vectors with a linear relationship as equal.
However, if you want the similarity between the actual ratings the users gave each song, you should use the root mean squared error between the two rating vectors. This is a purely distance based metric (linear relationships do not play into the similarity score), so the 4,5,6 and 3,6,9 users would not have a perfect similarity score.
The decision comes down to what you mean by "similar"...
That is all.
A:
If you want to do it in a approximate way without visiting all the records, you can use the Jaccard Coefficient. Probably needs some adaptation if you want to consider the scores. But I guess that's the best solutions if your system is too big and you don't have the time to check all the records.
A:
You should be able to find a good algorithm in this book: The Algorithm Design Manual by Steven Skiena.
The book has a whole bunch of algorithms for various purposes. You want a graph clustering algorithm, I think. I don't have my copy of the book handy, so I can't look it up for you.
A quick Google search found a Wikipedia page: http://en.wikipedia.org/wiki/Cluster_analysis Perhaps that will help, but I think the book explains algorithms more clearly.
|
Similarity Between Users Based On Votes
|
lets say i have a set of users, a set of songs, and a set of votes on each song:
=========== =========== =======
User Song Vote
=========== =========== =======
user1 song1 [score]
user1 song2 [score]
user1 song3 [score]
user2 song1 [score]
user2 song2 [score]
user2 song3 [score]
user3 song1 [score]
user3 song2 [score]
user3 song3 [score]
user-n song-n [score]
=========== =========== =======
whats the most efficient way to calculate user similarity based on song-votes? is there a better way than iterating over every user and every vote for every song?
|
[
"There are two common metrics that can be used to find similarities between users:\n\nEuclidean Distance, that is exactly what you are thinking: imagine a n-dimensional graph that has for each axis a song that is reviewed by two involved users (u1 and *u2) and the value on its axis is the score. You can easily calculate similarity using the formula:\nfor every song reviewed by u1 and u2, calculate pow(u1.song.score - u2.song.score, 2) and add all together into sum_of_powers. Similarity coefficient is then given by 1 / 1 + (sqrt(sum_of_powers)).\nPearson Correlation (or correlation coefficient): it's a better approach that finds how much two data sets are related one with another. This approach uses more complex formulas and a little of statistics background, check it here: wiki. You will have a graph for every couple of users, then you plot points according to scores.. for example if aSong has been voted 2 from u1 and 4 from u2 it will plot the point (2,4) (assuming that user1 is x-axis and u2 is y-axis).\n\nJust to clarify, you use linear regression to find two coefficients A and B, that describe the line that minimizes the distance from all the points of the graph. This line has this formula:y = Ax + B. If two sets are similar points should be near to the main diagonal so A should tend to 1 while B to 0. Don't assume this explaination as complete or as a reference because it lacks soundness and typical math formalism, it just to give you an idea.\nEDIT:\nlike written by others, more complex algorithms to cluster data exist, like k-means but I suggest you to start from easy ones (actually you should need something more difficult just when you realize that results are not enough).\n",
"I recommend the book Programming Collective Intelligence from Toby Segaran. Chapter 3 describes different clustering methods like Hierarchical Clustering and K-means Clustering. \nThe source code for the examples is available here\n",
"If you want the most accurate results, then no, you'd have to iterate over everything.\nIf your database is large enough, you could just take a statistical sampling, say taking between 1,000 -10,000 users and matching against that.\nYou would also be better off to add some more tables to the database, store the results, and only update it every so often, instead of calculating this on the fly.\n",
"Ilya Grigorik did a series on recommendation algorithms, though he was focusing on Ruby. It appears to be under the machine learning section in his archives, but there isn't a direct section link.\n",
"I think a lot of people on here are missing the simplicity of the question. He didn't say anything about creating a rating prediction system. He just wants to compute the similarity between each user's song rating behavior and each other user's song rating behavior. The Pearson correlation coefficient gives exactly that. Yes, you must iterate over every user/user pair.\nEDIT:\nAfter thinking about this a little more:\nPearson is great if you want the similarity between two users' tastes, but not their level of \"opinionatedness\"... one user who rates a series of songs 4, 5, and 6 will correlate perfectly with another user who rates the same songs 3, 6, and 9. In other words, they have the same \"taste\" (they would rank the songs in the same order), but the second user is much more opinionated. In other other words, the correlation coefficient treats any two rating vectors with a linear relationship as equal.\nHowever, if you want the similarity between the actual ratings the users gave each song, you should use the root mean squared error between the two rating vectors. This is a purely distance based metric (linear relationships do not play into the similarity score), so the 4,5,6 and 3,6,9 users would not have a perfect similarity score.\nThe decision comes down to what you mean by \"similar\"...\nThat is all.\n",
"If you want to do it in a approximate way without visiting all the records, you can use the Jaccard Coefficient. Probably needs some adaptation if you want to consider the scores. But I guess that's the best solutions if your system is too big and you don't have the time to check all the records. \n",
"You should be able to find a good algorithm in this book: The Algorithm Design Manual by Steven Skiena.\nThe book has a whole bunch of algorithms for various purposes. You want a graph clustering algorithm, I think. I don't have my copy of the book handy, so I can't look it up for you.\nA quick Google search found a Wikipedia page: http://en.wikipedia.org/wiki/Cluster_analysis Perhaps that will help, but I think the book explains algorithms more clearly.\n"
] |
[
11,
5,
3,
1,
1,
1,
0
] |
[] |
[] |
[
"database",
"information_retrieval",
"mysql",
"python",
"similarity"
] |
stackoverflow_0001836352_database_information_retrieval_mysql_python_similarity.txt
|
Q:
Passing numpy.arange() an argument
I'm trying to pass the values that I want numpy.arange to use.
The code is:
for x in numpy.arange(argument)
where argument is:
argument = (.1,6.3,.1) (tuple)
TypeError: arange: scaler arguements expected instead of a tuple
arguement = [.1,6.3,.1] (list)
TypeError: unsupported operand type(s) for -: 'str' and 'int'
arguement = '.1,6.3,.1' (string)
TypeError: unsupported operand type(s) for -: 'str' and 'int'
and I've tried putting the tuple and list in a string. None of these have worked.
I've searched the literature and can find no reference to this.
Any insights would be appreciated.
A:
arange is like python's range function.
Perhaps you were looking for numpy.array?
Or maybe you really did want the range to be from 0.1 to 6.3 in steps of 0.1. In that case, use Python's argument unpacking syntax:
arguments = (.1, 6.3, .1)
numpy.arange(*arguments)
|
Passing numpy.arange() an argument
|
I'm trying to pass the values that I want numpy.arange to use.
The code is:
for x in numpy.arange(argument)
where argument is:
argument = (.1,6.3,.1) (tuple)
TypeError: arange: scaler arguements expected instead of a tuple
arguement = [.1,6.3,.1] (list)
TypeError: unsupported operand type(s) for -: 'str' and 'int'
arguement = '.1,6.3,.1' (string)
TypeError: unsupported operand type(s) for -: 'str' and 'int'
and I've tried putting the tuple and list in a string. None of these have worked.
I've searched the literature and can find no reference to this.
Any insights would be appreciated.
|
[
"arange is like python's range function.\nPerhaps you were looking for numpy.array?\nOr maybe you really did want the range to be from 0.1 to 6.3 in steps of 0.1. In that case, use Python's argument unpacking syntax:\narguments = (.1, 6.3, .1)\nnumpy.arange(*arguments)\n\n"
] |
[
3
] |
[] |
[] |
[
"numpy",
"python"
] |
stackoverflow_0001836966_numpy_python.txt
|
Q:
What Python-only HTTP/1.1 web servers are available?
There is CherryPy. Are there any others?
A:
magnum-py
or...
Make your own!
A:
Twisted includes a web server.
A:
also:
web.py (webpy.org)
paste (pythonpaste.org)
|
What Python-only HTTP/1.1 web servers are available?
|
There is CherryPy. Are there any others?
|
[
"magnum-py\nor...\nMake your own!\n",
"Twisted includes a web server.\n",
"also:\nweb.py (webpy.org)\npaste (pythonpaste.org)\n"
] |
[
2,
2,
1
] |
[] |
[] |
[
"http",
"python"
] |
stackoverflow_0001835668_http_python.txt
|
Q:
Does pytables support NULL?
I have table looks like this
------------------
GeneId | ProteinId
1 | 157
2 | -
3 | 587
4 | 897
5 | -
6 | 120
In realational database, I can treat ProteinId column as INT and use NULL for "-" data. However, I can't find the same option in pytables. Does pytables support NULL ? Currently, I use "0" for NULL data.
A:
As the docs say,
Cells in a PyTables' table always have
a value of the cell type, so there is
no NULL. Instead, cells take a default
value (zero or empty) which can be
changed in the type declaration, like
this: col_name = StringCol(10,
dflt='nothing') (col_name takes the
value 'nothing' if unset).
So, for integer columns, a default of 0 is normally used, and, no, alas!, there is no way to mark a value as missing or unknown, as NULL does in SQL.
|
Does pytables support NULL?
|
I have table looks like this
------------------
GeneId | ProteinId
1 | 157
2 | -
3 | 587
4 | 897
5 | -
6 | 120
In realational database, I can treat ProteinId column as INT and use NULL for "-" data. However, I can't find the same option in pytables. Does pytables support NULL ? Currently, I use "0" for NULL data.
|
[
"As the docs say,\n\nCells in a PyTables' table always have\n a value of the cell type, so there is\n no NULL. Instead, cells take a default\n value (zero or empty) which can be\n changed in the type declaration, like\n this: col_name = StringCol(10,\n dflt='nothing') (col_name takes the\n value 'nothing' if unset).\n\nSo, for integer columns, a default of 0 is normally used, and, no, alas!, there is no way to mark a value as missing or unknown, as NULL does in SQL.\n"
] |
[
5
] |
[] |
[] |
[
"database",
"python"
] |
stackoverflow_0001837181_database_python.txt
|
Q:
How do I uninstall Python 2.5?
I recently upgraded to Mac OS 10.6 and didn't realise that it shipped with Python 2.6.
I installed Python 2.5.4 and now it is the default Python installation.
Can I uninstall Python 2.5.4 and keep 2.6?
A:
While there is no uninstaller for the python.org OS X python installers (because they use the standard Apple installer mechanism which does not provide an uninstaller by default), it is not difficult to remove. I've documented the full process here but keep in mind that it doesn't hurt to have multiple python instances installed on OS X.
The key to managing it all is understanding where each instance is installed and how to manage your shell $PATH search order. By default, the python.org installers modify your .bash_profile (or .profile) shell initialization file to add the python framework bin directory at the front of your $PATH, that is, before /usr/bin where the Apple-supplied python command is found. You'll probably find the unmodified version saved as .bash_profile.pysave. Do a diff first to make sure there aren't any other changes and then just mv it back:
$ cd ~
$ diff .bash_profile{,.pysave}
12,16d11
<
< # Setting PATH for MacPython 2.5
< # The orginal version is saved in .bash_profile.pysave
< PATH="/Library/Frameworks/Python.framework/Versions/2.5/bin:${PATH}"
< export PATH
$ mv .bash_profile.pysave .bash_profile
Start up a new terminal session and verify that python is again python2.6. (This assumes your default login shell is bash.)
If you want, you can then follow the instructions in the link above to actually remove all traces of the extra python. Note, do not attempt to remove the Apple-installed default python files in /usr/bin and /System/Library/Frameworks.
A:
Use the uninstall utility of the same package manager you used to install it.
As a sidenote, you can just modify the PATH not to point to the 2.5.4 installation by default, and both can live happily side-by-side.
A:
Not only path but also link to python as it is now resolved as python2.5, not python2.6.
|
How do I uninstall Python 2.5?
|
I recently upgraded to Mac OS 10.6 and didn't realise that it shipped with Python 2.6.
I installed Python 2.5.4 and now it is the default Python installation.
Can I uninstall Python 2.5.4 and keep 2.6?
|
[
"While there is no uninstaller for the python.org OS X python installers (because they use the standard Apple installer mechanism which does not provide an uninstaller by default), it is not difficult to remove. I've documented the full process here but keep in mind that it doesn't hurt to have multiple python instances installed on OS X.\nThe key to managing it all is understanding where each instance is installed and how to manage your shell $PATH search order. By default, the python.org installers modify your .bash_profile (or .profile) shell initialization file to add the python framework bin directory at the front of your $PATH, that is, before /usr/bin where the Apple-supplied python command is found. You'll probably find the unmodified version saved as .bash_profile.pysave. Do a diff first to make sure there aren't any other changes and then just mv it back:\n$ cd ~\n$ diff .bash_profile{,.pysave}\n12,16d11\n< \n< # Setting PATH for MacPython 2.5\n< # The orginal version is saved in .bash_profile.pysave\n< PATH=\"/Library/Frameworks/Python.framework/Versions/2.5/bin:${PATH}\"\n< export PATH\n$ mv .bash_profile.pysave .bash_profile\n\nStart up a new terminal session and verify that python is again python2.6. (This assumes your default login shell is bash.)\nIf you want, you can then follow the instructions in the link above to actually remove all traces of the extra python. Note, do not attempt to remove the Apple-installed default python files in /usr/bin and /System/Library/Frameworks.\n",
"Use the uninstall utility of the same package manager you used to install it.\nAs a sidenote, you can just modify the PATH not to point to the 2.5.4 installation by default, and both can live happily side-by-side.\n",
"Not only path but also link to python as it is now resolved as python2.5, not python2.6.\n"
] |
[
6,
2,
0
] |
[] |
[] |
[
"macos",
"python"
] |
stackoverflow_0001835003_macos_python.txt
|
Q:
python help display regular expression result
I am doing simple regular expressions in python
I am trying the re.split but things like ['\r\n', '\r\n'] are coming instead of the answer.
Can someone please tell me how to display the actual text please?
I tried this statement:
t_html = re.split("<[a-zA-Z0-9\s\w\W]*>[a-zA-Z0-9\s\w\W]*</[a-zA-Z0-9\s\w\W]*>" ,s)
THanks
A:
re.split by its very nature splits on the pattern but does not preserve it. If you want to return the string matched by the pattern you can put parentheses around the pattern: re.split((R),string) where R is your expression. If you want to say find all non overlapping matches use re.findall which will return a list. See here for more details and options.
A:
If you want to use a regex to parse html, see here.
|
python help display regular expression result
|
I am doing simple regular expressions in python
I am trying the re.split but things like ['\r\n', '\r\n'] are coming instead of the answer.
Can someone please tell me how to display the actual text please?
I tried this statement:
t_html = re.split("<[a-zA-Z0-9\s\w\W]*>[a-zA-Z0-9\s\w\W]*</[a-zA-Z0-9\s\w\W]*>" ,s)
THanks
|
[
"re.split by its very nature splits on the pattern but does not preserve it. If you want to return the string matched by the pattern you can put parentheses around the pattern: re.split((R),string) where R is your expression. If you want to say find all non overlapping matches use re.findall which will return a list. See here for more details and options.\n",
"If you want to use a regex to parse html, see here.\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001836637_python_regex.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.