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:
Nested memcache lookups in Python, o(n) good/bad?
Is something like this bad with memcache?
1. GET LIST OF KEYS
2. FOR EACH KEY IN LIST OF KEYS
- GET DATA
I'm expecting the list of keys to be around ~1000 long.
If this is bad, I'm wondering if there is a better way to do this? I figured memcache might be fast enough where such an O(n) query might not be so important. I would never do this in MySQL, for example.
Thanks.
A:
This will be slower than it needs to be, because each request will wait for the previous one to complete before being sent. If there's any latency at all to the memcache server, this will add up quickly: if there's just 100uS of latency (a typical Ethernet round-trip time), these 1000 lookups will take a tenth of a second, which is a long time in many applications.
The correct way of doing this is making batch requests: sending many requests to the server simultaneously, then receiving all of the responses back, so you don't take a latency penalty repeatedly.
The python-memcache module has the get_multi method to do this for you.
| Nested memcache lookups in Python, o(n) good/bad? | Is something like this bad with memcache?
1. GET LIST OF KEYS
2. FOR EACH KEY IN LIST OF KEYS
- GET DATA
I'm expecting the list of keys to be around ~1000 long.
If this is bad, I'm wondering if there is a better way to do this? I figured memcache might be fast enough where such an O(n) query might not be so important. I would never do this in MySQL, for example.
Thanks.
| [
"This will be slower than it needs to be, because each request will wait for the previous one to complete before being sent. If there's any latency at all to the memcache server, this will add up quickly: if there's just 100uS of latency (a typical Ethernet round-trip time), these 1000 lookups will take a tenth of... | [
2
] | [] | [] | [
"memcached",
"memcachedb",
"python"
] | stackoverflow_0004001052_memcached_memcachedb_python.txt |
Q:
What's the fastest way to remove duplicate lines in a txt file(and also some lines which contain specific strings) using python?
The txt is about 22,000 lines, and it's about 3.5MB. There are lots of duplicate lines in it. I simply want to remove the duplicate lines and also some lines which include specific strings not needed.
My way is to read the file into a big list using readlines() method, then read the file as a big string using read() method. Iterate the list, count occurrence, replace the line with ""(empty string). It took me 10 minutes to finish the job?!
Is there any fast way to do this?
Thanks a lot!
A:
list(set(line for line in file.readlines()
if 'badstring' not in line
and 'garbage' not in line))
Also, a regex might be faster than multiple not in tests.
A:
I almost always do file processing using generators. This makes for code that's fast, easy to modify, and easy to test.
First, build a generator that removes duplicates:
def remove_duplicates(seq):
found = set()
for item in seq:
if item in found:
continue
found.add(item)
yield item
Does it work?
>>> print "\n".join(remove_duplicates(["aa", "bb", "cc", "aa"]))
aa
bb
cc
Apparently so. Next, create a function that tells you whether or not a line is OK:
def is_line_ok(line):
if "bad text1" in line:
return False
if "bad text2" in line:
return False
return True
Does this work?
>>> is_line_ok("this line contains bad text2.")
False
>>> is_line_ok("this line's ok.")
True
>>>
So now we can use remove_duplicates and itertools.ifilter with our function:
>>> seq = ["OK", "bad text2", "OK", "Also OK"]
>>> print "\n".join(remove_duplicates(ifilter(is_line_ok, seq)))
OK
Also OK
This method works on any iterable that returns strings, including files:
with open(input_file, 'r') as f_in:
with open(output_file, 'w') as f_out:
f_out.writelines(remove_duplicates(ifilter(is_line_ok, f_in)))
A:
goodLines = set()
badString = 'bad string'
with open(inFilename, 'r') as f:
for line in f:
if badString not in line:
goodLines.add(line)
# and let's output these lines (sorted, unique) in another file...
with open(outFilename, 'w') as f:
f.writelines(sorted(goodLines))
| What's the fastest way to remove duplicate lines in a txt file(and also some lines which contain specific strings) using python? | The txt is about 22,000 lines, and it's about 3.5MB. There are lots of duplicate lines in it. I simply want to remove the duplicate lines and also some lines which include specific strings not needed.
My way is to read the file into a big list using readlines() method, then read the file as a big string using read() method. Iterate the list, count occurrence, replace the line with ""(empty string). It took me 10 minutes to finish the job?!
Is there any fast way to do this?
Thanks a lot!
| [
"list(set(line for line in file.readlines()\n if 'badstring' not in line\n and 'garbage' not in line))\n\nAlso, a regex might be faster than multiple not in tests. \n",
"I almost always do file processing using generators. This makes for code that's fast, easy to modify, and easy to test.\nFirst,... | [
3,
3,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0003996535_file_python.txt |
Q:
Is there Python web application framework for creating desktop-like GUI end-to-end applications?
I mean that the user interface and the server logic are like one thing, and no html/js is used.
There is an excellent C++ web toolkit, which does exactly this:
http://www.webtoolkit.eu/wt
Is there python equivalent/alternative?
Note: pyjamas does not count - it's great, but client side only.
Thanks!
A:
Nope, Wt is just about the only thing like that. The only thing remotely similar to Wt is ASP.NET, and that is a very long stretch.
| Is there Python web application framework for creating desktop-like GUI end-to-end applications? | I mean that the user interface and the server logic are like one thing, and no html/js is used.
There is an excellent C++ web toolkit, which does exactly this:
http://www.webtoolkit.eu/wt
Is there python equivalent/alternative?
Note: pyjamas does not count - it's great, but client side only.
Thanks!
| [
"Nope, Wt is just about the only thing like that. The only thing remotely similar to Wt is ASP.NET, and that is a very long stretch. \n"
] | [
0
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0004001324_python_user_interface.txt |
Q:
Can pygame use vector art?
http://cache.kotaku.com/assets/resources/2008/02/dbzburstcell.jpg
-edit- bassically just detailed vectorized 2d games.
When making a side scroller in pygame or any other comparable 2d framework with python, can you utilize graphics such as in the above link?
Thanks.
A:
You can always render your vectors to bitmaps with enough resolution and use the rendered version in the game, instead of rendering everything in runtime -- that seems to be what the game you linked above does.
That said, you could use cairo to render .svgs at runtime. There's even a tutorial available.
| Can pygame use vector art? | http://cache.kotaku.com/assets/resources/2008/02/dbzburstcell.jpg
-edit- bassically just detailed vectorized 2d games.
When making a side scroller in pygame or any other comparable 2d framework with python, can you utilize graphics such as in the above link?
Thanks.
| [
"You can always render your vectors to bitmaps with enough resolution and use the rendered version in the game, instead of rendering everything in runtime -- that seems to be what the game you linked above does.\nThat said, you could use cairo to render .svgs at runtime. There's even a tutorial available.\n"
] | [
4
] | [] | [] | [
"graphics",
"pygame",
"python"
] | stackoverflow_0004001340_graphics_pygame_python.txt |
Q:
How to initialize empty list?
Every time the input s comes from the form; the list is initialized again. How do I change the code to append each new s to the list?
Thank you.
class Test(webapp.RequestHandler):
def get(self):
s = self.request.get('sentence')
list = []
list.append(s)
htmlcode1 = HTML.table(list)
A:
I'm not sure what the context of your code is, but this should work:
class Test(webapp.RequestHandler):
def get(self):
s = self.request.get('sentence')
try:
self.myList.append(s)
except NameError:
self.myList= [s]
htmlcode1 = HTML.table(self.myList)
This makes list an instance variable so it'll stick around. The problem is that list might not exist the first time we try to use it, so in this case we need to initialize it.
Actually, looking at this post, this might be cleaner code:
class Test(webapp.RequestHandler):
def get(self):
s = self.request.get('sentence')
if not hasattr(self, 'myList'):
self.myList = []
self.myList.append(s)
htmlcode1 = HTML.table(self.myList)
[Edit:]
The above isn't working for some reason, so try this:
class Test(webapp.RequestHandler):
myList = []
def get(self):
s = self.request.get('sentence')
self.myList.append(s)
htmlcode1 = HTML.table(self.myList)
A:
You could make the list a member variable of the object and then only update it when get() is called:
class Test(webapp.RequestHandler):
def __init__(self, *p, **kw): # or whatever parameters this takes
webapp.RequestHandler.__init__(self, *p, **kw)
self.list = []
def get(self):
s = self.request.get('sentence')
self.list.append(s)
htmlcode1 = HTML.table(self.list)
| How to initialize empty list? | Every time the input s comes from the form; the list is initialized again. How do I change the code to append each new s to the list?
Thank you.
class Test(webapp.RequestHandler):
def get(self):
s = self.request.get('sentence')
list = []
list.append(s)
htmlcode1 = HTML.table(list)
| [
"I'm not sure what the context of your code is, but this should work:\nclass Test(webapp.RequestHandler):\n def get(self):\n s = self.request.get('sentence')\n try:\n self.myList.append(s)\n except NameError:\n self.myList= [s]\n htmlcode1 = HTML.table(self.myLis... | [
6,
5
] | [] | [] | [
"python"
] | stackoverflow_0004001652_python.txt |
Q:
Python Regular Expression Matching ## ##
Possible Duplicate:
Python Regular Expression Matching: ## ##
I already asked this question, but let me restate it better... Im searching a file line by line for the occurrence of ##random_string##. It works except for the case of multiple #...
pattern='##(.*?)##'
prog=re.compile(pattern)
string='lala ###hey## there'
result=prog.search(string)
print re.sub(result.group(1), 'FOUND', line)
Desired Output:
"lala #FOUND there"
Instead I get the following because its grabbing the whole ###hey##:
"lala FOUND there"
So how would i ignore any number of # at the beg or end, and only capture "##string##".
A:
Your problem is with your inner match. You use ., which matches any character that isn't a line end, and that means it matches # as well. So when it gets ###hey##, it matches (.*?) to #hey.
The easy solution is to exclude the # character from the matchable set:
prog = re.compile(r'##([^#]*)##')
Protip: Use raw strings (e.g. r'') for regular expressions so you don't have to go crazy with backslash escapes.
Trying to allow # inside the hashes will make things much more complicated.
(EDIT: Earlier version didn't handle leading/trailing ### right.)
A:
>>> s='lala ###hey## there'
>>> re.sub("(##[^#]+?)#+","FOUND",s)
'lala #FOUND there'
>>> s='lala ###hey## there blah ###### hey there again ##'
>>> re.sub("(##[^#]+?)#+","FOUND",s)
'lala #FOUND there blah ####FOUND'
A:
import re
pattern = "(##([^#]*)##)"
prog = re.compile(pattern)
str = "lala ###hey## there"
result = prog.search(string)
line = "lala ###hey## there"
print re.sub(result.group(0), "FOUND", line)
The trick is to say (not #) instead of anything. This also assumes that
line = "lala #### there"
results in:
line = "lala FOUND there"
| Python Regular Expression Matching ## ## |
Possible Duplicate:
Python Regular Expression Matching: ## ##
I already asked this question, but let me restate it better... Im searching a file line by line for the occurrence of ##random_string##. It works except for the case of multiple #...
pattern='##(.*?)##'
prog=re.compile(pattern)
string='lala ###hey## there'
result=prog.search(string)
print re.sub(result.group(1), 'FOUND', line)
Desired Output:
"lala #FOUND there"
Instead I get the following because its grabbing the whole ###hey##:
"lala FOUND there"
So how would i ignore any number of # at the beg or end, and only capture "##string##".
| [
"Your problem is with your inner match. You use ., which matches any character that isn't a line end, and that means it matches # as well. So when it gets ###hey##, it matches (.*?) to #hey.\nThe easy solution is to exclude the # character from the matchable set:\nprog = re.compile(r'##([^#]*)##')\n\nProtip: Use ... | [
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004002131_python_regex.txt |
Q:
Python: Optimize this loop
a = [(1,2),(3,1),(4,4),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5)]
# Quite a lot tuples in the list, 6 digits~
# I want to split it into rows and columns.
rows = 5
cols = 5
Data structure is
rows and cols are the index for the bit list
[rows, cols, (data)]
I use loop to do this, but it takes too long for processing a big amount of tuples.
processed_data = []
index = 0
for h in range(0, rows - 1):
for w in range(0, cols - 1):
li = []
li = [h, w, a[index]]
processed_data.append(li)
index += 1
This operation takes too long, is there a way to do optimization? Thanks very much!
A:
It's not at all clear to me what you want but here's a shot at the same loop in a more optimized manner:
import itertools as it
index = it.count(0)
processed_data = [[h, w, a[next(index)]]
for h in xrange(0, rows - 1)
for w in xrange(0, cols - 1)]
or, since you've already imported itertools,
index = ite.count(0)
indices = it.product(xrange(0, rows-1), xrange(0, cols-1))
processed_data = [[h, w, a[next(index)]] for h, w in indices]
The reason that these are faster is that they use list comprehensions instead of for loops. List comprehensions have their own opcode, LIST_APPEND, which routes directly to the append method on the list that's being constructed. In a normal for loop, the virtual machine has to go through the whole processes of looking up the append method on the list object which is fairly pricey.
Also, itertools is implemented in C so if it's not faster for the same algorithm, then there's a bug in itertools.
A:
Fine, if you really want the indices that badly...
[divmod(i, cols) + (x,) for i, x in itertools.izip(itertools.count(), a)]
A:
Sounds like you want to split it into evenly-sized chunks.
| Python: Optimize this loop | a = [(1,2),(3,1),(4,4),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5),(5,5)]
# Quite a lot tuples in the list, 6 digits~
# I want to split it into rows and columns.
rows = 5
cols = 5
Data structure is
rows and cols are the index for the bit list
[rows, cols, (data)]
I use loop to do this, but it takes too long for processing a big amount of tuples.
processed_data = []
index = 0
for h in range(0, rows - 1):
for w in range(0, cols - 1):
li = []
li = [h, w, a[index]]
processed_data.append(li)
index += 1
This operation takes too long, is there a way to do optimization? Thanks very much!
| [
"It's not at all clear to me what you want but here's a shot at the same loop in a more optimized manner:\nimport itertools as it\n\nindex = it.count(0) \nprocessed_data = [[h, w, a[next(index)]] \n for h in xrange(0, rows - 1)\n for w in xrange(0, cols - 1)]\n\nor, since you've alre... | [
2,
2,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0004002127_for_loop_python.txt |
Q:
Can I reliably figure out the correct mime type to serve untrusted content?
Say I let users upload files to my server, and I let users download them. I'd like to set the mime type to something other than just application/octet-stream, so that if the browser can just open them, it does (say, for images, pdf files, plain text files, etc.) Of course, since the files are uploaded by users, I can't trust the file extension, etc.
Is there a good library for figuring out what mime type goes with an arbitrary blob? Preferably usable from Python :-)
Thanks!
A:
Try python-magic.
A:
Beware of text files: there's no way of knowing what encoding they're in, and there's no reliable way of guessing, especially since most ones created in Windows are in 8-bit MBCS encodings which are indistinguishable without language heuristics. You need to know the encoding--not just the MIME type--to set the complete Content-Type for a file to be viewable in a browser. If you want to allow uploading and displaying text, it's much safer to use an HTML text form than a raw file upload.
Also, note that a file can be multiple file types; for example, self-extracting ZIPs are both valid Windows executables and ZIP files, and can be treated as either.
| Can I reliably figure out the correct mime type to serve untrusted content? | Say I let users upload files to my server, and I let users download them. I'd like to set the mime type to something other than just application/octet-stream, so that if the browser can just open them, it does (say, for images, pdf files, plain text files, etc.) Of course, since the files are uploaded by users, I can't trust the file extension, etc.
Is there a good library for figuring out what mime type goes with an arbitrary blob? Preferably usable from Python :-)
Thanks!
| [
"Try python-magic.\n",
"Beware of text files: there's no way of knowing what encoding they're in, and there's no reliable way of guessing, especially since most ones created in Windows are in 8-bit MBCS encodings which are indistinguishable without language heuristics. You need to know the encoding--not just the... | [
3,
1
] | [] | [] | [
"mime",
"mime_types",
"python",
"web_applications"
] | stackoverflow_0004002015_mime_mime_types_python_web_applications.txt |
Q:
How come when I use the tComment VIM plugin in a .ini file it adds/removes semi-colons instead of hashes as comment?
I am using gVIM and the tComment plug-in during editing the development.ini file in a Pylons/Python project. The default development.ini file has lines commented out using the hash # symbol which is the standard method of commenting out lines in Python. However, when I try to uncomment lines by using a tComment keyboard shortcut in gVIM, I do not see the # go away. Instead I see a semicolon get added to the beginning of the line.
How do I correct the behavior of tComment so that it adds, or removes, #s instead of adding, or removing, semicolons in Pylons .ini files?
A:
In the tcomment.vim file in your autoload directory you should find a list like this:
call tcomment#DefineType('aap', '# %s' )
call tcomment#DefineType('ada', '-- %s' )
call tcomment#DefineType('apache', '# %s' )
In there you'll find this line:
call tcomment#DefineType('dosini', '; %s' )
Assuming that you don't need to comment windows .ini files too often, you can just change it to this:
call tcomment#DefineType('dosini', '# %s' )
Update:
Here's a slightly better option since you don't have to edit anything but your vimrc. Since your vimrc is generally loaded first, any built in filetypes we try and define get redefined by the above file, so let's make our own:
au BufRead,BufNewFile, *.ini set filetype=pythonini
call tcomment#DefineType('pythonini', '# %s' )
We firstly set .ini files to our own filetype, pythonini, then add our own tcomment definition for it.
To keep your vimrc nice and portable, you may want to check whether or not we have tcomment before trying to call it:
if exists('loaded_tcomment')
au BufRead,BufNewFile, *.ini set filetype=pythonini
call tcomment#DefineType('pythonini', '# %s' )
endif
| How come when I use the tComment VIM plugin in a .ini file it adds/removes semi-colons instead of hashes as comment? | I am using gVIM and the tComment plug-in during editing the development.ini file in a Pylons/Python project. The default development.ini file has lines commented out using the hash # symbol which is the standard method of commenting out lines in Python. However, when I try to uncomment lines by using a tComment keyboard shortcut in gVIM, I do not see the # go away. Instead I see a semicolon get added to the beginning of the line.
How do I correct the behavior of tComment so that it adds, or removes, #s instead of adding, or removing, semicolons in Pylons .ini files?
| [
"In the tcomment.vim file in your autoload directory you should find a list like this:\ncall tcomment#DefineType('aap', '# %s' )\ncall tcomment#DefineType('ada', '-- %s' )\ncall tcomment#DefineType('apache', '# %s' )\n\nIn there you'll find this... | [
10
] | [] | [] | [
"comments",
"ini",
"pylons",
"python",
"vim"
] | stackoverflow_0004002018_comments_ini_pylons_python_vim.txt |
Q:
Measuring internet data transfers
Is there any way in python for S60 (using the python 2.5.4 codebase) to track the amount of data transferred over the mobile device's internet connection?
A:
Symbian C++ API has such a capability, so it is possible to write a python library for that, but if such already exists, that I do not know...
BR
STeN
| Measuring internet data transfers | Is there any way in python for S60 (using the python 2.5.4 codebase) to track the amount of data transferred over the mobile device's internet connection?
| [
"Symbian C++ API has such a capability, so it is possible to write a python library for that, but if such already exists, that I do not know...\nBR\nSTeN\n"
] | [
2
] | [] | [] | [
"pys60",
"python",
"symbian"
] | stackoverflow_0003928685_pys60_python_symbian.txt |
Q:
Django or Ruby on Rails - user extensions, plugins
Which framework has the most mature, flexible, intergrated, centralized and easy-to-use plugins/extension system.
My main requirements are:
a centralized system/repository where i could find a extension i need
no need to make changes in the source code, the plugin should be easily enabled and disabled
large plugin/extension database
something like http://wordpress.org/extend/plugins/
http://www.symfony-project.org/plugins/
A:
I can't speak for Django, but I can tell you about Rails' open source community. GitHub is the central location for all Rails open source code.
Most ruby libraries/plugins these days are packaged as "gems", which are easy to install, update, and remove. RubyGems is the place to go for these pre-packaged gems, when you care less about the code and more about dropping the functionality into your application.
There is now a new tool called RVM that keeps the gems (and even rails version) isolated from one application to the next, on your system. That way if one app uses version 1.0 of a gem, and another uses version 2.0, they don't conflict with each other.
All in all, a pretty sweet setup.
A:
There are lots of reusable django apps around. You can find many on the CheeseShop, but even more on GitHub and BitBucket.
There is also django-packages, which is a bit like the CheeseShop, but just for django packages.
VirtualEnv is like RVM (or rather, RVM is like VirtualEnv), which is a great way to isolate your python packages (I even use it in production). It has been around for ages, and works well with pip (the best python package installer).
A:
Both of them are mature frameworks. I don't use ruby so I don't know about the rails plugin land. Given how popular it is (and my information from my lurking time on local Ruby lists), it's pretty good.
With Django, you have (like Matthew mentioned) django-packages and a few other places. I've been working on a largish Django project and it's pretty easy to just search for something like "django facebook" on google and get what you need. The Pinax project is an integrated collection of Django apps that lets you have most things out of the box. That's another thing you might want to consider. The packaging of the plugins are using the standard Python distutils libraries so installation is a single command (or if you're using pip/virtualenv, directly off the net).
VirtualEnv and related tools are not really Django specific. They're good practice if you're doing any python development though.
You should take a step back and evaluate both languages as well in my opinion. Python and Ruby are quite different in their approach to good code and it's likely that one will fit your brain better than the other.
| Django or Ruby on Rails - user extensions, plugins | Which framework has the most mature, flexible, intergrated, centralized and easy-to-use plugins/extension system.
My main requirements are:
a centralized system/repository where i could find a extension i need
no need to make changes in the source code, the plugin should be easily enabled and disabled
large plugin/extension database
something like http://wordpress.org/extend/plugins/
http://www.symfony-project.org/plugins/
| [
"I can't speak for Django, but I can tell you about Rails' open source community. GitHub is the central location for all Rails open source code.\nMost ruby libraries/plugins these days are packaged as \"gems\", which are easy to install, update, and remove. RubyGems is the place to go for these pre-packaged gems,... | [
4,
1,
0
] | [] | [] | [
"django",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0003999234_django_python_ruby_ruby_on_rails.txt |
Q:
How to get the previous element when using a for loop?
Possible Duplicates:
Python - Previous and next values inside a loop
python for loop, how to find next value(object)?
I've got a list that contains a lot of elements, I iterate over the list using a for loop. For example:
li = [2, 31, 321, 41, 3423, 4, 234, 24, 32, 42, 3, 24, 31, 123]
for i in li:
print(i)
But I want to get the element before i. How can I achieve that?
A:
You can use zip:
for previous, current in zip(li, li[1:]):
print(previous, current)
or, if you need to do something a little fancier, because creating a list or taking a slice of li would be inefficient, use the pairwise recipe from itertools
import itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
for a, b in pairwise(li):
print(a, b)
A:
Just keep track of index using enumerate and get the previous item by index
li = list(range(10))
for i, item in enumerate(li):
if i > 0:
print(item, li[i-1])
print("or...")
for i in range(1, len(li)):
print li[i], li[i-1]
Output:
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
or...
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
Another alternative is to remember the last item, e.g.
last_item = None
for item in li:
print(last_item, item)
last_item = item
A:
Normally, you use enumerate() or range() to go through the elements. Here's an alternative using zip()
>>> li = [2, 31, 321, 41, 3423, 4, 234, 24, 32, 42, 3, 24, 31, 123]
>>> list(zip(li[1:], li))
[(31, 2), (321, 31), (41, 321), (3423, 41), (4, 3423), (234, 4), (24, 234), (32, 24), (42, 32), (3, 42), (24, 3), (31, 24), (123, 31)]
the 2nd element of each tuple is the previous element of the list.
A:
j = None
for i in li:
print(j)
j = i
A:
An option using the itertools recipe from here:
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
for i, j in pairwise(li):
print(i, j)
A:
Use a loop counter as an index. (Be sure to start at 1 so you stay in range.)
for i in range(1, len(li)):
print(li[i], li[i-1])
| How to get the previous element when using a for loop? |
Possible Duplicates:
Python - Previous and next values inside a loop
python for loop, how to find next value(object)?
I've got a list that contains a lot of elements, I iterate over the list using a for loop. For example:
li = [2, 31, 321, 41, 3423, 4, 234, 24, 32, 42, 3, 24, 31, 123]
for i in li:
print(i)
But I want to get the element before i. How can I achieve that?
| [
"You can use zip:\nfor previous, current in zip(li, li[1:]):\n print(previous, current)\n\nor, if you need to do something a little fancier, because creating a list or taking a slice of li would be inefficient, use the pairwise recipe from itertools\nimport itertools\n\ndef pairwise(iterable):\n \"s -> (s0,s1... | [
39,
24,
24,
9,
3,
2
] | [
"li = [2,31,321,41,3423,4,234,24,32,42,3,24,,31,123]\n\ncounter = 0\nfor l in li:\n print l\n print li[counter-1] #Will return last element in list during first iteration as martineau points out.\n counter+=1\n\n"
] | [
-3
] | [
"for_loop",
"list",
"python"
] | stackoverflow_0004002598_for_loop_list_python.txt |
Q:
Handling dates prior to 1970 in a repeatable way in MySQL and Python
In my MySQL database I have dates going back to the mid 1700s which I need to convert somehow to ints in a format similar to Unix time. The value of the int isn't important, so long as I can take a date from either my database or from user input and generate the same int. I need to use MySQL to generate the int on the database side, and python to transform the date from the user.
Normally, the UNIX_TIMESTAMP function, would accomplish this in MySQL, but for dates before 1970, it always returns zero.
The TO_DAYS MySQL function, also could work, but I can't take a date from user input and use Python to create the same values as this function creates in MySQL.
So basically, I need a function like UNIX_TIMESTAMP that works in MySQL and Python for dates between 1700-01-01 and 2100-01-01.
Put another way, this MySQL pseudo-code:
select 1700_UNIX_TIME(date) from table;
Must equal this Python code:
1700_UNIX_TIME(date)
A:
I don't have MySQL here installed, but when I look here: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_to-days - I see an example TO_DAYS('2008-10-07') returning 733687.
The following Python function returns datetime(2008,10,7).toordinal() = 733322, which is 365 less than the MySQL's output.
So take this:
from datetime import datetime
query = '2008-10-07'
nbOfDays = datetime.strptime(query, '%Y-%m-%d').toordinal() + 365
and it should work for dates between 1700 and 2100.
A:
According to the link that you gave,
Given a date date, returns a day number (the number of days since year 0).
mysql> SELECT TO_DAYS(950501);
-> 728779
mysql> SELECT TO_DAYS('2007-10-07');
-> 733321
Corresponding numbers in Python:
>>> import datetime
>>> datetime.date(1995,5,1).toordinal()
728414
>>> datetime.date(2007,10,7).toordinal()
732956
So the relationship is : mySQL_int == Python_int + 365 and you can convert in the other direction by using the fromordinal class method:
>>> datetime.date.fromordinal(728779 - 365)
datetime.date(1995, 5, 1)
| Handling dates prior to 1970 in a repeatable way in MySQL and Python | In my MySQL database I have dates going back to the mid 1700s which I need to convert somehow to ints in a format similar to Unix time. The value of the int isn't important, so long as I can take a date from either my database or from user input and generate the same int. I need to use MySQL to generate the int on the database side, and python to transform the date from the user.
Normally, the UNIX_TIMESTAMP function, would accomplish this in MySQL, but for dates before 1970, it always returns zero.
The TO_DAYS MySQL function, also could work, but I can't take a date from user input and use Python to create the same values as this function creates in MySQL.
So basically, I need a function like UNIX_TIMESTAMP that works in MySQL and Python for dates between 1700-01-01 and 2100-01-01.
Put another way, this MySQL pseudo-code:
select 1700_UNIX_TIME(date) from table;
Must equal this Python code:
1700_UNIX_TIME(date)
| [
"I don't have MySQL here installed, but when I look here: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_to-days - I see an example TO_DAYS('2008-10-07') returning 733687.\nThe following Python function returns datetime(2008,10,7).toordinal() = 733322, which is 365 less than the MySQL... | [
2,
2
] | [] | [] | [
"epoch",
"mysql",
"python",
"sphinx"
] | stackoverflow_0004002660_epoch_mysql_python_sphinx.txt |
Q:
Python Simulation: Total Website Traffic Qty Estimation using Personas Segments
I need to estimate future website traffic & conversion volume based on:
1) Baseline historical averages for 6 differing types of traffic segments
2) How each of those distinct visitor segments interacts with 5 unique content groups
After searching the internet I've concluded modules exist that can easily be
adapted to fit my assumptions.
Reference the following article which describes an overall traffic queuing application:
http://www.ibm.com/developerworks/linux/library/l-simpy.html?dwzone=linux
Please advise if there's a more realistic alternative approach or pre-existing
modules to tweak.
Thank you in advance for your kind consideration and support.
A:
I'm not an expert in simulating of website traffic, but maybe you can use some Monte Carlo simulation to create a statistical representation of real traffic they have on the test site.
Excuse the lack of particulars, and the first idea of what appeared to me, not tested. I'm not sure that I understood your problem.
Post Scriptum.
I think about your and I what to sure. You want to test the efficiency of the website, and you have some historical data of traffic on this website?
| Python Simulation: Total Website Traffic Qty Estimation using Personas Segments | I need to estimate future website traffic & conversion volume based on:
1) Baseline historical averages for 6 differing types of traffic segments
2) How each of those distinct visitor segments interacts with 5 unique content groups
After searching the internet I've concluded modules exist that can easily be
adapted to fit my assumptions.
Reference the following article which describes an overall traffic queuing application:
http://www.ibm.com/developerworks/linux/library/l-simpy.html?dwzone=linux
Please advise if there's a more realistic alternative approach or pre-existing
modules to tweak.
Thank you in advance for your kind consideration and support.
| [
"I'm not an expert in simulating of website traffic, but maybe you can use some Monte Carlo simulation to create a statistical representation of real traffic they have on the test site.\nExcuse the lack of particulars, and the first idea of what appeared to me, not tested. I'm not sure that I understood your proble... | [
0
] | [] | [] | [
"python",
"simulation",
"traffic"
] | stackoverflow_0004002427_python_simulation_traffic.txt |
Q:
Can a program call itself?
I have a Python program that runs a cell model continuously. when I press "A" or "B" certain functions are called - cell divide, etc. when the "esc" key is pressed the simulation exits. Is there a way for the program to exit and then restart itself when "esc" is pressed?
A:
Yes. This is probably what you want
The-Evil-MacBook:~ ivucica$ cat test.py
#!/usr/bin/env python
import sys
import os
print sys.argv[0] + " with argcount " + str(len(sys.argv))
if len(sys.argv) < 2 or sys.argv[1] != "2":
print "doing recursion"
os.system(sys.argv[0] + " 2");
else:
print "not doing recursion"
exit(0)
The-Evil-MacBook:~ ivucica$ ./test.py
./test.py with argcount 1
doing recursion
./test.py with argcount 2
not doing recursion
The-Evil-MacBook:~ ivucica$
So when you want the program to restart itself, just call its sys.argv[0] using os.system() and immediately call exit(some_return_code_here) (zero means 'no error'). You might want to pass an extra argument so it knows it's a restarted instance, but are by no means required to do so; I did so above to prevent endless loop. If you have other mechanisms to prevent endless loops, then use those.
Please also note: for the above code, you need to run the program directly; python test.py did not do the trick for me (for obvious reasons). Also, above will probably work only under UNIX systems.
Note, also, that system() is blocking. If you need the original program to complete shutdown upon launching new program, easiest way would be to send the new one into background (thus "unblocking" system()). Just modify the line like this:
os.system(sys.argv[0] + " 2 &");
Note the "&" which tells the shell to send the new process into background.
A:
The obvious solution is for the program to start a new copy of itself as the last thing it does before exiting. But you probably should think more along the lines of coding the simulator so that it can be reset without requiring a complete restart of the program.
| Can a program call itself? | I have a Python program that runs a cell model continuously. when I press "A" or "B" certain functions are called - cell divide, etc. when the "esc" key is pressed the simulation exits. Is there a way for the program to exit and then restart itself when "esc" is pressed?
| [
"Yes. This is probably what you want\nThe-Evil-MacBook:~ ivucica$ cat test.py\n#!/usr/bin/env python\nimport sys\nimport os\nprint sys.argv[0] + \" with argcount \" + str(len(sys.argv))\nif len(sys.argv) < 2 or sys.argv[1] != \"2\":\n print \"doing recursion\"\n os.system(sys.argv[0] + \" 2\");\nelse:\n pr... | [
2,
0
] | [] | [] | [
"command_line",
"linux",
"python"
] | stackoverflow_0004003104_command_line_linux_python.txt |
Q:
How can I change the cursor image in python soya?
Soya is a 3D game framework for python.
How can I change the cursor image to/from a different image?
A:
Not sure but,
dir() function is your friend. Use it see what methods and attributes are available for "Cursor" class.
From the look of it, it doesn't have one. How ever the parent class allows you to set a shape.
http://home.gna.org/soya/soya.cursor.html
This class is derived from soya.Volume
http://home.gna.org/soya/soya.html#Volume
It seems to have a function called set_shape.
| How can I change the cursor image in python soya? | Soya is a 3D game framework for python.
How can I change the cursor image to/from a different image?
| [
"Not sure but,\ndir() function is your friend. Use it see what methods and attributes are available for \"Cursor\" class.\nFrom the look of it, it doesn't have one. How ever the parent class allows you to set a shape.\n\nhttp://home.gna.org/soya/soya.cursor.html \n\nThis class is derived from soya.Volume \n\nhttp:/... | [
0
] | [] | [] | [
"opengl",
"python",
"sdl"
] | stackoverflow_0004003122_opengl_python_sdl.txt |
Q:
Pyqt save dom to file
Why this code does not work ?
I want save dom after js execute at this page and i want use qt without gui.
Sorry for my English.
#coding:utf-8
from PyQt4 import QtCore, QtWebKit
class Sp():
def save(self):
print "call"
data = self.webView.page().currentFrame().documentElement().toInnerXml()
open("htm","w").write(data)
def main(self):
self.webView = QtWebKit.QWebPage()
self.webView.load(QtCore.QUrl("http://www.google.com"))
QtCore.QObject.connect(self.webView,QtCore.SIGNAL("loadFinished(bool)"),self.save)
s = Sp()
s.main()
A:
You have to create a QApplication before executing other stuff.
Add this:
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
s = Sp()
s.main()
sys.exit(app.exec_())
UPDATED: Also, change the code, because QWebPage doesn't have a load method:
import sys
from PyQt4 import QtGui, QtCore, QtWebKit
class Sp():
def save(self):
print "call"
data = self.webView.page().currentFrame().documentElement().toInnerXml()
open("htm","w").write(data)
print 'finished'
def main(self):
self.webView = QtWebKit.QWebView()
self.webView.load(QtCore.QUrl("http://www.google.com"))
QtCore.QObject.connect(self.webView,QtCore.SIGNAL("loadFinished(bool)"),self.save)
app = QtGui.QApplication(sys.argv)
s = Sp()
s.main()
sys.exit(app.exec_())
| Pyqt save dom to file | Why this code does not work ?
I want save dom after js execute at this page and i want use qt without gui.
Sorry for my English.
#coding:utf-8
from PyQt4 import QtCore, QtWebKit
class Sp():
def save(self):
print "call"
data = self.webView.page().currentFrame().documentElement().toInnerXml()
open("htm","w").write(data)
def main(self):
self.webView = QtWebKit.QWebPage()
self.webView.load(QtCore.QUrl("http://www.google.com"))
QtCore.QObject.connect(self.webView,QtCore.SIGNAL("loadFinished(bool)"),self.save)
s = Sp()
s.main()
| [
"You have to create a QApplication before executing other stuff.\nAdd this:\nimport sys\nfrom PyQt4 import QtGui\n\napp = QtGui.QApplication(sys.argv)\ns = Sp()\ns.main()\nsys.exit(app.exec_())\n\nUPDATED: Also, change the code, because QWebPage doesn't have a load method:\nimport sys\nfrom PyQt4 import QtGui, QtCo... | [
2
] | [] | [] | [
"pyqt4",
"python",
"qt",
"qwebpage"
] | stackoverflow_0004003416_pyqt4_python_qt_qwebpage.txt |
Q:
Translate `thread.start_new_thread(...)` to the new threading API
When I use the old Python thread API everything works fine:
thread.start_new_thread(main_func, args, kwargs)
But if I try to use the new threading API the process, which runs the thread hangs when it should exit itself with sys.exit(3):
threading.Thread(target=main_func, args=args, kwargs=kwargs).start()
How can I translate the code to the new threading API?
You can see this example in context.
A:
This behavior is due to the fact that thread.start_new_thread creates a thread in daemon mode while threading.Thread creates a thread in non-daemon mode.
To start threading.Thread in daemon mode, you need to use .setDaemon method:
my_thread = threading.Thread(target=main_func, args=args, kwargs=kwargs)
my_thread.setDaemon(True)
my_thread.start()
A:
The program will exit when all non-daemon threads have exited. You can make your secondary Thread daemonic by setting its daemon property to True.
Alternatively you can replace your call to sys.exit with os._exit.
| Translate `thread.start_new_thread(...)` to the new threading API | When I use the old Python thread API everything works fine:
thread.start_new_thread(main_func, args, kwargs)
But if I try to use the new threading API the process, which runs the thread hangs when it should exit itself with sys.exit(3):
threading.Thread(target=main_func, args=args, kwargs=kwargs).start()
How can I translate the code to the new threading API?
You can see this example in context.
| [
"This behavior is due to the fact that thread.start_new_thread creates a thread in daemon mode while threading.Thread creates a thread in non-daemon mode.\nTo start threading.Thread in daemon mode, you need to use .setDaemon method:\nmy_thread = threading.Thread(target=main_func, args=args, kwargs=kwargs)\nmy_threa... | [
8,
2
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0004003783_multithreading_python.txt |
Q:
Django Model Inheritance And Foreign Keys
Basically, I have a model where I've created a superclass that many other classes share, and then each of those classes has some unique features that differ from each other. Let's say class A is the superclass, and class B, C, and D are children of that class.
Both class B and class C can have multiples of class D, however I've seen that it's best to put the foreign key relationship in class D, which then refers to its parent class. Now in other languages, I could simply say it has a ForeignKey relationship to class A, and then the language recognizes the classes' true type. However, I don't think that's how it works with Python.
What's the best recommended way of pursuing this issue?
EDIT: Here is roughly what I mean...
class A(models.Model):
field = models.TextField()
class B(A):
other = <class specific functionality>
class C(A):
other2 = <different functionality>
class D(A):
#I would like class D to have a foreign key to either B or C, but not both.
Essentially, class B and class C both have multiple class D's. But a particular class D only belongs to one of them.
A:
One way to do this is to add an intermediate class as follows:
class A(Model):
class Meta(Model.Meta):
abstract = True
# common definitions here
class Target(A):
# this is the target for links from D - you then need to access the
# subclass through ".b" or ".c"
# (no fields here)
class B(Target):
# additional fields here
class C(Target):
# additional fields here
class D(A):
b_or_c = ForeignKey(Target)
def resolve_target(self):
# this does the work for you in testing for whether it is linked
# to a b or c instance
try:
return self.b_or_c.b
except B.DoesNotExist:
return self.b_or_c.c
Using an intermediate class (Target) guarantees that there will only be one link from D to either B or C. Does that make sense? See model inheritance for more information.
In your database there will be tables for Target, B, C and D, but not A, because that was marked as abstract (instead, columns related to attributes on A will be present in Target and D).
[Warning: I have not actually tried this code - any corrections welcome!]
A:
You could also do a generic relation http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1 and check the types to constrain it to B or C when setting or saving. This is probably more work than figuring out the direct reference, but might feel cleaner.
A:
From the Django Docs:
For example, if you were building a
database of "places", you would build
pretty standard stuff such as address,
phone number, etc. in the database.
Then, if you wanted to build a
database of restaurants on top of the
places, instead of repeating yourself
and replicating those fields in the
Restaurant model, you could make
Restaurant have a OneToOneField to
Place (because a restaurant "is a"
place; in fact, to handle this you'd
typically use inheritance, which
involves an implicit one-to-one
relation).
Normally, you would just have Restaurant inherit from Place. Sadly, you need what I consider a hack: making a one-to-one reference from subclass to superclass (Restaurant to Place)
A:
I see a problem here:
class D(A):
#D has foreign key to either B or C, but not both.
Can't do it. You'll have to add both because in SQL columns must be defined exactly.
Also even though inherited models like you have compile with syncdb - they don't seem to behave like you would expect - at least I could not make them work. I can't explain why.
This is how FK works in Django
class A(models.Model):
a = models.CharField(max_length=5)
class B(models.Model):
a = model.ForeignKey(A, related_name='A')
b = models.CharField(max_length=5)
class D(models.Model):
a = model.ForeignKey(A, related_name='A')
parent = model.ForeignKey(B, related_name='D')
this way you can effectively have multiples of D in B.
Inheritance in models (e.g. class B(A)) doesn't work as I would expect it. Maybe someone else can explain it better.
Take a look at this doc page. It's about many-to-one relationship in django.
b = B()
b.D_set.create(...)
| Django Model Inheritance And Foreign Keys | Basically, I have a model where I've created a superclass that many other classes share, and then each of those classes has some unique features that differ from each other. Let's say class A is the superclass, and class B, C, and D are children of that class.
Both class B and class C can have multiples of class D, however I've seen that it's best to put the foreign key relationship in class D, which then refers to its parent class. Now in other languages, I could simply say it has a ForeignKey relationship to class A, and then the language recognizes the classes' true type. However, I don't think that's how it works with Python.
What's the best recommended way of pursuing this issue?
EDIT: Here is roughly what I mean...
class A(models.Model):
field = models.TextField()
class B(A):
other = <class specific functionality>
class C(A):
other2 = <different functionality>
class D(A):
#I would like class D to have a foreign key to either B or C, but not both.
Essentially, class B and class C both have multiple class D's. But a particular class D only belongs to one of them.
| [
"One way to do this is to add an intermediate class as follows:\nclass A(Model):\n class Meta(Model.Meta):\n abstract = True\n # common definitions here\n\nclass Target(A):\n # this is the target for links from D - you then need to access the \n # subclass through \".b\" or \".c\"\n # (no fiel... | [
5,
4,
3,
2
] | [] | [] | [
"django",
"django_models",
"foreign_keys",
"inheritance",
"python"
] | stackoverflow_0001114767_django_django_models_foreign_keys_inheritance_python.txt |
Q:
How to change Selection Colour for selected items in wxpython's CustomTreeCtrl
I am using wxpython's CustumTreeCtrl. Since some of the items in my tree-hierarchy are supposed to have different textcolours it would useful if these items also keep their textcolours when selected. However, when an item is selected the background colour is automatically changed to blue (that can be controlled with SetHilightFocusColour()) and also the colour of the text is changed to white. But in my case I dont want it to change to white. Is there a way that I can change the text colour of an item when in selected state? SetItemTextColour() only sets the text colour for non-selected items...
Cheers.
A:
Are you on a Mac? I found this code in the (extremely long...) PaintItem method:
if wx.Platform == "__WXMAC__" and item.IsSelected() and self._hasFocus:
dc.SetTextForeground(wx.WHITE)
dc.DrawLabel(item.GetText(), textrect)
I couldn't be sure for other platforms, but it appears to use the system defaults.
So it looks like the only thing to do is to modify the class to add an internal highlight foreground color, or subclass it and override the OnPaintItem method (with lots of copy pasta, unfortunately).
Edit
A quick hack would be to add this to the __init__ method:
self.highlight_fgc = wx.WHITE
Then in the OnPaintItem method, you would add this code immediately before the dc.DrawLabel calls at the end of the method:
dc.SetTextForeground(self.highlight_fgc)
Finally, in your own code, you would set the highlight foreground color:
self.tree.highlight_fgc = wx.RED # etc...
Or if you want each item to have its own color, you would modify the item (isn't there a "SetItemData" method or similar) to hold the color, and then do:
dc.SetTextForeground(item.GetItemData()) # or whatever...
A:
Try the latest code from SVN - it may be fixed.
| How to change Selection Colour for selected items in wxpython's CustomTreeCtrl | I am using wxpython's CustumTreeCtrl. Since some of the items in my tree-hierarchy are supposed to have different textcolours it would useful if these items also keep their textcolours when selected. However, when an item is selected the background colour is automatically changed to blue (that can be controlled with SetHilightFocusColour()) and also the colour of the text is changed to white. But in my case I dont want it to change to white. Is there a way that I can change the text colour of an item when in selected state? SetItemTextColour() only sets the text colour for non-selected items...
Cheers.
| [
"Are you on a Mac? I found this code in the (extremely long...) PaintItem method:\n if wx.Platform == \"__WXMAC__\" and item.IsSelected() and self._hasFocus:\n dc.SetTextForeground(wx.WHITE)\n dc.DrawLabel(item.GetText(), textrect)\n\nI couldn't be sure for other platforms, but it appears t... | [
0,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003992868_python_wxpython.txt |
Q:
non-destructive version of pop() for a dictionary
Is there any idiom for getting an arbitrary key, value pair from a dictionary without removing them? (P3K)
EDIT:
Sorry for the confusing wording.
I used the word arbitrary in the sense that I don't care about what I'm getting.
It's different from random, where I do care about what I'm getting (i.e., I need probabilities of each item being chosen to be the same).
And I don't have a key to use; if I did, I'd think it would be in the RTFM category and wouldn't deserve an answer on SO.
EDIT:
Unfortunately in P3K, .items() returns a dict_items object, unlike Python 2 which returned an iterator:
ActivePython 3.1.2.4 (ActiveState Software Inc.) based on
Python 3.1.2 (r312:79147, Sep 14 2010, 22:00:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {1:2}
>>> k,v = next(d.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: dict_items object is not an iterator
A:
k, v = next(iter(d.items())) # updated for Python 3
| non-destructive version of pop() for a dictionary | Is there any idiom for getting an arbitrary key, value pair from a dictionary without removing them? (P3K)
EDIT:
Sorry for the confusing wording.
I used the word arbitrary in the sense that I don't care about what I'm getting.
It's different from random, where I do care about what I'm getting (i.e., I need probabilities of each item being chosen to be the same).
And I don't have a key to use; if I did, I'd think it would be in the RTFM category and wouldn't deserve an answer on SO.
EDIT:
Unfortunately in P3K, .items() returns a dict_items object, unlike Python 2 which returned an iterator:
ActivePython 3.1.2.4 (ActiveState Software Inc.) based on
Python 3.1.2 (r312:79147, Sep 14 2010, 22:00:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {1:2}
>>> k,v = next(d.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: dict_items object is not an iterator
| [
"k, v = next(iter(d.items())) # updated for Python 3\n\n"
] | [
5
] | [
"pop is supposed to remove a item. Isn't that the meaning of that method?\nIf you want to get random key , value pair use pseudo random module\n>>> import random\n>>> x = {1:3, 4:5, 6:7}\n>>> x = {1:3, 4:5, 6:7, 'a':9, 'z':'x'}\n>>> k = random.choice(x.keys())\n>>> x[k]\n7\n>>> \n\n",
"The items() method returns ... | [
-1,
-1,
-2,
-3
] | [
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0004002874_dictionary_python_python_3.x.txt |
Q:
text with unicode escape sequences to unicode in python
suppose I have the string
test
'\\u0259'
Note the escaped backslash.
How do I convert it to the respective unicode string?
A:
>>> print('test \\u0259'.decode('unicode-escape'))
test ə
| text with unicode escape sequences to unicode in python | suppose I have the string
test
'\\u0259'
Note the escaped backslash.
How do I convert it to the respective unicode string?
| [
">>> print('test \\\\u0259'.decode('unicode-escape'))\ntest ə\n\n"
] | [
38
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0004004431_python_unicode.txt |
Q:
How to remove the last element in each list in a list
I've got a list like:
alist = [[a,b,(1,2)], [a,b,(1,2)], [a,b,(1,2)]]
I want to remove the last element from all the elements in a list. So the result will be:
alist = [[a,b], [a,b], [a,b]]
Is there a fast way to do this?
A:
You could use list comprehension to create a new list that removes the last element.
>>> alist = [[1,2,(3,4)],[5,6,(7,8)],[9,10,(11,12)]]
>>> [x[:-1] for x in alist] # <-------------
[[1, 2], [5, 6], [9, 10]]
However, if you want efficiency you could modify the list in-place:
>>> alist = [[1,2,(3,4)],[5,6,(7,8)],[9,10,(11,12)]]
>>> for x in alist: del x[-1] # <-------------
...
>>> alist
[[1, 2], [5, 6], [9, 10]]
| How to remove the last element in each list in a list | I've got a list like:
alist = [[a,b,(1,2)], [a,b,(1,2)], [a,b,(1,2)]]
I want to remove the last element from all the elements in a list. So the result will be:
alist = [[a,b], [a,b], [a,b]]
Is there a fast way to do this?
| [
"You could use list comprehension to create a new list that removes the last element.\n>>> alist = [[1,2,(3,4)],[5,6,(7,8)],[9,10,(11,12)]]\n>>> [x[:-1] for x in alist] # <-------------\n[[1, 2], [5, 6], [9, 10]]\n\nHowever, if you want efficiency you could modify the list in-place:\n>>> alist = [[1,2,(3,4)],... | [
12
] | [
"This is basic Python stuff. You should be able to do it after reading the Python tutorial\n>>> alist = [[1,2,(3,4)],[5,6,(7,8)],[9,10,(11,12)]]\n>>> for li in alist:\n... print li[0:2]\n...\n[1, 2]\n[5, 6]\n[9, 10]\n>>>\n\nLater on, you can go to intermediate stuff like list comprehension etc\n"
] | [
-2
] | [
"list",
"python"
] | stackoverflow_0004004447_list_python.txt |
Q:
Replacing whitespaces within list elements
I have a list of tags:
>>> tags_list
['tag1', 'second tag', 'third longer tag']
How can I replace whitespaces within each element of the list with "+" ? I was trying to do this with regular expressions but each string remains unchanged:
for tag in tags_list:
re.sub("\s+" , " ", tag)
What is wrong with my approach ?
EDIT:
Yes I forgot to mention, that between the words in each tag we can have multiple whitespaces as well as tags can begin or end with whitespaces, since they're parsed from a comma separated string with split(",") : ("First tag, second tag, third tag"). Sorry for not being precise enough.
A:
re.sub() returns a new string, it does not modify its parameter in-place.
You probably want:
tags_list = [re.sub(r"\s+", "+", tag) for tag in tags_list]
Also, don't forget the r before the regex or you'll have to double all the backslashes inside (i.e. the regex you posted won't work).
EDIT: I assume replace whitespaces within each element of the list with "+" means collapsing all consecutive whitespace into a single +character. If not, use r"\s" instead of r"\s+".
A:
What you were doing is not replacing spaces with +, you were replacing multiple whitespace characters with a single space, on top of that you were throwing results out. Here is what you need:
>>> tags = ['tag1', 'second tag', 'third longer tag']
>>> [re.sub(r'\s+', '+', i.strip()) for i in tags]
['tag1', 'second+tag', 'third+longer+tag']
>>> tags
['tag1', 'second tag', 'third longer tag']
A:
>>> tags = ['tag1', 'second tag', 'third longer tag']
>>> [ '+'.join(i.split()) for i in tags ]
['tag1', 'second+tag', 'third+longer+tag']
| Replacing whitespaces within list elements | I have a list of tags:
>>> tags_list
['tag1', 'second tag', 'third longer tag']
How can I replace whitespaces within each element of the list with "+" ? I was trying to do this with regular expressions but each string remains unchanged:
for tag in tags_list:
re.sub("\s+" , " ", tag)
What is wrong with my approach ?
EDIT:
Yes I forgot to mention, that between the words in each tag we can have multiple whitespaces as well as tags can begin or end with whitespaces, since they're parsed from a comma separated string with split(",") : ("First tag, second tag, third tag"). Sorry for not being precise enough.
| [
"re.sub() returns a new string, it does not modify its parameter in-place.\nYou probably want:\ntags_list = [re.sub(r\"\\s+\", \"+\", tag) for tag in tags_list]\n\nAlso, don't forget the r before the regex or you'll have to double all the backslashes inside (i.e. the regex you posted won't work).\nEDIT: I assume re... | [
6,
2,
0
] | [] | [] | [
"python",
"regex",
"replace",
"string",
"whitespace"
] | stackoverflow_0004004349_python_regex_replace_string_whitespace.txt |
Q:
Converting string series to float list in python
I am quite new to programing so I hope this question is simple enough.
I need to know how to convert a string input of numbers separated by spaces on a single line:
5.2 5.6 5.3
and convert this to a float list
lsit = [5.2,5.6,5.3]
How can this be done?
A:
Try a list comprehension:
s = '5.2 5.6 5.3'
floats = [float(x) for x in s.split()]
In Python 2.x it can also be done with map:
floats = map(float, s.split())
Note that in Python 3.x the second version returns a map object rather than a list. If you need a list you can convert it to a list with a call to list, or just use the list comprehension approach instead.
| Converting string series to float list in python | I am quite new to programing so I hope this question is simple enough.
I need to know how to convert a string input of numbers separated by spaces on a single line:
5.2 5.6 5.3
and convert this to a float list
lsit = [5.2,5.6,5.3]
How can this be done?
| [
"Try a list comprehension:\ns = '5.2 5.6 5.3'\nfloats = [float(x) for x in s.split()]\n\nIn Python 2.x it can also be done with map:\nfloats = map(float, s.split())\n\nNote that in Python 3.x the second version returns a map object rather than a list. If you need a list you can convert it to a list with a call to l... | [
75
] | [] | [] | [
"python"
] | stackoverflow_0004004550_python.txt |
Q:
How can I distinguish lists from strings in django templates
I'm developing a project on Google AppEngine, using Django templates, so I have to use tags like {{ aitem.Author }} to print content within my HTML template.
Author, however, can either be a string or a list object, and I have no way to tell it in advance. When the Author is a list and I try to print it on my template, I get the ugly result of
Author: [u'J. K. Rowling', u'Mary GrandPr\xe9']
Is there any way to handle this kind of scenario (basically printing a field differently depending on its type) effectively? Do I have to rely on custom tags or any other means?
A:
I think the cleanest solution would be to add a method to the model get_authors() which always returns a list either of one or more authors. Then you can use:
Author: {{ aitem.get_authors|join:", " }}
If you for some reason have only access to the templates and can't change the model, then you can use a hack like this:
{% if "[" == aitem.Author|pprint|slice:":1" %}
Author: {{ aitem.Author|join:", " }}
{% else %}
Author: {{ aitem.Author }}
{% endif %}
P.S. it's not a good convention to use capital letters for attribute names.
A:
I think that Aidas's get_authors() solution is the best, but an alternative might be to create a template tag that does the test. You'll want to read up on custom template tags, but they aren't that hard to create if you look at the existing ones.
A:
I followed Matthew's advice and eventually implemented a filter to handle lists.
I'm posting it here just in case someone else needs it.
@register.filter(name='fixlist')
def fixlist(author):
if type(author) == list:
return ', '.join(author)
else:
return author
I call it from the template pages like this {{ aitem.Author|fixlist }}
Thank you for the help!
| How can I distinguish lists from strings in django templates | I'm developing a project on Google AppEngine, using Django templates, so I have to use tags like {{ aitem.Author }} to print content within my HTML template.
Author, however, can either be a string or a list object, and I have no way to tell it in advance. When the Author is a list and I try to print it on my template, I get the ugly result of
Author: [u'J. K. Rowling', u'Mary GrandPr\xe9']
Is there any way to handle this kind of scenario (basically printing a field differently depending on its type) effectively? Do I have to rely on custom tags or any other means?
| [
"I think the cleanest solution would be to add a method to the model get_authors() which always returns a list either of one or more authors. Then you can use:\nAuthor: {{ aitem.get_authors|join:\", \" }}\n\nIf you for some reason have only access to the templates and can't change the model, then you can use a hack... | [
7,
1,
0
] | [] | [] | [
"django",
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0004001802_django_django_templates_google_app_engine_python.txt |
Q:
How to serialize XML document in python using xml.dom library
I'd like to know how I can serialize an XML document in python specifically using the xml.dom library.
A:
You mean something like:
xml.dom.ext.PrettyPrint(doc, open(name, "w"))
where doc is the XML document and name is the name of the file?
Or, if you have xml.dom.minidom, how about the xml.dom.minidom.writexml function?
| How to serialize XML document in python using xml.dom library | I'd like to know how I can serialize an XML document in python specifically using the xml.dom library.
| [
"You mean something like:\nxml.dom.ext.PrettyPrint(doc, open(name, \"w\"))\n\nwhere doc is the XML document and name is the name of the file?\nOr, if you have xml.dom.minidom, how about the xml.dom.minidom.writexml function?\n"
] | [
1
] | [] | [] | [
"dom",
"python",
"xml"
] | stackoverflow_0004004735_dom_python_xml.txt |
Q:
Python: how to know how many colors in a bounding box in PIL?
Hey, I've got so many PIL bounding box(x,y, x1,y1)
I just want to know how many colors are there in the bounding box, is there any fast way to do?
A:
>>> myimg = ...
>>> colors = myimg.crop((x0, y0, x1, y1)).getcolors()
According to PIL's docs getcolors "Returns an unsorted list of (count, color) tuples, where the count is the number of times the corresponding color occurs in the image".
| Python: how to know how many colors in a bounding box in PIL? | Hey, I've got so many PIL bounding box(x,y, x1,y1)
I just want to know how many colors are there in the bounding box, is there any fast way to do?
| [
">>> myimg = ...\n>>> colors = myimg.crop((x0, y0, x1, y1)).getcolors()\n\nAccording to PIL's docs getcolors \"Returns an unsorted list of (count, color) tuples, where the count is the number of times the corresponding color occurs in the image\".\n"
] | [
2
] | [] | [] | [
"bounding_box",
"python",
"python_imaging_library"
] | stackoverflow_0004004677_bounding_box_python_python_imaging_library.txt |
Q:
GUI-embeddable Python drawing widget with anti-aliasing
I am writing a small diagram drawing application (similar to Graphviz in spirit), and need a GUI library that would allow me to embed a canvas capable of drawing anti-aliased lines and text. I want to have a text editor in one half of the window to edit the diagram code and a (perhaps live) preview pane in the other.
Right now I have the text editor in a tkinter window and the rendered diagram in a separate pygame one. This technically works, but it's messy (e.g. having two event loops), and in general I would much prefer having both parts in one window. I have searched for ways of integrating the two, but haven't been able to find anything cross-platform, and pygame explicitly suggests not trying to do it.
An alternative would be to have pygame export the image into a file and load it back into tkinter, but tkinter can read only GIF/PPM without PIL (and I use Python 3, which PIL doesn't support) and pygame can't write GIF/PPM. I could backport to Python 2, since it's a tiny app, but even then, having a large extra library for a simple image conversion doesn't seem right, and the round-trip to a file will probably be too slow for live preview (not to mention ugly).
Finally, a simple tkinter canvas is almost what I want, except it can't draw anti-aliased lines, and for a program whose main purpose is to draw line figures, that is not acceptable.
I'm using Python 3 so libraries that support it are preferred, but if there's no way to do that whatsoever Python 2 libs are Ok as well. The library needs to be cross-platform, and of course, the fewer external packages are required, the better.
A:
If you don't mind the way GTK looks, pygtk has an option for antialising in their canvas widget (see this) and is considered by many to be as powerful as Tkinter, though it is not included in standard Python installs.
Also, it's Python 3.x compatible, which can't be said of most non-standard library modules and packages.
A:
Screwing around with Tkinter+pygame is silly. I would use wxPython. In fact, I've done a diagramming widget using wxPython, and it has anti-aliasing:
Unfortunately it was for work, so I can't distribute the code.
The wxPython classes you want to look at for anti-aliasing are wx.GCDC and/or wx.GraphicsContext.
A:
After a thorough search I ended up using PyQt4. It does fit all my requirements (Python 3, cross-platform, anti-aliasing), and now that I've gotten through the basics, it's also quite intuitive and easy to use.
Posting this as an answer to my own question and accepting it for future reference.
| GUI-embeddable Python drawing widget with anti-aliasing | I am writing a small diagram drawing application (similar to Graphviz in spirit), and need a GUI library that would allow me to embed a canvas capable of drawing anti-aliased lines and text. I want to have a text editor in one half of the window to edit the diagram code and a (perhaps live) preview pane in the other.
Right now I have the text editor in a tkinter window and the rendered diagram in a separate pygame one. This technically works, but it's messy (e.g. having two event loops), and in general I would much prefer having both parts in one window. I have searched for ways of integrating the two, but haven't been able to find anything cross-platform, and pygame explicitly suggests not trying to do it.
An alternative would be to have pygame export the image into a file and load it back into tkinter, but tkinter can read only GIF/PPM without PIL (and I use Python 3, which PIL doesn't support) and pygame can't write GIF/PPM. I could backport to Python 2, since it's a tiny app, but even then, having a large extra library for a simple image conversion doesn't seem right, and the round-trip to a file will probably be too slow for live preview (not to mention ugly).
Finally, a simple tkinter canvas is almost what I want, except it can't draw anti-aliased lines, and for a program whose main purpose is to draw line figures, that is not acceptable.
I'm using Python 3 so libraries that support it are preferred, but if there's no way to do that whatsoever Python 2 libs are Ok as well. The library needs to be cross-platform, and of course, the fewer external packages are required, the better.
| [
"If you don't mind the way GTK looks, pygtk has an option for antialising in their canvas widget (see this) and is considered by many to be as powerful as Tkinter, though it is not included in standard Python installs.\nAlso, it's Python 3.x compatible, which can't be said of most non-standard library modules and p... | [
2,
2,
2
] | [] | [] | [
"drawing",
"pygame",
"python",
"python_3.x",
"tkinter"
] | stackoverflow_0003999780_drawing_pygame_python_python_3.x_tkinter.txt |
Q:
GAE organizing data structure problem
Ok. I'm working with GAE. And i want create something like this:
I have types "group" "topic" "tag":
each "group" can have as many
"topics" as needed
each "topic" can have as many "tags"
as needed
each "group" can have as many "tags"
as needed
it's something like circle.
right now i have something like this:
class TopicGroup(db.Model):
value = db.StringProperty(required=True)
class Topic(db.Model):
title = db.StringProperty(required=True)
group = db.ReferenceProperty(TopicGroup, 'group', 'topics', required=True)
class TopicTag(db.Model):
topic = db.ReferenceProperty(Topic, 'topic', 'tags', required=True)
group = db.ReferenceProperty(TopicGroup, 'group', 'tags', required=True)
value = db.StringProperty(required=True)
but this is no good (in my model "topic" can have only one tag, but i nead "topic" to have as many tags as needed)
well i already have a crack in my head... is there someone who could help?
A:
Many-to-many joins can be implemented as join tables (or Relationship Models). In the solution below, there is a model that holds all of the tags that are applied to individual Groups (GroupTags) and a model that holds the tags that are applied to Topics (TopicTags).
Decoupling the Tag itself from references to the Tag allows you to do things like change the spelling of a tag without needing to update every Group or Topic to which that Tag is applied.
Also, this model takes good advantage of the fact that AppEngine creates automatic backreferences on entities that have other entities referencing them. In the models below, a Group entity will have a property called topics that is a query that will fetch all Topic entities who's group reference points to that Group. Similarly, each Group gets a tags property from the GroupsTags model that gives it all of the Tag entities that belong to it. Every Tag entity gets a groups and topics property that is a query for all of the entities of those types that have the give Tag assigned, making searching by tag (a very typical operation) quite simple.
It's a very powerful and flexible approach to modeling systems such as yours.
class Group(db.Model):
# All of my group-specific data here.
class Topic(db.Model):
title = db.StringProperty(required=True)
group = db.ReferenceProperty(Group, collection='topics')
# other topic-specific data here.
class Tag(db.Model):
text = db.StringProperty(required=True)
class GroupTags(db.Model):
group = db.ReferenceProperty(Group, collection='tags')
tag = db.ReferenceProperty(Tag, collection='groups')
class TopicTags(db.Model):
topic = db.ReferenceProperty(Topic, collection='tags')
tag = db.ReferenceProperty(Tag, collection='topics')
A:
The solution is to use a db.ListProperty with a type of db.Key.
see: http://code.google.com/appengine/articles/modeling.html (section many to many)
| GAE organizing data structure problem | Ok. I'm working with GAE. And i want create something like this:
I have types "group" "topic" "tag":
each "group" can have as many
"topics" as needed
each "topic" can have as many "tags"
as needed
each "group" can have as many "tags"
as needed
it's something like circle.
right now i have something like this:
class TopicGroup(db.Model):
value = db.StringProperty(required=True)
class Topic(db.Model):
title = db.StringProperty(required=True)
group = db.ReferenceProperty(TopicGroup, 'group', 'topics', required=True)
class TopicTag(db.Model):
topic = db.ReferenceProperty(Topic, 'topic', 'tags', required=True)
group = db.ReferenceProperty(TopicGroup, 'group', 'tags', required=True)
value = db.StringProperty(required=True)
but this is no good (in my model "topic" can have only one tag, but i nead "topic" to have as many tags as needed)
well i already have a crack in my head... is there someone who could help?
| [
"Many-to-many joins can be implemented as join tables (or Relationship Models). In the solution below, there is a model that holds all of the tags that are applied to individual Groups (GroupTags) and a model that holds the tags that are applied to Topics (TopicTags).\nDecoupling the Tag itself from references to t... | [
5,
2
] | [] | [] | [
"database",
"google_app_engine",
"python"
] | stackoverflow_0004004770_database_google_app_engine_python.txt |
Q:
XML parser-writer that keeps Attributes order
I need to parse XML document and then write every node to separate files keeping exact order of attributes.
So if i have input file like :
<item a="a" b="b" c="c"/>
<item a="a1" b="b2" c="c3"/>
Output should be 2 files with every item.
Now if xml.dom.minidom is used - attribute order is changed in output( i can get - <item b="b" c="c" **a="a"**/>)
I found pxdom lib, it keeps order but very-very slow( minidom parsing takes 0.08 sec., pxdom parsing takes 2,5 sec.)
Is there any other python libraries that can keep attributes?
UPD: libarry should also keep upper and lower cases. So "Item" is not equal to "item"
A:
You might find this question useful. Bottom line summary-- standard xml tools and libraries most likely won't be able to do this.
A:
You can use BeautifulSoup:
>>> from BeautifulSoup import BeautifulSoup as soup
>>> html = '''<item a="a" b="b" c="c"/>
<item a="a1" b="b2" c="c3"/>'''
>>> s = soup(html)
>>> s.findAll('item')
[<item a="a" b="b" c="c"></item>, <item a="a1" b="b2" c="c3"></item>]
| XML parser-writer that keeps Attributes order | I need to parse XML document and then write every node to separate files keeping exact order of attributes.
So if i have input file like :
<item a="a" b="b" c="c"/>
<item a="a1" b="b2" c="c3"/>
Output should be 2 files with every item.
Now if xml.dom.minidom is used - attribute order is changed in output( i can get - <item b="b" c="c" **a="a"**/>)
I found pxdom lib, it keeps order but very-very slow( minidom parsing takes 0.08 sec., pxdom parsing takes 2,5 sec.)
Is there any other python libraries that can keep attributes?
UPD: libarry should also keep upper and lower cases. So "Item" is not equal to "item"
| [
"You might find this question useful. Bottom line summary-- standard xml tools and libraries most likely won't be able to do this.\n",
"You can use BeautifulSoup:\n>>> from BeautifulSoup import BeautifulSoup as soup\n\n>>> html = '''<item a=\"a\" b=\"b\" c=\"c\"/>\n<item a=\"a1\" b=\"b2\" c=\"c3\"/>'''\n>>> s = s... | [
1,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0004003643_python_xml.txt |
Q:
What is a good function to map an id to memcache in a pool of servers?
Something like:
host = getHost(id)
>>> 172.16.25.52
Ideally, the algorithm should minimize the number of cache misses when the pool of servers is expanded / contracted.
Are there any known algorithms out there that do this? Or libraries, potentially (I'm using Python).
Thank you.
A:
The memcached library does this by default. So you can just read the code from the repository: http://bazaar.launchpad.net/~python-memcached-team/python-memcached/trunk/annotate/head%3A/memcache.py#L274
As for minimizing the cache misses with an expanding/contracting pool... a difficult thing to do. Either you're not dividing the servers correctly at first or it will be less optimal when expanding/contracting. If you would have a maximum of N servers than it might be easier though, since you can make a couple of assumptions.
| What is a good function to map an id to memcache in a pool of servers? | Something like:
host = getHost(id)
>>> 172.16.25.52
Ideally, the algorithm should minimize the number of cache misses when the pool of servers is expanded / contracted.
Are there any known algorithms out there that do this? Or libraries, potentially (I'm using Python).
Thank you.
| [
"The memcached library does this by default. So you can just read the code from the repository: http://bazaar.launchpad.net/~python-memcached-team/python-memcached/trunk/annotate/head%3A/memcache.py#L274\nAs for minimizing the cache misses with an expanding/contracting pool... a difficult thing to do. Either you're... | [
1
] | [] | [] | [
"memcached",
"python"
] | stackoverflow_0004004935_memcached_python.txt |
Q:
How to decode this YUV colorspace string and save it as an image
So I am using one third party library which is not very well documented. It has a method which takes a picture with camera and this is what it returns:
'E{\x7fM{\x7f;\x89\x89:\x89\x89=\x81\x87<\x81\x87O\x90\x7fJ\x90\x7fB\x87\x80I\x87\x80<{\x81={\x81A\x81\x82A\x81\x82E\x81\x81:\x81\x818\x80\x81?\x80\x81?\x8c\x85C\x8c\x85Dw\x84Kw\x84K\x81}H\x81}S\x82|R\x82|N\x88xS\x88xP\x87|P\x87|H\x83}H\x83}J\x83|F\x83|S{\x80P{\x80G~zH~zDx\x7fDx\x7fI\x7f\x80M\x7f\x80I\x82yK\x82yH\x83\x80H\x83\x80K\x84\x80L\x84\x80K\x82|H\x82|G\x83\x83G\x83\x83M\x81\x80M\x81\x80K\x83~F\x83~H\x81~L\x81~N\x85|J\x85|B\x84\x82I\x84\x82K\x84\x7fJ\x84\x7fG\x83\x80F\x83\x80B~\x81G~\x81E}~G}~D}\x81B}\x81I|\x84I|\x84I\x82\x7fG\x82\x7fG\x80~E\x80~Iy\x81Jy\x81H|\x82M|\x82L\x81\x82I\x81\x82Gx\x82Hx\x82Ez\x7fGz\x7fL|\x81N|\x81G\x82\x80K\x82\x80L\x81}P\x81}J\x82\x7fH\x82\x7fCz|Dz|K}\x7fH}\x7fDs|Es|L\x83\x81I\x83\x81HxzHxzJ{\x83F{\x83G\x84\x81F\x84\x81I\x88\x85G\x88\x85Cu\x83@u\x83H}\x83D}\x83<u\x80;u\x80C\x88{C\x88{A\x7f\x82E\x7f\x82D\x84\x81C\x84\x81A}\x87A}\x87>|\x7fA|\x7fA}\x82;}\x82D\x83\x80?\x83\x80@\x80\x7fB\x80\x7fB\x80\x85A\x80\x85@u\x88>u\x888~\x848~\x84?w|=w|9|\x7f9|\x7f:\x84\x81;\x84\x81:~\x83;~\x836u\x87>u\x879{\x8d:{\x8d;\x7f\x86;\x7f\x86;y\x834y\x836\x82\x8c;\x82\x8c<y\x8b5y\x8bI~~M~~>\x88\x84:\x88\x84A\x81\x889\x81\x88B~\x81E~\x81A{\x81@{\x81O\x80\x83S\x80\x83\\\x85xf\x85xQ\x90\x80L\x90\x80G\x81\x7fK\x81\x7f@y\x83Dy\x83E~\x88E~\x88F\x81\x82M\x81\x82P\x82\x80O\x82\x80S\x85\x7fT\x85\x7fT\x83~U\x83~T\x88\x7fR\x88\x7fPz\x7fTz\x7fQ\x7f}P\x7f}Q}\x81U}\x81R\x7f\x7fO\x7f\x7fP\x83\x83N\x83\x83M\x85\x80R\x85\x80L\x87\x82O\x87\x82N\x82{N\x82{V|\x84P|\x84Rz\x83Qz\x83M\x89\x84R\x89\x84P\x8c\x85N\x8c\x85L\x80\x81I\x80\x81M|~N|~L}\x81J}\x81S\x82\x7fL\x82\x7fM}\x84I}\x84K~\x80L~\x80Lz\x80Iz\x80Hy\x80Ly\x80K~\x7fJ~\x7fJx\x82Ox\x82J\x7f\x81M\x7f\x81I\x80~J\x80~Q\x81\x82O\x81\x82M\x84\x7fH\x84\x7fO~\x80R~\x80I\x80\x84J\x80\x84J\x7f\x82L\x7f\x82N\x85\x85U\x85\x85R\x83\x87O\x83\x87U\x82\x80P\x82\x80N|\x85K|\x85O}~O}~J\x7f\x81K\x7f\x81M}\x86N}\x86I|\x82I|\x82Ix\x84Gx\x84My\x88Jy\x88J{\x7fH{\x7fF}{F}{G\x7f\x82K\x7f\x82E}\x7fE}\x7fBz\x80Dz\x80I}\x80J}\x80Dw\x81Dw\x81G\x82\x84H\x82\x84Fz\x85Cz\x85>\x85\x86;\x85\x86H\x8a\x84J\x8a\x84Cx\x80Cx\x80B\x80\x85B\x80\x85@|\x83B|\x83?{\x81@{\x81H{\x84@{\x84?y\x84Ay\x84A\x84\x85=\x84\x85;}\x81=}\x81=\x84\x86@\x84\x86:}\x85;}\x85=}\x83=}\x838\x81\x86=\x81\x86:\x81\x82>\x81\x82=w\x83?w\x83Ot\x81St\x81P\x86\x80L\x86\x80B\x83\x7f?\x83\x7f=\x82\x82>\x82\x82N{\x86H{\x86A\x82\x85K\x82\x85B\x85\x7fB\x85\x7fB\x8b\x85A\x8b\x85B\x83\x85@\x83\x85;\x86\x89?\x86\x89>\x86\x84A\x86\x848v\x81?v\x81I\x81\x81M\x81\x81R\x87\x7fU\x87\x7fT\x88~U\x88~R\x83~S\x83~N{yO{yR\x86\x80P\x86\x80T\x87\x7fQ\x87\x7fQ\x89\x81Q\x89\x81R\x88\x85S\x88\x85O\x80\x80N\x80\x80J\x83\x7fJ\x83\x7fN\x86\x7fM\x86\x7fL\x83\x88J\x83\x88M\x81\x82L\x81\x82O\x84\x82R\x84\x82R{\x80O{\x80K~}O~}R\x7f\x83N\x7f\x83N\x81\x86N\x81\x86Ny\x7fMy\x7fN\x84\x82N\x84\x82Ly\x82Ry\x82O\x81\x82M\x81\x82K|\x83Q|\x83O\x81\x82M\x81\x82J|\x80N|\x80I}\x84D}\x84K\x8a\x83M\x8a\x83M\x85}P\x85}R\x85\x83N\x85\x83Kz|Hz|H~}H~}Nm~Rm~N\x83~I\x83~O\x81\x80O\x81\x80J\x7f\x80K\x7f\x80J\x83\x80K\x83\x80Ix\x84Kx\x84L\x81\x84L\x81\x84J}\x83J}\x83K{\x7fK{\x7fGz}Cz}Ex\x83Hx\x83Jz{Jz{M\x7f\x82N\x7f\x82K}\x83F}\x83Ey\x7fEy\x7fGs\x7fHs\x7fG}\x83F}\x83Fv\x80Ev\x80Fw\x85Gw\x85G\x83\x84J\x83\x84B|\x85D|\x85@\x80\x80@\x80\x80D\x80\x82C\x80\x82B\x84\x86C\x84\x86A\x80\x81@\x80\x81Cu\x87Bu\x87I{\x83C{\x83C\x82\x82A\x82\x82@|\x85<|\x85@{\x88@{\x88D\x81\x89A\x81\x89;z\x857z\x85?\x7f\x84>\x7f\x84@\x81\x80A\x81\x80<\x83\x86;\x83\x86=}\x83:}\x83F\x7f|L\x7f|J\x8d\x85O\x8d\x85F\x8d\x85D\x8d\x85;}\x84B}\x84A\x81~D\x81~>\x80\x85A\x80\x85B{|={|?\x82\x82@\x82\x82;\x81\x827\x81\x82=w\x85=w\x85Gw\x82Iw\x82I}\x83K}\x83K\x8e\x80I\x8e\x80Q\x8d\x7fS\x8d\x7fR\x87\x7fU\x87\x7fQ\x88\x81Q\x88\x81N\x84\x83Q\x84\x83N\x85\x80O\x85\x80M\x88\x82P\x88\x82U\x81\x80P\x81\x80Tz\x7fQz\x7fOy\x7fOy\x7fN\x80\x82N\x80\x82Q\x85\x81R\x85\x81N\x87~L\x87~K\x87\x80M\x87\x80P\x8b\x85L\x8b\x85Q\x7f\x7fN\x7f\x7fQ\x7f\x81M\x7f\x81O\x84\x84Q\x84\x84Q\x80\x82Q\x80\x82I\x7f\x84J\x7f\x84Hn\x80On\x80I\x87\x87I\x87\x87Q\x7f\x80M\x7f\x80N\x83~L\x83~O\x81\x81O\x81\x81N\x7f\x80I\x7f\x80K\x82\x80N\x82\x80O\x80\x84Q\x80\x84O~\x83K~\x83Kt\x84Ot\x84P~\x85M~\x85L\x7f\x82K\x7f\x82Pz\x82Pz\x82J{\x81E{\x81L|\x81M|\x81J\x81\x81J\x81\x81K|\x83M|\x83K\x82\x80J\x82\x80I|\x82H|\x82P~\x89O~\x89Hx|Kx|Lw\x83Fw\x83N~\x87R~\x87P\x84\x80M\x84\x80>v|?v|E~\x81D~\x81Gx\x80Kx\x80I{\x7fD{\x7fB}\x7fD}\x7fG~\x84H~\x84J\x85\x80I\x85\x80H\x82\x80F\x82\x80=}\x80?}\x80D\x81\x82F\x81\x82C\x81\x84F\x81\x84Dt\x80Bt\x80B\x80\x81C\x80\x81A}\x82=}\x82C{\x86@{\x86Bv\x84Gv\x84?\x80\x7f=\x80\x7f?\x81\x89A\x81\x895q\x855q\x85@x\x82Ex\x82>|\x7f@|\x7f:~\x82>~\x82@\x84\x86@\x84\x867\x7f\x837\x7f\x83O~}T~}P\x8a\x83R\x8a\x83R\x8f\x7fL\x8f\x7f6x\x817x\x81?\x89\x83@\x89\x83H\x80\x80G\x80\x80I\x81\x83J\x81\x83H\x85\x85J\x85\x85J\x85\x82F\x85\x82M~\x80L~\x80Os\x80Ts\x80S~\x80R~\x80K\x86\x80N\x86\x80L\x8d\x81M\x8d\x81M\x87\x7fP\x87\x7fS\x84\x82Q\x84\x82M\x81{J\x81{S\x84}T\x84}T\x88\x82S\x88\x82U~\x7fT~\x7fO\x80}P\x80}Q\x85~Q\x85~P\x88\x82N\x88\x82M}\x80J}\x80M\x80\x81J\x80\x81I\x80\x82O\x80\x82S\x86\x83O\x86\x83T\x80\x7fR\x80\x7fL\x82\x7fK\x82\x7fT\x85\x80N\x85\x80L\x7f\x81O\x7f\x81P\x88\x80M\x88\x80Mw\x85Pw\x85O\x86\x87J\x86\x87Ov\x81Nv\x81M\x80\x84L\x80\x84Ox\x81Mx\x81M}\x80O}\x80P{\x83M{\x83M\x80\x82K\x80\x82H~\x80L~\x80Nz\x83Oz\x83M\x82}K\x82}O~\x83R~\x83R|\x85Q|\x85Nz\x7fKz\x7fQx~Rx~L}\x85K}\x85O\x82\x81N\x82\x81Q}\x81Q}\x81L~{M~{P\x7f~L\x7f~I\x80\x82H\x80\x82J\x7f\x83N\x7f\x83F}\x89J}\x89J\x7f\x83I\x7f\x83J\x81\x86I\x81\x86Et\x86Gt\x86K\x7f\x83J\x7f\x83I\x82\x84G\x82\x84Gz\x84Dz\x84Ky\x80Ey\x80G\x80\x80F\x80\x80G\x82\x85E\x82\x85>}\x81B}\x81Cv\x81Fv\x81=\x80\x84?\x80\x84C\x81\x81A\x81\x81C\x80\x82C\x80\x82@r\x82<r\x82>\x82\x83@\x82\x83C{\x82@{\x828w\x7f9w\x7f>x\x87<x\x87<|\x81>|\x81A{\x86@{\x86D\x80\x7fB\x80\x7f<v\x7f<v\x7f=\x83\x82>\x83\x82>}\x83<}\x83N}\x82R}\x82N\x8e\x81N\x8e\x81O\x8b|O\x8b|K\x87\x83K\x87\x83L\x82\x84M\x82\x84Q\x8d}R\x8d}N\x85}O\x85}M\x90{O\x90{U\x8d\x81Q\x8d\x81P\x89\x80O\x89\x80L\x7f~N\x7f~R\x88\x80S\x88\x80U\x8f\x84S\x8f\x84L\x81\x7fM\x81\x7fR\x82~S\x82~T\x84\x83V\x84\x83T\x83}R\x83}O\x7fzL\x7fzK\x86\x80P\x86\x80N\x7f\x83O\x7f\x83Q}\x81P}\x81S{}O{}Q\x86\x84P\x86\x84Q{}O{}J\x7f\x7fO\x7f\x7fL\x81\x81N\x81\x81Q\x80\x80K\x80\x80J\x81\x7fK\x81\x7fO}\x80N}\x80Q\x86\x82Q\x86\x82H}~N}~O{yO{yEr\x81Gr\x81S\x7f~O\x7f~O}\x80I}\x80S\x85\x86T\x85\x86Jy\x80Ly\x80P\x80\x84Q\x80\x84M\x82\x84M\x82\x84O\x80{R\x80{L\x7f}O\x7f}M~\x80I~\x80M|\x81K|\x81Ew~Fw~M\x82\x80L\x82\x80J|\x83O|\x83K{|L{|Ez\x87Jz\x87O{\x7fL{\x7fI}\x81L}\x81My\x80Py\x80N\x84\x81N\x84\x81M{\x88J{\x88Lz\x85Nz\x85?\x88\x80A\x88\x80J|\x86G|\x86Fx~Ex~G\x85~E\x85~E\x83\x8bH\x83\x8bD\x80\x82E\x80\x82H~\x84E~\x84Dz\x84Bz\x84Bx\x85Fx\x85E~\x84G~\x84=w\x82>w\x82E\x86\x7fE\x86\x7f>y\x81?y\x81E}\x86C}\x86@}\x87;}\x87F}\x81F}\x81<\x80\x7f;\x80\x7fA\x7f\x86A\x7f\x86Cy\x84Dy\x84?s\x82?s\x82;|\x85=|\x85>\x85\x83<\x85\x83A|\x87@|\x878\x84\x827\x84\x822\x8b\x879\x8b\x87:z\x862z\x86M|\x7fQ|\x7fP\x92|S\x92|W\x88~R\x88~I\x8a\x80H\x8a\x80L\x86}O\x86}R\x8b~U\x8b~R\x8a\x7fS\x8a\x7fP\x91}U\x91}V\x87~V\x87~T\x86\x7fQ\x86\x7fQ\x83}P\x83}N\x82zS\x82zR\x8b\x80S\x8b\x80U\x89{T\x89{X\x83{X\x83{L{\x80K{\x80T\x85\x7fS\x85\x7fR\x89\x81R\x89\x81Q\x82zQ\x82zQ\x7fzR\x7fzTu~Pu~U\x87\x81P\x87\x81R\x8b~P\x8b~M\x87\x86N\x87\x86Kx~Ox~N\x8d\x83P\x8d\x83N\x87|Q\x87|W\x85\x7fT\x85\x7fR\x7f\x82Q\x7f\x82N\x86\x80L\x86\x80L\x86\x80K\x86\x80M\x80~F\x80~N\x7f\x7fU\x7f\x7fO\x80\x81L\x80\x81L\x7f}K\x7f}L}}R}}R\x84\x7fQ\x84\x7fO\x80\x80O\x80\x80Ly\x7fQy\x7fQ\x85\x80N\x85\x80Rw\x87Qw\x87P\x87\x81Q\x87\x81N~\x82N~\x82J|yL|yL\x82\x84O\x82\x84M|\x84O|\x84M\x80\x81M\x80\x81Kx\x82Mx\x82Lx\x81Lx\x81L~\x82P~\x82N{~P{~Lw\x81Ow\x81J|}F|}Ls\x82Ls\x82D\x81\x85D\x81\x85Gt\x80Et\x80Kz\x80Iz\x80D\x80\x81F\x80\x81E\x80\x85F\x80\x85Iz\x82Fz\x82G|\x86F|\x86Fy\x82Gy\x82Hr\x80Fr\x80B\x80\x80@\x80\x80C\x7f\x82B\x7f\x82Fx\x80Hx\x80Cx\x85Hx\x85B}\x80E}\x80;w\x83<w\x83@|\x82@|\x82B{~B{~@\x83\x81?\x83\x81Bw\x7f?w\x7fBz\x88?z\x886x\x827x\x82<|\x81=|\x814\x81\x871\x81\x87Hv\x85;v\x85?\x87\x84N\x87\x848z\x82<z\x82F\x7f}N\x7f}Q\x8awR\x8awO\x8f|N\x8f|U\x84}T\x84}N{\x84H{\x84S\x8a~S\x8a~O\x8c|R\x8c|M\x84\x80S\x84\x80P\x82wS\x82wP\x89}M\x89}P\x89zS\x89zM\x84\x7fR\x84\x7fL\x86\x82N\x86\x82T\x80~U\x80~J\x89\x81K\x89\x81O\x7fzS\x7fzOy\x80Ny\x80R\x84\x7fP\x84\x7fQ|yM|yN\x80{M\x80{M}\x7fN}\x7fR\x88\x80Q\x88\x80J|\x7fN|\x7fS}\x81Q}\x81M\x84}M\x84}P\x8c\x80R\x8c\x80Q\x8a\x80O\x8a\x80R\x82\x7fN\x82\x7fQ\x83\x7fJ\x83\x7fU\x82\x84U\x82\x84M\x7f\x83Q\x7f\x83N\x7f\x81S\x7f\x81P\x83\x82L\x83\x82N\x81}M\x81}I\x82\x7fF\x82\x7fQ}\x82U}\x82N\x81\x7fL\x81\x7fN\x86\x81P\x86\x81M~\x7fJ~\x7fQ\x83}P\x83}O\x85\x7fL\x85\x7fG\x82{H\x82{P\x7f~N\x7f~K\x81~J\x81~F\x85\x80J\x85\x80O\x7f\x85Q\x7f\x85Py\x7fMy\x7fM~\x7fM~\x7fG\x81\x84K\x81\x84J|\x80J|\x80I\x82\x81Q\x82\x81P\x7f\x83L\x7f\x83H\x81\x81H\x81\x81I{\x86H{\x86I\x80\x7fJ\x80\x7fCz{Dz{Jx~Fx~H\x83\x83H\x83\x83?~~D~~F\x86\x81D\x86\x81D\x85\x80H\x85\x80D\x81\x82B\x81\x82B|\x87C|\x87Ex\x80Ex\x80?w\x88Aw\x88E\x84\x85H\x84\x85E~\x81I~\x81A}\x85A}\x85D\x81~A\x81~=\x84\x82?\x84\x82=\x7f\x80?\x7f\x80Ay\x82Ay\x82D}\x82?}\x82=z\x829z\x82:v\x819v\x81Xy}Ry}@y\x81My\x81Gv\x84@v\x84Gw\x85Ew\x859\x84\x87:\x84\x87Py\x80Ry\x80Q\x8b~N\x8b~L\x86yQ\x86yV\x88\x80S\x88\x80Q\x8b\x81S\x8b\x81O\x86\x80K\x86\x80U\x86{V\x86{O\x93}O\x93}Q\x84{Q\x84{T\x87\x80S\x87\x80R\x87\x82R\x87\x82V\x84{W\x84{O\x89xP\x89xU\x86xV\x86xQ\x87~R\x87~N\x87~P\x87~M\x81\x80T\x81\x80U|\x80P|\x80Z{\x80U{\x80K}\x81M}\x81T\x87\x83M\x87\x83Q\x82xP\x82xM\x84\x84R\x84\x84R|\x81M|\x81L\x80}K\x80}O\x84~O\x84~R\x89}O\x89}Q\x85\x80S\x85\x80T\x84\x80U\x84\x80P\x82\x83M\x82\x83M\x7fzO\x7fzS\x80\x81N\x80\x81W\x81\x87R\x81\x87O\x82\x7fO\x82\x7fJ\x86~J\x86~L\x83\x81Q\x83\x81Rw\x82Ww\x82M|\x81K|\x81Q\x87\x84Q\x87\x84Q\x86\x83O\x86\x83P\x85\x7fO\x85\x7fN\x7f\x80O\x7f\x80S~\x83S~\x83N\x85\x7fK\x85\x7fK\x82\x86M\x82\x86Ku\x7fPu\x7fJx~Lx~P}\x82R}\x82I}\x7fL}\x7fL}\x80K}\x80L\x84\x81K\x84\x81Rx\x89Qx\x89Mx\x80Jx\x80L\x7f\x85H\x7f\x85M\x83\x85M\x83\x85K\x83\x82H\x83\x82F\x80\x80H\x80\x80M\x81\x86I\x81\x86J\x80\x87K\x80\x87H\x85yI\x85yDx\x8aCx\x8aB}~E}~K\x7f~I\x7f~J\x80\x80I\x80\x80B~\x7fC~\x7fJ\x83\x80I\x83\x80H~\x81J~\x81@|\x82=|\x82?y\x80?y\x80E\x87\x7fE\x87\x7fGt\x80Ht\x80Cx\x81Dx\x81C\x8b\x85D\x8b\x856z\x829z\x827u\x876u\x87>y\x876y\x87@y\x88Cy\x881\x84\x86:\x84\x86Gy\x88;y\x88Y{\x83_{\x83J\x81\x84R\x81\x84P\x8e\x80Q\x8e\x80R\x88~R\x88~R\x8a\x7fT\x8a\x7fS\x8e|Q\x8e|N\x83\x81M\x83\x81T\x89{T\x89{T\x89\x80Q\x89\x80T\x86\x7fS\x86\x7fO\x8c|R\x8c|T\x8e\x81U\x8e\x81M\x88\x80Q\x88\x80S\x89\x81S\x89\x81Q\x83\x81R\x83\x81U\x86xN\x86xM\x86|Q\x86|T\x84\x80U\x84\x80O}}Q}}P\x84\x7fR\x84\x7fP|\x7fP|\x7fL\x86}O\x86}S}|S}|T\x8a\x82V\x8a\x82Q}~R}~R\x87\x7fP\x87\x7fO|\x81R|\x81M\x88~S\x88~Ry\x7fRy\x7fP\x85\x80P\x85\x80N\x87\x81O\x87\x81R\x80\x81T\x80\x81P\x83}N\x83}R}\x7fM}\x7fQ~~P~~Q\x81\x83N\x81\x83S~\x80P~\x80Ns|Qs|R\x81\x85S\x81\x85T\x85\x81N\x85\x81P{}O{}O|\x7fO|\x7fT\x82\x81S\x82\x81Q\x82\x86Q\x82\x86M\x7f\x82J\x7f\x82O\x81\x86O\x81\x86O|}M|}Is\x81Os\x81Kx\x85Gx\x85NrzKrzK{\x7fL{\x7fG}\x81G}\x81K\x89\x80J\x89\x80J|\x80L|\x80I}\x86K}\x86K{~L{~G\x80\x87K\x80\x87Hw\x82Hw\x82E\x82~E\x82~C\x84}E\x84}G}\x80L}\x80H|\x83H|\x83K}\x88O}\x88I{\x85G{\x85L\x84\x82K\x84\x82G\x80\x80I\x80\x80F\x7f\x82E\x7f\x82C\x80\x81E\x80\x81D{\x7fA{\x7fCz\x83Bz\x83C\x7f\x86F\x7f\x86D~\x88F~\x88A~\x83@~\x83>\x80\x80;\x80\x80@\x86\x85@\x86\x85?{\x81Z{\x81Gk\x838k\x83m~~a~~F\x82}T\x82}G\x80~F\x80~X|\x80N|\x80F\x7f~R\x7f~Q\x84\x80R\x84\x80U\x8b\x80S\x8b\x80P\x8a\x80Q\x8a\x80I\x8byL\x8byV\x8avM\x8avN\x89\x7fR\x89\x7fL}~P}~V\x81\x83O\x81\x83M\x88\x80Q\x88\x80U\x8a\x7fU\x8a\x7fO\x86\x7fM\x86\x7fS\x88{U\x88{R\x7f\x81Q\x7f\x81R\x88~P\x88~N\x83{J\x83{T\x80\x7fS\x80\x7fR\x84\x83Q\x84\x83N\x83\x81P\x83\x81Qy\x7fSy\x7fK\x80}L\x80}P\x83\x81P\x83\x81P\x83}R\x83}T\x85\x85V\x85\x85P\x84\x80R\x84\x80J\x86\x7fN\x86\x7fT}}O}}X\x86\x80U\x86\x80W\x80\x80S\x80\x80S}\x84R}\x84Q\x82\x84T\x82\x84R\x83\x80Q\x83\x80S\x80}S\x80}U\x80\x84U\x80\x84U|\x81Q|\x81S\x80{U\x80{O{\x7fN{\x7fPy\x80Sy\x80R\x82\x7fR\x82\x7fQ{\x85O{\x85S}\x81O}\x81T~\x86T~\x86Q\x80\x87T\x80\x87Q\x84\x84M\x84\x84L~\x80L~\x80Qz\x80Mz\x80Lv\x85Mv\x85L\x81\x82M\x81\x82M\x81~M\x81~H|\x85L|\x85M{\x81M{\x81Hy\x81My\x81Iw\x80Kw\x80K\x7f}G\x7f}F\x80\x83G\x80\x83N{\x80K{\x80My\x82Ky\x82I}\x87K}\x87K\x84\x83E\x84\x83A\x80\x7fB\x80\x7fK\x81\x85L\x81\x85H\x82\x85H\x82\x85E{\x80H{\x80Fz~Hz~Jt\x82Gt\x82I\x81\x82J\x81\x82D\x80\x87B\x80\x87Ev\x82Dv\x82I\x80\x81H\x80\x81F\x82\x8cI\x82\x8cB\x82\x80D\x82\x80D\x82\x87B\x82\x87Aw\x83@w\x83:z}7z}>{\x80H{\x805y\x895y\x89Aw\x856w\x85Qz\x85Uz\x85<\x82\x84L\x82\x84Tp\x89Fp\x89E\x80\x82P\x80\x82L\x84{M\x84{V\x8a\x85S\x8a\x85V\x87\x83X\x87\x83N\x8b}Q\x8b}V\x91\x81R\x91\x81J\x87\x7fM\x87\x7fR\x85yP\x85yT\x89}S\x89}P\x8a~O\x8a~U~}W~}Q\x86\x7fQ\x86\x7fV\x88yT\x88yL\x87zL\x87zS~xQ~xZ~~W~~Mx\x81Nx\x81O\x85\x82U\x85\x82L\x84}L\x84}S\x82}V\x82}Q\x83zP\x83zU\x7f\x7fT\x7f\x7fT\x89\x85S\x89\x85U\x7f\x80S\x7f\x80I|}L|}H\x84}F\x84}N\x82\x82O\x82\x82P\x83\x84O\x83\x84N\x89\x7fN\x89\x7fR\x84\x81R\x84\x81P\x82~K\x82~Pr|Kr|Lw\x80Ow\x80N\x82\x83Q\x82\x83Nx\x7fNx\x7fFy\x7fNy\x7fX|\x84P|\x84P\x7f\x7fO\x7f\x7fM\x85\x82Q\x85\x82U\x80\x80Q\x80\x80Py\x7fNy\x7fO\x82\x7fR\x82\x7fR\x84\x84S\x84\x84Q}\x83S}\x83N}\x80I}\x80Q\x82\x80N\x82\x80I\x82\x82I\x82\x82K~\x82N~\x82O\x81\x84L\x81\x84N\x80\x80L\x80\x80R\x82\x83P\x82\x83Q|\x81T|\x81K}\x7fM}\x7fN\x7f\x80I\x7f\x80K\x82\x85K\x82\x85Jy\x83Jy\x83K\x82\x82G\x82\x82I|\x81J|\x81H\x80\x85L\x80\x85N~\x82N~\x82L\x82\x86I\x82\x86B\x81\x84F\x81\x84Hz~Ez~F\x80~H\x80~H~\x80E~\x80E\x82\x80I\x82\x80E~\x7fG~\x7fE{\x81E{\x81I\x82~K\x82~E}\x85H}\x85=\x82}@\x82}?y~?y~<x\x7f=x\x7fCx\x84Ax\x84w{zn{zHz~az~Hvz?vzUz\x7fKz\x7fGv\x86Pv\x86E\x85\x87C\x85\x87H\x81\x83M\x81\x83O\x86\x85Q\x86\x85M\x82\x81L\x82\x81O\x7f\x84N\x7f\x84S\x85\x80P\x85\x80U\x85\x80T\x85\x80P\x84\x7fO\x84\x7fN\x80|L\x80|U\x86\x7fS\x86\x7fT\x82\x84Q\x82\x84M\x87{M\x87{N\x87uL\x87uL\x88\x7fL\x88\x7fM\x87\x80P\x87\x80T\x86\x80R\x86\x80N\x85\x7fS\x85\x7fH\x80\x82I\x80\x82S|~V|~Qu}Pu}S\x87}T\x87}U\x82\x80R\x82\x80M\x88\x86S\x88\x86Q\x7f\x86O\x7f\x86Qx\x81Ux\x81T{}S{}Q\x89\x83N\x89\x83O\x83}Q\x83}T~\x82O~\x82N\x80\x81N\x80\x81T\x80}V\x80}S~\x81Q~\x81M\x81\x80O\x81\x80Ry\x7fOy\x7fPs\x81Qs\x81P\x7f\x80P\x7f\x80N\x81~R\x81~Q\x86\x82P\x86\x82Q\x84\x81O\x84\x81R\x84\x82S\x84\x82P{\x84U{\x84O{\x7fO{\x7fS\x82\x82T\x82\x82T~\x82U~\x82P\x81\x85O\x81\x85R\x83\x80O\x83\x80V\x80~R\x80~T~\x83N~\x83J\x82\x81M\x82\x81K\x83\x85M\x83\x85O{\x81R{\x81Nz\x80Mz\x80O\x80\x81O\x80\x81L\x81|K\x81|M|\x86L|\x86I\x87\x84J\x87\x84I\x83\x83L\x83\x83H{\x82G{\x82Lq~Oq~Hx\x82Kx\x82E\x7f\x82J\x7f\x82N{\x85M{\x85J|\x7fL|\x7fCv\x84Bv\x84K\x7f\x86K\x7f\x86G\x7f~K\x7f~I}\x85K}\x85B\x7f\x80C\x7f\x80Cz\x80Bz\x80?...
That's not the whole string, it is much longer. What I know is that it is a 160*120 image and it uses YUV colorspace. It has 3 layers.
The documentation to the library I'm using does not provide any example how to decode this string into an image so I need some help with it. I seems that the string contains information about pixels but I do not understand the format of the string.
I have found this C++ function to convert YUV to RGB but I don't know how to use it on the string I have. Any ideas?
void yuvToRgb(byte *y, byte *u, byte *v, byte *r, byte *g, byte *b) {
int c = (*y) - 16;
int d = (*u) - 128;
int e = (*v) - 128;
int R = (298 * c) + (409 * e) + (128);
int G = (298 * c) - (100 * d) - (208 * e) + 128;
int B = (298 * c) + (516 * d) + (128);
R >>= 8;
G >>= 8;
B >>= 8;
//Change the values
(*r) = clip(R);
(*g) = clip(G);
(*b) = clip(B);
}
A:
The data looks to me like 4:4:4 YUV with the data samples interleaved rather than planar. Converting that to English, the bytes decode as
Y1 U1 V1 Y2 U2 V2 Y3 U3 V3 ...
so the Y, U and V values of the first pixel, then of the second pixel, and so on.
I'm guessing at that because of the good correllation between every third value. This should make it pretty straightforward to convert to an RGB triple using the code you have.
Once you have the RGB triples it's likely that they will be in a simple scan, so knowing that it's 160x120 is very useful (i.e. the first 160 RGB value are the top line, the next 160 the 2nd line and so on).
My completely untested translation of the C++ code to Python (2.6+) would be something like this:
def clip(v):
# Clip to 0-255
v = max(v, 0)
v = min(v, 255)
return v
def yuvToRgb(y, u, v):
c = y - 16
d = u - 128
e = v - 128
R = (298 * c) + (409 * e) + 128
G = (298 * c) - (100 * d) - (208 * e) + 128
B = (298 * c) + (516 * d) + 128
R >>= 8
G >>= 8
B >>= 8
return (clip(R), clip(G), clip(B))
b = bytearray('\x84K\x7f\x86K\x7f\x86G\x7f~K\x7f~I}\x85K}\x85') # etc...
RGB = []
for i in xrange(0, len(b), 3):
RGB.append(yuvToRgb(b[3*i], b[3*i+1], b[3*i+2]))
I hope that's useful to you.
An alternative method would be just to use the Python Imaging Library. I'm not too familiar with it myself, but if you go in assuming it's 160x120 interleaved 4:4:4 YUV then it might be quite easy.
| How to decode this YUV colorspace string and save it as an image | So I am using one third party library which is not very well documented. It has a method which takes a picture with camera and this is what it returns:
'E{\x7fM{\x7f;\x89\x89:\x89\x89=\x81\x87<\x81\x87O\x90\x7fJ\x90\x7fB\x87\x80I\x87\x80<{\x81={\x81A\x81\x82A\x81\x82E\x81\x81:\x81\x818\x80\x81?\x80\x81?\x8c\x85C\x8c\x85Dw\x84Kw\x84K\x81}H\x81}S\x82|R\x82|N\x88xS\x88xP\x87|P\x87|H\x83}H\x83}J\x83|F\x83|S{\x80P{\x80G~zH~zDx\x7fDx\x7fI\x7f\x80M\x7f\x80I\x82yK\x82yH\x83\x80H\x83\x80K\x84\x80L\x84\x80K\x82|H\x82|G\x83\x83G\x83\x83M\x81\x80M\x81\x80K\x83~F\x83~H\x81~L\x81~N\x85|J\x85|B\x84\x82I\x84\x82K\x84\x7fJ\x84\x7fG\x83\x80F\x83\x80B~\x81G~\x81E}~G}~D}\x81B}\x81I|\x84I|\x84I\x82\x7fG\x82\x7fG\x80~E\x80~Iy\x81Jy\x81H|\x82M|\x82L\x81\x82I\x81\x82Gx\x82Hx\x82Ez\x7fGz\x7fL|\x81N|\x81G\x82\x80K\x82\x80L\x81}P\x81}J\x82\x7fH\x82\x7fCz|Dz|K}\x7fH}\x7fDs|Es|L\x83\x81I\x83\x81HxzHxzJ{\x83F{\x83G\x84\x81F\x84\x81I\x88\x85G\x88\x85Cu\x83@u\x83H}\x83D}\x83<u\x80;u\x80C\x88{C\x88{A\x7f\x82E\x7f\x82D\x84\x81C\x84\x81A}\x87A}\x87>|\x7fA|\x7fA}\x82;}\x82D\x83\x80?\x83\x80@\x80\x7fB\x80\x7fB\x80\x85A\x80\x85@u\x88>u\x888~\x848~\x84?w|=w|9|\x7f9|\x7f:\x84\x81;\x84\x81:~\x83;~\x836u\x87>u\x879{\x8d:{\x8d;\x7f\x86;\x7f\x86;y\x834y\x836\x82\x8c;\x82\x8c<y\x8b5y\x8bI~~M~~>\x88\x84:\x88\x84A\x81\x889\x81\x88B~\x81E~\x81A{\x81@{\x81O\x80\x83S\x80\x83\\\x85xf\x85xQ\x90\x80L\x90\x80G\x81\x7fK\x81\x7f@y\x83Dy\x83E~\x88E~\x88F\x81\x82M\x81\x82P\x82\x80O\x82\x80S\x85\x7fT\x85\x7fT\x83~U\x83~T\x88\x7fR\x88\x7fPz\x7fTz\x7fQ\x7f}P\x7f}Q}\x81U}\x81R\x7f\x7fO\x7f\x7fP\x83\x83N\x83\x83M\x85\x80R\x85\x80L\x87\x82O\x87\x82N\x82{N\x82{V|\x84P|\x84Rz\x83Qz\x83M\x89\x84R\x89\x84P\x8c\x85N\x8c\x85L\x80\x81I\x80\x81M|~N|~L}\x81J}\x81S\x82\x7fL\x82\x7fM}\x84I}\x84K~\x80L~\x80Lz\x80Iz\x80Hy\x80Ly\x80K~\x7fJ~\x7fJx\x82Ox\x82J\x7f\x81M\x7f\x81I\x80~J\x80~Q\x81\x82O\x81\x82M\x84\x7fH\x84\x7fO~\x80R~\x80I\x80\x84J\x80\x84J\x7f\x82L\x7f\x82N\x85\x85U\x85\x85R\x83\x87O\x83\x87U\x82\x80P\x82\x80N|\x85K|\x85O}~O}~J\x7f\x81K\x7f\x81M}\x86N}\x86I|\x82I|\x82Ix\x84Gx\x84My\x88Jy\x88J{\x7fH{\x7fF}{F}{G\x7f\x82K\x7f\x82E}\x7fE}\x7fBz\x80Dz\x80I}\x80J}\x80Dw\x81Dw\x81G\x82\x84H\x82\x84Fz\x85Cz\x85>\x85\x86;\x85\x86H\x8a\x84J\x8a\x84Cx\x80Cx\x80B\x80\x85B\x80\x85@|\x83B|\x83?{\x81@{\x81H{\x84@{\x84?y\x84Ay\x84A\x84\x85=\x84\x85;}\x81=}\x81=\x84\x86@\x84\x86:}\x85;}\x85=}\x83=}\x838\x81\x86=\x81\x86:\x81\x82>\x81\x82=w\x83?w\x83Ot\x81St\x81P\x86\x80L\x86\x80B\x83\x7f?\x83\x7f=\x82\x82>\x82\x82N{\x86H{\x86A\x82\x85K\x82\x85B\x85\x7fB\x85\x7fB\x8b\x85A\x8b\x85B\x83\x85@\x83\x85;\x86\x89?\x86\x89>\x86\x84A\x86\x848v\x81?v\x81I\x81\x81M\x81\x81R\x87\x7fU\x87\x7fT\x88~U\x88~R\x83~S\x83~N{yO{yR\x86\x80P\x86\x80T\x87\x7fQ\x87\x7fQ\x89\x81Q\x89\x81R\x88\x85S\x88\x85O\x80\x80N\x80\x80J\x83\x7fJ\x83\x7fN\x86\x7fM\x86\x7fL\x83\x88J\x83\x88M\x81\x82L\x81\x82O\x84\x82R\x84\x82R{\x80O{\x80K~}O~}R\x7f\x83N\x7f\x83N\x81\x86N\x81\x86Ny\x7fMy\x7fN\x84\x82N\x84\x82Ly\x82Ry\x82O\x81\x82M\x81\x82K|\x83Q|\x83O\x81\x82M\x81\x82J|\x80N|\x80I}\x84D}\x84K\x8a\x83M\x8a\x83M\x85}P\x85}R\x85\x83N\x85\x83Kz|Hz|H~}H~}Nm~Rm~N\x83~I\x83~O\x81\x80O\x81\x80J\x7f\x80K\x7f\x80J\x83\x80K\x83\x80Ix\x84Kx\x84L\x81\x84L\x81\x84J}\x83J}\x83K{\x7fK{\x7fGz}Cz}Ex\x83Hx\x83Jz{Jz{M\x7f\x82N\x7f\x82K}\x83F}\x83Ey\x7fEy\x7fGs\x7fHs\x7fG}\x83F}\x83Fv\x80Ev\x80Fw\x85Gw\x85G\x83\x84J\x83\x84B|\x85D|\x85@\x80\x80@\x80\x80D\x80\x82C\x80\x82B\x84\x86C\x84\x86A\x80\x81@\x80\x81Cu\x87Bu\x87I{\x83C{\x83C\x82\x82A\x82\x82@|\x85<|\x85@{\x88@{\x88D\x81\x89A\x81\x89;z\x857z\x85?\x7f\x84>\x7f\x84@\x81\x80A\x81\x80<\x83\x86;\x83\x86=}\x83:}\x83F\x7f|L\x7f|J\x8d\x85O\x8d\x85F\x8d\x85D\x8d\x85;}\x84B}\x84A\x81~D\x81~>\x80\x85A\x80\x85B{|={|?\x82\x82@\x82\x82;\x81\x827\x81\x82=w\x85=w\x85Gw\x82Iw\x82I}\x83K}\x83K\x8e\x80I\x8e\x80Q\x8d\x7fS\x8d\x7fR\x87\x7fU\x87\x7fQ\x88\x81Q\x88\x81N\x84\x83Q\x84\x83N\x85\x80O\x85\x80M\x88\x82P\x88\x82U\x81\x80P\x81\x80Tz\x7fQz\x7fOy\x7fOy\x7fN\x80\x82N\x80\x82Q\x85\x81R\x85\x81N\x87~L\x87~K\x87\x80M\x87\x80P\x8b\x85L\x8b\x85Q\x7f\x7fN\x7f\x7fQ\x7f\x81M\x7f\x81O\x84\x84Q\x84\x84Q\x80\x82Q\x80\x82I\x7f\x84J\x7f\x84Hn\x80On\x80I\x87\x87I\x87\x87Q\x7f\x80M\x7f\x80N\x83~L\x83~O\x81\x81O\x81\x81N\x7f\x80I\x7f\x80K\x82\x80N\x82\x80O\x80\x84Q\x80\x84O~\x83K~\x83Kt\x84Ot\x84P~\x85M~\x85L\x7f\x82K\x7f\x82Pz\x82Pz\x82J{\x81E{\x81L|\x81M|\x81J\x81\x81J\x81\x81K|\x83M|\x83K\x82\x80J\x82\x80I|\x82H|\x82P~\x89O~\x89Hx|Kx|Lw\x83Fw\x83N~\x87R~\x87P\x84\x80M\x84\x80>v|?v|E~\x81D~\x81Gx\x80Kx\x80I{\x7fD{\x7fB}\x7fD}\x7fG~\x84H~\x84J\x85\x80I\x85\x80H\x82\x80F\x82\x80=}\x80?}\x80D\x81\x82F\x81\x82C\x81\x84F\x81\x84Dt\x80Bt\x80B\x80\x81C\x80\x81A}\x82=}\x82C{\x86@{\x86Bv\x84Gv\x84?\x80\x7f=\x80\x7f?\x81\x89A\x81\x895q\x855q\x85@x\x82Ex\x82>|\x7f@|\x7f:~\x82>~\x82@\x84\x86@\x84\x867\x7f\x837\x7f\x83O~}T~}P\x8a\x83R\x8a\x83R\x8f\x7fL\x8f\x7f6x\x817x\x81?\x89\x83@\x89\x83H\x80\x80G\x80\x80I\x81\x83J\x81\x83H\x85\x85J\x85\x85J\x85\x82F\x85\x82M~\x80L~\x80Os\x80Ts\x80S~\x80R~\x80K\x86\x80N\x86\x80L\x8d\x81M\x8d\x81M\x87\x7fP\x87\x7fS\x84\x82Q\x84\x82M\x81{J\x81{S\x84}T\x84}T\x88\x82S\x88\x82U~\x7fT~\x7fO\x80}P\x80}Q\x85~Q\x85~P\x88\x82N\x88\x82M}\x80J}\x80M\x80\x81J\x80\x81I\x80\x82O\x80\x82S\x86\x83O\x86\x83T\x80\x7fR\x80\x7fL\x82\x7fK\x82\x7fT\x85\x80N\x85\x80L\x7f\x81O\x7f\x81P\x88\x80M\x88\x80Mw\x85Pw\x85O\x86\x87J\x86\x87Ov\x81Nv\x81M\x80\x84L\x80\x84Ox\x81Mx\x81M}\x80O}\x80P{\x83M{\x83M\x80\x82K\x80\x82H~\x80L~\x80Nz\x83Oz\x83M\x82}K\x82}O~\x83R~\x83R|\x85Q|\x85Nz\x7fKz\x7fQx~Rx~L}\x85K}\x85O\x82\x81N\x82\x81Q}\x81Q}\x81L~{M~{P\x7f~L\x7f~I\x80\x82H\x80\x82J\x7f\x83N\x7f\x83F}\x89J}\x89J\x7f\x83I\x7f\x83J\x81\x86I\x81\x86Et\x86Gt\x86K\x7f\x83J\x7f\x83I\x82\x84G\x82\x84Gz\x84Dz\x84Ky\x80Ey\x80G\x80\x80F\x80\x80G\x82\x85E\x82\x85>}\x81B}\x81Cv\x81Fv\x81=\x80\x84?\x80\x84C\x81\x81A\x81\x81C\x80\x82C\x80\x82@r\x82<r\x82>\x82\x83@\x82\x83C{\x82@{\x828w\x7f9w\x7f>x\x87<x\x87<|\x81>|\x81A{\x86@{\x86D\x80\x7fB\x80\x7f<v\x7f<v\x7f=\x83\x82>\x83\x82>}\x83<}\x83N}\x82R}\x82N\x8e\x81N\x8e\x81O\x8b|O\x8b|K\x87\x83K\x87\x83L\x82\x84M\x82\x84Q\x8d}R\x8d}N\x85}O\x85}M\x90{O\x90{U\x8d\x81Q\x8d\x81P\x89\x80O\x89\x80L\x7f~N\x7f~R\x88\x80S\x88\x80U\x8f\x84S\x8f\x84L\x81\x7fM\x81\x7fR\x82~S\x82~T\x84\x83V\x84\x83T\x83}R\x83}O\x7fzL\x7fzK\x86\x80P\x86\x80N\x7f\x83O\x7f\x83Q}\x81P}\x81S{}O{}Q\x86\x84P\x86\x84Q{}O{}J\x7f\x7fO\x7f\x7fL\x81\x81N\x81\x81Q\x80\x80K\x80\x80J\x81\x7fK\x81\x7fO}\x80N}\x80Q\x86\x82Q\x86\x82H}~N}~O{yO{yEr\x81Gr\x81S\x7f~O\x7f~O}\x80I}\x80S\x85\x86T\x85\x86Jy\x80Ly\x80P\x80\x84Q\x80\x84M\x82\x84M\x82\x84O\x80{R\x80{L\x7f}O\x7f}M~\x80I~\x80M|\x81K|\x81Ew~Fw~M\x82\x80L\x82\x80J|\x83O|\x83K{|L{|Ez\x87Jz\x87O{\x7fL{\x7fI}\x81L}\x81My\x80Py\x80N\x84\x81N\x84\x81M{\x88J{\x88Lz\x85Nz\x85?\x88\x80A\x88\x80J|\x86G|\x86Fx~Ex~G\x85~E\x85~E\x83\x8bH\x83\x8bD\x80\x82E\x80\x82H~\x84E~\x84Dz\x84Bz\x84Bx\x85Fx\x85E~\x84G~\x84=w\x82>w\x82E\x86\x7fE\x86\x7f>y\x81?y\x81E}\x86C}\x86@}\x87;}\x87F}\x81F}\x81<\x80\x7f;\x80\x7fA\x7f\x86A\x7f\x86Cy\x84Dy\x84?s\x82?s\x82;|\x85=|\x85>\x85\x83<\x85\x83A|\x87@|\x878\x84\x827\x84\x822\x8b\x879\x8b\x87:z\x862z\x86M|\x7fQ|\x7fP\x92|S\x92|W\x88~R\x88~I\x8a\x80H\x8a\x80L\x86}O\x86}R\x8b~U\x8b~R\x8a\x7fS\x8a\x7fP\x91}U\x91}V\x87~V\x87~T\x86\x7fQ\x86\x7fQ\x83}P\x83}N\x82zS\x82zR\x8b\x80S\x8b\x80U\x89{T\x89{X\x83{X\x83{L{\x80K{\x80T\x85\x7fS\x85\x7fR\x89\x81R\x89\x81Q\x82zQ\x82zQ\x7fzR\x7fzTu~Pu~U\x87\x81P\x87\x81R\x8b~P\x8b~M\x87\x86N\x87\x86Kx~Ox~N\x8d\x83P\x8d\x83N\x87|Q\x87|W\x85\x7fT\x85\x7fR\x7f\x82Q\x7f\x82N\x86\x80L\x86\x80L\x86\x80K\x86\x80M\x80~F\x80~N\x7f\x7fU\x7f\x7fO\x80\x81L\x80\x81L\x7f}K\x7f}L}}R}}R\x84\x7fQ\x84\x7fO\x80\x80O\x80\x80Ly\x7fQy\x7fQ\x85\x80N\x85\x80Rw\x87Qw\x87P\x87\x81Q\x87\x81N~\x82N~\x82J|yL|yL\x82\x84O\x82\x84M|\x84O|\x84M\x80\x81M\x80\x81Kx\x82Mx\x82Lx\x81Lx\x81L~\x82P~\x82N{~P{~Lw\x81Ow\x81J|}F|}Ls\x82Ls\x82D\x81\x85D\x81\x85Gt\x80Et\x80Kz\x80Iz\x80D\x80\x81F\x80\x81E\x80\x85F\x80\x85Iz\x82Fz\x82G|\x86F|\x86Fy\x82Gy\x82Hr\x80Fr\x80B\x80\x80@\x80\x80C\x7f\x82B\x7f\x82Fx\x80Hx\x80Cx\x85Hx\x85B}\x80E}\x80;w\x83<w\x83@|\x82@|\x82B{~B{~@\x83\x81?\x83\x81Bw\x7f?w\x7fBz\x88?z\x886x\x827x\x82<|\x81=|\x814\x81\x871\x81\x87Hv\x85;v\x85?\x87\x84N\x87\x848z\x82<z\x82F\x7f}N\x7f}Q\x8awR\x8awO\x8f|N\x8f|U\x84}T\x84}N{\x84H{\x84S\x8a~S\x8a~O\x8c|R\x8c|M\x84\x80S\x84\x80P\x82wS\x82wP\x89}M\x89}P\x89zS\x89zM\x84\x7fR\x84\x7fL\x86\x82N\x86\x82T\x80~U\x80~J\x89\x81K\x89\x81O\x7fzS\x7fzOy\x80Ny\x80R\x84\x7fP\x84\x7fQ|yM|yN\x80{M\x80{M}\x7fN}\x7fR\x88\x80Q\x88\x80J|\x7fN|\x7fS}\x81Q}\x81M\x84}M\x84}P\x8c\x80R\x8c\x80Q\x8a\x80O\x8a\x80R\x82\x7fN\x82\x7fQ\x83\x7fJ\x83\x7fU\x82\x84U\x82\x84M\x7f\x83Q\x7f\x83N\x7f\x81S\x7f\x81P\x83\x82L\x83\x82N\x81}M\x81}I\x82\x7fF\x82\x7fQ}\x82U}\x82N\x81\x7fL\x81\x7fN\x86\x81P\x86\x81M~\x7fJ~\x7fQ\x83}P\x83}O\x85\x7fL\x85\x7fG\x82{H\x82{P\x7f~N\x7f~K\x81~J\x81~F\x85\x80J\x85\x80O\x7f\x85Q\x7f\x85Py\x7fMy\x7fM~\x7fM~\x7fG\x81\x84K\x81\x84J|\x80J|\x80I\x82\x81Q\x82\x81P\x7f\x83L\x7f\x83H\x81\x81H\x81\x81I{\x86H{\x86I\x80\x7fJ\x80\x7fCz{Dz{Jx~Fx~H\x83\x83H\x83\x83?~~D~~F\x86\x81D\x86\x81D\x85\x80H\x85\x80D\x81\x82B\x81\x82B|\x87C|\x87Ex\x80Ex\x80?w\x88Aw\x88E\x84\x85H\x84\x85E~\x81I~\x81A}\x85A}\x85D\x81~A\x81~=\x84\x82?\x84\x82=\x7f\x80?\x7f\x80Ay\x82Ay\x82D}\x82?}\x82=z\x829z\x82:v\x819v\x81Xy}Ry}@y\x81My\x81Gv\x84@v\x84Gw\x85Ew\x859\x84\x87:\x84\x87Py\x80Ry\x80Q\x8b~N\x8b~L\x86yQ\x86yV\x88\x80S\x88\x80Q\x8b\x81S\x8b\x81O\x86\x80K\x86\x80U\x86{V\x86{O\x93}O\x93}Q\x84{Q\x84{T\x87\x80S\x87\x80R\x87\x82R\x87\x82V\x84{W\x84{O\x89xP\x89xU\x86xV\x86xQ\x87~R\x87~N\x87~P\x87~M\x81\x80T\x81\x80U|\x80P|\x80Z{\x80U{\x80K}\x81M}\x81T\x87\x83M\x87\x83Q\x82xP\x82xM\x84\x84R\x84\x84R|\x81M|\x81L\x80}K\x80}O\x84~O\x84~R\x89}O\x89}Q\x85\x80S\x85\x80T\x84\x80U\x84\x80P\x82\x83M\x82\x83M\x7fzO\x7fzS\x80\x81N\x80\x81W\x81\x87R\x81\x87O\x82\x7fO\x82\x7fJ\x86~J\x86~L\x83\x81Q\x83\x81Rw\x82Ww\x82M|\x81K|\x81Q\x87\x84Q\x87\x84Q\x86\x83O\x86\x83P\x85\x7fO\x85\x7fN\x7f\x80O\x7f\x80S~\x83S~\x83N\x85\x7fK\x85\x7fK\x82\x86M\x82\x86Ku\x7fPu\x7fJx~Lx~P}\x82R}\x82I}\x7fL}\x7fL}\x80K}\x80L\x84\x81K\x84\x81Rx\x89Qx\x89Mx\x80Jx\x80L\x7f\x85H\x7f\x85M\x83\x85M\x83\x85K\x83\x82H\x83\x82F\x80\x80H\x80\x80M\x81\x86I\x81\x86J\x80\x87K\x80\x87H\x85yI\x85yDx\x8aCx\x8aB}~E}~K\x7f~I\x7f~J\x80\x80I\x80\x80B~\x7fC~\x7fJ\x83\x80I\x83\x80H~\x81J~\x81@|\x82=|\x82?y\x80?y\x80E\x87\x7fE\x87\x7fGt\x80Ht\x80Cx\x81Dx\x81C\x8b\x85D\x8b\x856z\x829z\x827u\x876u\x87>y\x876y\x87@y\x88Cy\x881\x84\x86:\x84\x86Gy\x88;y\x88Y{\x83_{\x83J\x81\x84R\x81\x84P\x8e\x80Q\x8e\x80R\x88~R\x88~R\x8a\x7fT\x8a\x7fS\x8e|Q\x8e|N\x83\x81M\x83\x81T\x89{T\x89{T\x89\x80Q\x89\x80T\x86\x7fS\x86\x7fO\x8c|R\x8c|T\x8e\x81U\x8e\x81M\x88\x80Q\x88\x80S\x89\x81S\x89\x81Q\x83\x81R\x83\x81U\x86xN\x86xM\x86|Q\x86|T\x84\x80U\x84\x80O}}Q}}P\x84\x7fR\x84\x7fP|\x7fP|\x7fL\x86}O\x86}S}|S}|T\x8a\x82V\x8a\x82Q}~R}~R\x87\x7fP\x87\x7fO|\x81R|\x81M\x88~S\x88~Ry\x7fRy\x7fP\x85\x80P\x85\x80N\x87\x81O\x87\x81R\x80\x81T\x80\x81P\x83}N\x83}R}\x7fM}\x7fQ~~P~~Q\x81\x83N\x81\x83S~\x80P~\x80Ns|Qs|R\x81\x85S\x81\x85T\x85\x81N\x85\x81P{}O{}O|\x7fO|\x7fT\x82\x81S\x82\x81Q\x82\x86Q\x82\x86M\x7f\x82J\x7f\x82O\x81\x86O\x81\x86O|}M|}Is\x81Os\x81Kx\x85Gx\x85NrzKrzK{\x7fL{\x7fG}\x81G}\x81K\x89\x80J\x89\x80J|\x80L|\x80I}\x86K}\x86K{~L{~G\x80\x87K\x80\x87Hw\x82Hw\x82E\x82~E\x82~C\x84}E\x84}G}\x80L}\x80H|\x83H|\x83K}\x88O}\x88I{\x85G{\x85L\x84\x82K\x84\x82G\x80\x80I\x80\x80F\x7f\x82E\x7f\x82C\x80\x81E\x80\x81D{\x7fA{\x7fCz\x83Bz\x83C\x7f\x86F\x7f\x86D~\x88F~\x88A~\x83@~\x83>\x80\x80;\x80\x80@\x86\x85@\x86\x85?{\x81Z{\x81Gk\x838k\x83m~~a~~F\x82}T\x82}G\x80~F\x80~X|\x80N|\x80F\x7f~R\x7f~Q\x84\x80R\x84\x80U\x8b\x80S\x8b\x80P\x8a\x80Q\x8a\x80I\x8byL\x8byV\x8avM\x8avN\x89\x7fR\x89\x7fL}~P}~V\x81\x83O\x81\x83M\x88\x80Q\x88\x80U\x8a\x7fU\x8a\x7fO\x86\x7fM\x86\x7fS\x88{U\x88{R\x7f\x81Q\x7f\x81R\x88~P\x88~N\x83{J\x83{T\x80\x7fS\x80\x7fR\x84\x83Q\x84\x83N\x83\x81P\x83\x81Qy\x7fSy\x7fK\x80}L\x80}P\x83\x81P\x83\x81P\x83}R\x83}T\x85\x85V\x85\x85P\x84\x80R\x84\x80J\x86\x7fN\x86\x7fT}}O}}X\x86\x80U\x86\x80W\x80\x80S\x80\x80S}\x84R}\x84Q\x82\x84T\x82\x84R\x83\x80Q\x83\x80S\x80}S\x80}U\x80\x84U\x80\x84U|\x81Q|\x81S\x80{U\x80{O{\x7fN{\x7fPy\x80Sy\x80R\x82\x7fR\x82\x7fQ{\x85O{\x85S}\x81O}\x81T~\x86T~\x86Q\x80\x87T\x80\x87Q\x84\x84M\x84\x84L~\x80L~\x80Qz\x80Mz\x80Lv\x85Mv\x85L\x81\x82M\x81\x82M\x81~M\x81~H|\x85L|\x85M{\x81M{\x81Hy\x81My\x81Iw\x80Kw\x80K\x7f}G\x7f}F\x80\x83G\x80\x83N{\x80K{\x80My\x82Ky\x82I}\x87K}\x87K\x84\x83E\x84\x83A\x80\x7fB\x80\x7fK\x81\x85L\x81\x85H\x82\x85H\x82\x85E{\x80H{\x80Fz~Hz~Jt\x82Gt\x82I\x81\x82J\x81\x82D\x80\x87B\x80\x87Ev\x82Dv\x82I\x80\x81H\x80\x81F\x82\x8cI\x82\x8cB\x82\x80D\x82\x80D\x82\x87B\x82\x87Aw\x83@w\x83:z}7z}>{\x80H{\x805y\x895y\x89Aw\x856w\x85Qz\x85Uz\x85<\x82\x84L\x82\x84Tp\x89Fp\x89E\x80\x82P\x80\x82L\x84{M\x84{V\x8a\x85S\x8a\x85V\x87\x83X\x87\x83N\x8b}Q\x8b}V\x91\x81R\x91\x81J\x87\x7fM\x87\x7fR\x85yP\x85yT\x89}S\x89}P\x8a~O\x8a~U~}W~}Q\x86\x7fQ\x86\x7fV\x88yT\x88yL\x87zL\x87zS~xQ~xZ~~W~~Mx\x81Nx\x81O\x85\x82U\x85\x82L\x84}L\x84}S\x82}V\x82}Q\x83zP\x83zU\x7f\x7fT\x7f\x7fT\x89\x85S\x89\x85U\x7f\x80S\x7f\x80I|}L|}H\x84}F\x84}N\x82\x82O\x82\x82P\x83\x84O\x83\x84N\x89\x7fN\x89\x7fR\x84\x81R\x84\x81P\x82~K\x82~Pr|Kr|Lw\x80Ow\x80N\x82\x83Q\x82\x83Nx\x7fNx\x7fFy\x7fNy\x7fX|\x84P|\x84P\x7f\x7fO\x7f\x7fM\x85\x82Q\x85\x82U\x80\x80Q\x80\x80Py\x7fNy\x7fO\x82\x7fR\x82\x7fR\x84\x84S\x84\x84Q}\x83S}\x83N}\x80I}\x80Q\x82\x80N\x82\x80I\x82\x82I\x82\x82K~\x82N~\x82O\x81\x84L\x81\x84N\x80\x80L\x80\x80R\x82\x83P\x82\x83Q|\x81T|\x81K}\x7fM}\x7fN\x7f\x80I\x7f\x80K\x82\x85K\x82\x85Jy\x83Jy\x83K\x82\x82G\x82\x82I|\x81J|\x81H\x80\x85L\x80\x85N~\x82N~\x82L\x82\x86I\x82\x86B\x81\x84F\x81\x84Hz~Ez~F\x80~H\x80~H~\x80E~\x80E\x82\x80I\x82\x80E~\x7fG~\x7fE{\x81E{\x81I\x82~K\x82~E}\x85H}\x85=\x82}@\x82}?y~?y~<x\x7f=x\x7fCx\x84Ax\x84w{zn{zHz~az~Hvz?vzUz\x7fKz\x7fGv\x86Pv\x86E\x85\x87C\x85\x87H\x81\x83M\x81\x83O\x86\x85Q\x86\x85M\x82\x81L\x82\x81O\x7f\x84N\x7f\x84S\x85\x80P\x85\x80U\x85\x80T\x85\x80P\x84\x7fO\x84\x7fN\x80|L\x80|U\x86\x7fS\x86\x7fT\x82\x84Q\x82\x84M\x87{M\x87{N\x87uL\x87uL\x88\x7fL\x88\x7fM\x87\x80P\x87\x80T\x86\x80R\x86\x80N\x85\x7fS\x85\x7fH\x80\x82I\x80\x82S|~V|~Qu}Pu}S\x87}T\x87}U\x82\x80R\x82\x80M\x88\x86S\x88\x86Q\x7f\x86O\x7f\x86Qx\x81Ux\x81T{}S{}Q\x89\x83N\x89\x83O\x83}Q\x83}T~\x82O~\x82N\x80\x81N\x80\x81T\x80}V\x80}S~\x81Q~\x81M\x81\x80O\x81\x80Ry\x7fOy\x7fPs\x81Qs\x81P\x7f\x80P\x7f\x80N\x81~R\x81~Q\x86\x82P\x86\x82Q\x84\x81O\x84\x81R\x84\x82S\x84\x82P{\x84U{\x84O{\x7fO{\x7fS\x82\x82T\x82\x82T~\x82U~\x82P\x81\x85O\x81\x85R\x83\x80O\x83\x80V\x80~R\x80~T~\x83N~\x83J\x82\x81M\x82\x81K\x83\x85M\x83\x85O{\x81R{\x81Nz\x80Mz\x80O\x80\x81O\x80\x81L\x81|K\x81|M|\x86L|\x86I\x87\x84J\x87\x84I\x83\x83L\x83\x83H{\x82G{\x82Lq~Oq~Hx\x82Kx\x82E\x7f\x82J\x7f\x82N{\x85M{\x85J|\x7fL|\x7fCv\x84Bv\x84K\x7f\x86K\x7f\x86G\x7f~K\x7f~I}\x85K}\x85B\x7f\x80C\x7f\x80Cz\x80Bz\x80?...
That's not the whole string, it is much longer. What I know is that it is a 160*120 image and it uses YUV colorspace. It has 3 layers.
The documentation to the library I'm using does not provide any example how to decode this string into an image so I need some help with it. I seems that the string contains information about pixels but I do not understand the format of the string.
I have found this C++ function to convert YUV to RGB but I don't know how to use it on the string I have. Any ideas?
void yuvToRgb(byte *y, byte *u, byte *v, byte *r, byte *g, byte *b) {
int c = (*y) - 16;
int d = (*u) - 128;
int e = (*v) - 128;
int R = (298 * c) + (409 * e) + (128);
int G = (298 * c) - (100 * d) - (208 * e) + 128;
int B = (298 * c) + (516 * d) + (128);
R >>= 8;
G >>= 8;
B >>= 8;
//Change the values
(*r) = clip(R);
(*g) = clip(G);
(*b) = clip(B);
}
| [
"The data looks to me like 4:4:4 YUV with the data samples interleaved rather than planar. Converting that to English, the bytes decode as \nY1 U1 V1 Y2 U2 V2 Y3 U3 V3 ...\nso the Y, U and V values of the first pixel, then of the second pixel, and so on.\nI'm guessing at that because of the good correllation betwee... | [
2
] | [] | [] | [
"python",
"yuv"
] | stackoverflow_0004004710_python_yuv.txt |
Q:
Restful communication between local applications is a good idea?
I wonder if it's a good idea letting local applications (in the same server) communicate with each other entirely through Restful API?
I know this is not an uncommon thing, cause we already have applications like CouchDB that is using HTTP REST for communication, even with local applications.
But I want to take it to a higher level by creating applications that act like modules for a bigger application, which could also be a module for another application and so on. In other words, there will be a lot of local applications/modules that are communicating with Restful API.
In this way these applications/modules could be in any language and they could communicate over the wire between servers.
But I have some questions:
Is this a good idea?
Will the data transfer between them be slow?
If I do this, then each application/module have to be a HTTP server right? So if my application uses 100 applications/modules then each one of these have to be a local HTTP web server each running on a different port (http://localhost:81, http://localhost:82, http://localhost:83 and so on) right?
Any best practices/gotchas that I should know of?
A:
Is this a good idea?
Sure, perhaps.
Will the data
transfer between them be slow?
Yup! But compared to what? Compared to native, internal calls, absolutely -- it'll be glacial. Compared to some other network API, eh, not necessarily slower.
If I
do this, then each application/module
have to be a HTTP server right? So if
my application uses 100
applications/modules I have to have
100 local HTTP web servers up and
running each with different port
(http://localhost:81,
http://localhost:82,
http://localhost:83 and so on)?
Nah, no reason to allocate a port per module. All sorts of ways to do this.
Any
best practices/gotchas that I should
know of?
The only way this will succeed is if the services you are talking about are coarse enough. These have to be big, black boxy kinds of services that make the expense of calling them worthwhile. You will be incurring connection costs, data transfer costs, and data marshaling cost on each transaction. So, you want those transactions to be as rare as possible, and you want the payloads to be as large as possible to get the best benefit.
Are you talking actually using the REST architecture or just sending stuff back and forth via HTTP? (These are different things) REST incurs its own costs, include embedded linkages, ubiquitous and common data types, etc.
Finally, you simply may not need to do this. It might well be "kinda cool", a "nice to have", "looks good on the white board", but if, really, don't need it, then don't do it. Simply follow good practices of isolating your internal services so that should you decide later to do something like this, you can just insert the glue layer necessary to manage the communication, etc. Adding remote distribution will increase risk, complexity and lower performance, (scaling != performance) so there should be a Good Reason to do it at all.
That, arguably, is the "best practice" of them all.
Edit -- Response to comment:
So you mean I run ONE web server that
handle all incoming requests? But then
the modules won't be stand-alone
applications, which defeats the whole
purpose. I want each one of the
modules to be able to run by itself.
No, it doesn't defeat the purpose.
Here's the deal.
Let's say you have 3 services.
http://store.example.com/service1
http://blog.example.com/service2
http://forum.example.com/service3
At a glance, it would be fair to say that these are three different services, on 3 different machines, running in 3 different web servers.
But the truth is that these can all be running on the SAME machine, on the SAME web server, even down to (to take this to the extreme) running the exact same logic.
HTTP allows you to map all sorts of things. HTTP itself is mechanism of abstraction.
As a client all you care about is the URL to use and the payload to send. What machine it ends up talking to, or what actual code it executes it not the clients problem.
At an architecture level, you have achieved a manner of abstraction and modularization. The URLs let you organize you system is whatever LOGICAL layout you want. The PHYSICAL implementation is distinct from the logical view.
Those 3 services can be running on a single machine served by a single process. On the other hand, they can represent 1000 machines. How many machines do you think respond to "www.google.com"?
You can easily host all 3 services on a single machine, without sharing any code save the web server itself. Making it easy to move a service from its original machine to some other machine.
The host name is the simplest way to map a service to a machine. Any modern web server can service any number of different hosts. Each "virtual host" can service any number of individual service endpoints within the name space of that host. At the "host" level its trivial to relocate code from one machine to another if and when you have to.
You should explore more the capabilities of a modern web server to direct arbitrary requests to actual logic on the server. You'll find them very flexible.
A:
Is this a good idea?
Yes. It's done all the time. That's how all database servers work, for example. Linux is packed full of client/server applications communicating through TCP/IP.
Will the data transfer between them be slow?
No. TCP/IP uses localhost as a short-cut to save doing actual network I/O.
The HTTP protocol isn't the best thing for dedicated connections, but it's simple and well supported.
If I do this, then each application/module have to be a HTTP server right?
Not necessarily. Some modules can be clients and not have a server.
So if my application uses 100 applications/modules then each one of these have to be a local HTTP web server each running on a different port (http://localhost:81, http://localhost:82, http://localhost:83 and so on) right?
Yes. That's the way it works.
Any best practices/gotchas that I should know of?
Do not "hard-code" port numbers.
Do not use the "privileged" port numbers (under 1024).
Use a WSGI library and you'll be happiest making all your modules into WSGI applications. You can then use a trivial 2-line HTTP server to wrap your module.
Read this. http://docs.python.org/library/wsgiref.html#examples
A:
On using restful solutions for application integration, I believe this is a good idea and professed similar views at another question.
How to share data across an organization
A:
To be frank I don't think you need 100 servers for 100 applications, maybe just use 100 ports on the same server.
and also, RESTful interface will give you the flexibility to expand the servers and enable load balancing if you want to have the potential to scale up to huge.
A:
No - it is not a good idea if you don't have a good reason. It is a good idea to layer the code of your application so it can be "rested" at a later stage should you need it. (Or whatever performance improvement is deemed necessary.) The increased deployment complexity of "server based layers" is a good reason to not do it. I would suggest:
Write a well structured application with good, clean code.
Test it with expected production loads
if needed - refactor into layers that are servers - but.....
A better approach is to load balance the entire application. If you are doing something like rails with no state in the app server it should be no problem to run several instances in parallel.
If you are looking for complexity - disregard my answer. :-)
| Restful communication between local applications is a good idea? | I wonder if it's a good idea letting local applications (in the same server) communicate with each other entirely through Restful API?
I know this is not an uncommon thing, cause we already have applications like CouchDB that is using HTTP REST for communication, even with local applications.
But I want to take it to a higher level by creating applications that act like modules for a bigger application, which could also be a module for another application and so on. In other words, there will be a lot of local applications/modules that are communicating with Restful API.
In this way these applications/modules could be in any language and they could communicate over the wire between servers.
But I have some questions:
Is this a good idea?
Will the data transfer between them be slow?
If I do this, then each application/module have to be a HTTP server right? So if my application uses 100 applications/modules then each one of these have to be a local HTTP web server each running on a different port (http://localhost:81, http://localhost:82, http://localhost:83 and so on) right?
Any best practices/gotchas that I should know of?
| [
"\nIs this a good idea? \n\nSure, perhaps.\n\nWill the data\ntransfer between them be slow? \n\nYup! But compared to what? Compared to native, internal calls, absolutely -- it'll be glacial. Compared to some other network API, eh, not necessarily slower.\n\nIf I\ndo this, then each application/module\nhave to be a ... | [
6,
5,
2,
0,
0
] | [] | [] | [
"javascript",
"node.js",
"python",
"rest",
"ruby"
] | stackoverflow_0004002545_javascript_node.js_python_rest_ruby.txt |
Q:
What does pynotify.init stand for?
I haven't find a documentation about pynotify, so I don't know what pynotify.init() function stands for.
A:
if you are talking about the python wrapper for libnotify
the notify.init() just wrap the C function notify_init() which initializes the notifications library.
For more examples check this: http://roscidus.com/desktop/node/336
the code source is here : http://www.galago-project.org/downloads.php
the C API : http://www.galago-project.org/docs/api/libnotify/notify_8h.html
and the ubuntu Guideline : https://wiki.ubuntu.com/NotificationDevelopmentGuidelines#How%20do%20I%20get%20these%20slick%20icons
Update:
Here is the hole code in C from the source:
/**
* notify_init:
* @app_name: The name of the application initializing libnotify.
*
* Initialized libnotify. This must be called before any other functions.
*
* Returns: %TRUE if successful, or %FALSE on error.
*/
gboolean
notify_init(const char *app_name)
{
GError *error = NULL;
DBusGConnection *bus = NULL;
g_return_val_if_fail(app_name != NULL, FALSE);
g_return_val_if_fail(*app_name != '\0', FALSE);
if (_initted)
return TRUE;
_app_name = g_strdup(app_name);
g_type_init();
bus = dbus_g_bus_get(DBUS_BUS_SESSION, &error);
if (error != NULL)
{
g_message("Unable to get session bus: %s", error->message);
g_error_free(error);
return FALSE;
}
_proxy = dbus_g_proxy_new_for_name(bus,
NOTIFY_DBUS_NAME,
NOTIFY_DBUS_CORE_OBJECT,
NOTIFY_DBUS_CORE_INTERFACE);
dbus_g_connection_unref(bus);
dbus_g_object_register_marshaller(notify_marshal_VOID__UINT_STRING,
G_TYPE_NONE,
G_TYPE_UINT,
G_TYPE_STRING, G_TYPE_INVALID);
dbus_g_proxy_add_signal(_proxy, "NotificationClosed",
G_TYPE_UINT, G_TYPE_INVALID);
dbus_g_proxy_add_signal(_proxy, "ActionInvoked",
G_TYPE_UINT, G_TYPE_STRING,
G_TYPE_INVALID);
_initted = TRUE;
return TRUE;
}
so basically what it's does it initalisaing the D-BUS for communication and add some signals to it.
| What does pynotify.init stand for? | I haven't find a documentation about pynotify, so I don't know what pynotify.init() function stands for.
| [
"if you are talking about the python wrapper for libnotify\nthe notify.init() just wrap the C function notify_init() which initializes the notifications library. \nFor more examples check this: http://roscidus.com/desktop/node/336\nthe code source is here : http://www.galago-project.org/downloads.php\nthe C API : h... | [
3
] | [] | [] | [
"pynotify",
"python"
] | stackoverflow_0004004971_pynotify_python.txt |
Q:
Django-Piston - I Can't POST on a model with a ForeignKey
I'm trying to set up piston on my Django project. I ran into a brick wall when I tried to POST (create) a new entry on a model that contains a ForeignKey: location.
Here is the exact error I receive:
Cannot assign "u'1'": "Fest.location" must be a "Location" instance.
In the above example, I tried to send over location=1 in the POST.
What am I doing wrong here? Surely Foreign Keys are supported on CREATEs...
Update:
To be clear, I'm using PISTON to handle these REST API requests. My Handler currently looks like this:
class FestHandler(BaseHandler):
model = Fest`
A:
You need to assign an actual object. Something like the following should work:
loc = Location.objects.get(pk=1)
obj.location = loc
obj.save()
where obj is the model you're trying to save which has location as a foreign key.
| Django-Piston - I Can't POST on a model with a ForeignKey | I'm trying to set up piston on my Django project. I ran into a brick wall when I tried to POST (create) a new entry on a model that contains a ForeignKey: location.
Here is the exact error I receive:
Cannot assign "u'1'": "Fest.location" must be a "Location" instance.
In the above example, I tried to send over location=1 in the POST.
What am I doing wrong here? Surely Foreign Keys are supported on CREATEs...
Update:
To be clear, I'm using PISTON to handle these REST API requests. My Handler currently looks like this:
class FestHandler(BaseHandler):
model = Fest`
| [
"You need to assign an actual object. Something like the following should work:\nloc = Location.objects.get(pk=1)\nobj.location = loc\nobj.save()\n\nwhere obj is the model you're trying to save which has location as a foreign key.\n"
] | [
2
] | [] | [] | [
"django",
"django_piston",
"python"
] | stackoverflow_0004005347_django_django_piston_python.txt |
Q:
Fast python tutorial for Django beginners?
Is there a FAST python tutorial for Django beginners?
A:
Google Python Class. It's a 2-day class providing written matrial, lecture videos and exercises.
A:
This is small tutorial and fasted paced
http://www.ibiblio.org/swaroopch/byteofpython/read/
I would suggest that you pick and choose the articles by Mertz from the "Charming python" columns
http://gnosis.cx/publish/tech_index_cp.html
Python in 10 minutes :)
http://www.korokithakis.net/tutorials/python
| Fast python tutorial for Django beginners? | Is there a FAST python tutorial for Django beginners?
| [
"Google Python Class. It's a 2-day class providing written matrial, lecture videos and exercises.\n",
"This is small tutorial and fasted paced\n\nhttp://www.ibiblio.org/swaroopch/byteofpython/read/\n\nI would suggest that you pick and choose the articles by Mertz from the \"Charming python\" columns\n\nhttp://gno... | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004005521_django_python.txt |
Q:
Ways to give a SQLite a variable name
I am tracking changes made to a levels in a game. The way I currently track changes is in a sqlite database. Each level is supposed to have its own database, as just one database for all the levels would provide complications when adding and deleting levels. So for each level, I want a database that has the same name as that level. SO that changes made to level "foo" get written to database "foo". I don't need to edit the tables just the actual name of the database. I guess now that I could just use a file renaming function in python, but I would like to know if there is any way to change names from the start.
Heres an example:
connection = sqlite.connect('\database\foo.db')
cursor = connection.cursor()
Where foo is the variable
A:
You'll need to post some code for us to answer this completely.
You can use the ALTER TABLE command to rename the tables within your database, you can rename your sqlite db file on disk if you close it first, and you can use a variable in your python code to represent the name of the DB you're using. But you need to be more specific if you want a more specific answer.
| Ways to give a SQLite a variable name | I am tracking changes made to a levels in a game. The way I currently track changes is in a sqlite database. Each level is supposed to have its own database, as just one database for all the levels would provide complications when adding and deleting levels. So for each level, I want a database that has the same name as that level. SO that changes made to level "foo" get written to database "foo". I don't need to edit the tables just the actual name of the database. I guess now that I could just use a file renaming function in python, but I would like to know if there is any way to change names from the start.
Heres an example:
connection = sqlite.connect('\database\foo.db')
cursor = connection.cursor()
Where foo is the variable
| [
"You'll need to post some code for us to answer this completely.\nYou can use the ALTER TABLE command to rename the tables within your database, you can rename your sqlite db file on disk if you close it first, and you can use a variable in your python code to represent the name of the DB you're using. But you need... | [
0
] | [] | [] | [
"database",
"python",
"sqlite"
] | stackoverflow_0004005709_database_python_sqlite.txt |
Q:
web2py: Where should I store private, application-specific files?
I have just started working on web2py. Personally, I find it easier to learn than Django.
My query is that I have to load a file at application startup. Its a pickled hashtable. Where should I store this file so that the system is able to see it
My code is :
import cPickle as pickle
def index():
"""
Load the file into memory and message the number of entries
"""
f = open('tables.pkl','rb')
session.tables = pickle.load(f)
f.close()
terms = len(session.tables.keys())
message = 'The total entries in table = ' + str(terms)
return dict(message=message)
As you can see, I have put the code in index() to load it at startup. At present I am using the absolute path upto the physical location of the 'tables.pkl' file. Where should i put it in my application folder.
Also, I want tables variable to be available to all functions in the controller. Is session.tables the right way to go? It is just a search app so there is no user login.
The table has to be loaded only once for all users accessing the page.
Thank you.
A:
I think the private folder would be a good place for this. You can get the absolute path with:
import os
fp = os.path.join(request.folder,'private','tables.pkl')
I would use cache instead of session if the file is not unique per user.
| web2py: Where should I store private, application-specific files? | I have just started working on web2py. Personally, I find it easier to learn than Django.
My query is that I have to load a file at application startup. Its a pickled hashtable. Where should I store this file so that the system is able to see it
My code is :
import cPickle as pickle
def index():
"""
Load the file into memory and message the number of entries
"""
f = open('tables.pkl','rb')
session.tables = pickle.load(f)
f.close()
terms = len(session.tables.keys())
message = 'The total entries in table = ' + str(terms)
return dict(message=message)
As you can see, I have put the code in index() to load it at startup. At present I am using the absolute path upto the physical location of the 'tables.pkl' file. Where should i put it in my application folder.
Also, I want tables variable to be available to all functions in the controller. Is session.tables the right way to go? It is just a search app so there is no user login.
The table has to be loaded only once for all users accessing the page.
Thank you.
| [
"I think the private folder would be a good place for this. You can get the absolute path with:\nimport os\nfp = os.path.join(request.folder,'private','tables.pkl') \n\nI would use cache instead of session if the file is not unique per user. \n"
] | [
4
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0004004794_python_web2py.txt |
Q:
Get CURRENT_FILE_ENCODING for a python file or environment
How can I tell the encoding of the source file from inside a running python process, if it is even possible?
A:
encoding = open(__file__).encoding
This might work in some circumstances, but take note of http://docs.python.org/library/stdtypes.html#file.encoding
| Get CURRENT_FILE_ENCODING for a python file or environment | How can I tell the encoding of the source file from inside a running python process, if it is even possible?
| [
"encoding = open(__file__).encoding\nThis might work in some circumstances, but take note of http://docs.python.org/library/stdtypes.html#file.encoding\n"
] | [
2
] | [
"If you examine __file__, it will give you the file name of the running code. If it ends in \".pyc\" or \".pyo\", clip off the last character. This is the source file of the running code. Read that file, looking for the encoding header.\nNote that this is a simplification, and it can get much harder to find the ... | [
-1
] | [
"encoding",
"python"
] | stackoverflow_0004005928_encoding_python.txt |
Q:
How to build a conceptual search engine?
I would like to build an internal search engine (I have a very large collection of thousands of XML files) that is able to map queries to concepts. For example, if I search for "big cats", I would want highly ranked results to return documents with "large cats" as well. But I may also be interested in having it return "huge animals", albeit at a much lower relevancy score.
I'm currently reading through the Natural Language Processing in Python book, and it seems WordNet has some word mappings that might prove useful, though I'm not sure how to integrate that into a search engine. Could I use Lucene to do this? How?
From further research, it seems "latent semantic analysis" is relevant to what I'm looking for but I'm not sure how to implement it.
Any advice on how to get this done?
A:
I'm not sure how to integrate that into a search engine. Could I use Lucene to do this? How?
Step 1. Stop.
Step 2. Get something to work.
Step 3. By then, you'll understand more about Python and Lucene and other tools and ways you might integrate them.
Don't start by trying to solve integration problems. Software can always be integrated. That's what an Operating System does. It integrates software. Sometimes you want "tighter" integration, but that's never the first problem to solve.
The first problem to solve is to get your search or concept thing or whatever it is to work as a dumb-old command-line application. Or pair of applications knit together by passing files around or knit together with OS pipes or something.
Later, you can try and figure out how to make the user experience seamless.
But don't start with integration and don't stall because of integration questions. Set integration aside and get something to work.
A:
This is an incredibly hard problem and it can't be solved in a way that would always produce adequate results. I'd suggest to stick to some very simple principles instead so that the results are at least predictable. I think you need 2 things: some basic morphology engine plus a dictionary of synonyms.
Whenever a search query arrives, for each word you
Look for a literal match
"Normalize/canonicalze" the word using the morphology engine, i.e. make it singular, first form, etc and look for matches
Look for synonyms of the word
Then repeat for all combinations of the input words, i.e. "big cats", "big cat", "huge cats" huge cat" etc.
In fact, you need to store your index data in canonical form, too (singluar, first form etc) along with the literal form.
As for concepts, such as cats are also animals - this is where it gets tricky. It never really worked, because otherwise Google would have been returning conceptual matches already, but it's not doing that.
A:
First, I agree with most of the advice here about starting slow, and first building bits and pieces of this grand plan, devising a minimal first product and continuing from there.
Second, if you want to use some Wordnet functionality with Lucene, there is a contrib package for interfacing Lucene queries with Wordnet. I have no idea whether it was ported over to pylucene. Good luck and be careful out there.
A:
First , write a piece of python code that will return you pineapple , orange , papaya when you input apple. By focusing on "is" relation of semantic network. Then continue with has a relationship and so on.
I think at the end , you might get a fairly sufficient piece of code for a school project.
| How to build a conceptual search engine? | I would like to build an internal search engine (I have a very large collection of thousands of XML files) that is able to map queries to concepts. For example, if I search for "big cats", I would want highly ranked results to return documents with "large cats" as well. But I may also be interested in having it return "huge animals", albeit at a much lower relevancy score.
I'm currently reading through the Natural Language Processing in Python book, and it seems WordNet has some word mappings that might prove useful, though I'm not sure how to integrate that into a search engine. Could I use Lucene to do this? How?
From further research, it seems "latent semantic analysis" is relevant to what I'm looking for but I'm not sure how to implement it.
Any advice on how to get this done?
| [
"\nI'm not sure how to integrate that into a search engine. Could I use Lucene to do this? How?\n\nStep 1. Stop.\nStep 2. Get something to work.\nStep 3. By then, you'll understand more about Python and Lucene and other tools and ways you might integrate them.\nDon't start by trying to solve integration problems... | [
9,
1,
1,
0
] | [] | [] | [
"lsa",
"lucene",
"nlp",
"python",
"search"
] | stackoverflow_0004003840_lsa_lucene_nlp_python_search.txt |
Q:
Is possible to know the path of the file of a subclass in python?
I have a plugin system. The plugins subclass from a common ancestor... ad look like this:
-- SDK
--- basePlugin.py
-- PLUGINS
--- PluginA
---- Plugin.py
---- Config.ini
--- PluginB
---- Plugin.py
---- Config.ini
I need to read the info of Config.ini in basePlugin.py __init__. CUrrently in each plugin I do:
class PluginA(BaseSync):
__init__(self, path):
super(PluginA,self).__init__(self, __file__)
But wonder if is possible to know in the parent class in which file is located the sub-class...
A:
Assuming BaseSync is a new-style class, the parent class BaseSync could find the file that defines PluginA this way:
import sys
class BaseSync(object):
def __init__(self):
path=sys.modules[self.__module__].__file__
(so you don't have to pass the path explicitly).
| Is possible to know the path of the file of a subclass in python? | I have a plugin system. The plugins subclass from a common ancestor... ad look like this:
-- SDK
--- basePlugin.py
-- PLUGINS
--- PluginA
---- Plugin.py
---- Config.ini
--- PluginB
---- Plugin.py
---- Config.ini
I need to read the info of Config.ini in basePlugin.py __init__. CUrrently in each plugin I do:
class PluginA(BaseSync):
__init__(self, path):
super(PluginA,self).__init__(self, __file__)
But wonder if is possible to know in the parent class in which file is located the sub-class...
| [
"Assuming BaseSync is a new-style class, the parent class BaseSync could find the file that defines PluginA this way:\nimport sys\nclass BaseSync(object):\n def __init__(self):\n path=sys.modules[self.__module__].__file__\n\n(so you don't have to pass the path explicitly).\n"
] | [
26
] | [] | [] | [
"inheritance",
"plugins",
"python"
] | stackoverflow_0004006102_inheritance_plugins_python.txt |
Q:
How to choose 10 different integers from range (0, 99)
I want to choose 10 random integers from 0 to 99. I know I can use:
random.randint(a, b)
But how to tell the randint() that I only want different integers.
Do I have to just check after each random generation to see if the integer has already been generated and call the method again? That does not seem like an optimal solution.
A:
from random import sample
sample(range(0, 100), 10)
A:
Here's general strategy that is language independent. Generate an array of 100 entries from 0 to 99. Choose a random number from 0 to 99 and swap the entry at that position with the element at position 0. Then successively choose a random number from i to 99, where i = 1 to 9 and swap the element at that position with the one at element i. Your 10 random numbers are in the first 10 positions of the array.
A:
This may not be a solution depending on what you will need to use this for... but have you thought of splitting it off into 10 different random number generators? Ex. 0-9, 10-19, 20-29, etc. I guess that's not really as "random" as you are specifying different ranges and are guaranteed 1 number from each range. The only other solution I can think of would be to have a list of the random integers, iterate through and check to see if the random number has been generated yet and if so run the random.randint() again.
A:
Here is a language independent solution:
integer numbers[10];
for(integer i = 0; i < 10; i += 1) {
integer num = randomInteger(min = 0, max = (99 - i));
boolean hasFoundDuplicate = false;
for(integer j = 0; j < i && hasFoundDuplicate == false; j += 1) {
if(numbers[j] == num) {
num = 99 + 1 - i + j;
hasFoundDuplicate = true;
}
}
numbers[i] = num;
}
| How to choose 10 different integers from range (0, 99) | I want to choose 10 random integers from 0 to 99. I know I can use:
random.randint(a, b)
But how to tell the randint() that I only want different integers.
Do I have to just check after each random generation to see if the integer has already been generated and call the method again? That does not seem like an optimal solution.
| [
"from random import sample\n\nsample(range(0, 100), 10)\n\n",
"Here's general strategy that is language independent. Generate an array of 100 entries from 0 to 99. Choose a random number from 0 to 99 and swap the entry at that position with the element at position 0. Then successively choose a random number fro... | [
10,
8,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004006054_python.txt |
Q:
python - 'str' object has no attribute 'execute'
First time python user here, be gentle.... ;-)
Python 2.6 on OSX
Got a class which just has some wrappers around sqlite... here it is
from pysqlite2 import dbapi2 as sqlite
class SqliteDB:
connection = ''
curser = ''
def connect(self):
try:
self.connection = sqlite.connect("pagespeed.sqlite")
self.curser = self.connection.cursor()
except sqlite.Error, e:
print "Ooops: ", e.args[0]
def find_or_create(self, table, column, value):
self.curser.execute("SELECT id FROM ? WHERE ?=? LIMIT 1", (table, column, value))
records = self.curser.fetchall()
if records.count() == false:
self.curser.execute("INSERT into ? SET ?=?", (table, column, value))
self.curser.execute("SELECT id FROM ? WHERE ?=? LIMIT 1", (table, column, value))
print records
and I call it like this in a separate file
import sqlitedb
def main():
db = sqlitedb.SqliteDB()
db.connect
url_id = db.find_or_create('urls', 'url', 'http://www.example.com')
however I get this error,
Traceback (most recent call last):
File "update_urls.py", line 17, in <module>
main()
File "update_urls.py", line 11, in main
url_id = db.find_or_create('urls', 'url', 'http://www.example.com')
File "....../sqlitedb.py", line 16, in find_or_create
self.curser.execute("SELECT id FROM ? WHERE ?=? LIMIT 1", (table, column, value))
AttributeError: 'str' object has no attribute 'execute'
So it's almost like self.curser is not getting a curser, or is self not correct?
Not to sure if what I am doing is right here....
cheers
A:
I don't know what's wrong, but at the very least:
db.connect
should be
db.connect()
e.g. call the function.
OK. S.Lott had the answer, I just found an other bug :)
A:
Do Not Do This.
class SqliteDB:
connection = ''
curser = ''
It doesn't "declare" any variables. This isn't C++ or Java.
Do this.
class SqliteDB:
def __init__( self ):
self.connection = None
self.cursor= None
A:
And the 3rd bug:
self.curser.execute("SELECT id FROM ? WHERE ?=? LIMIT 1", (table, column, value))
You can't parameterise table names and column names. All you can parameterise are things that can be an expression in SQL syntax. You'll need to do something like this:
sql = "SELECT id FROM %s WHERE %s = ? LIMIT 1" % (table, column)
self.curser.execute(sql, (value, ))
Oh yeah, to save the flurry of comments: or use the modern string.format(data) method instead of the antique string % data operator.
A:
I will also add that this will not work :
curser.execute("SELECT id FROM ? WHERE ?=? LIMIT 1", (table, column, value))
because placeholders (?) doesn't work for table name, you should rather use string formatting before if you still want to use table name as parameter:
query = "SELECT id FROM %s WHERE %s=? LIMIT 1" % (table, column)
curser.execute(query, (value, ))
and one last thing "curser" is misspelled :)
| python - 'str' object has no attribute 'execute' | First time python user here, be gentle.... ;-)
Python 2.6 on OSX
Got a class which just has some wrappers around sqlite... here it is
from pysqlite2 import dbapi2 as sqlite
class SqliteDB:
connection = ''
curser = ''
def connect(self):
try:
self.connection = sqlite.connect("pagespeed.sqlite")
self.curser = self.connection.cursor()
except sqlite.Error, e:
print "Ooops: ", e.args[0]
def find_or_create(self, table, column, value):
self.curser.execute("SELECT id FROM ? WHERE ?=? LIMIT 1", (table, column, value))
records = self.curser.fetchall()
if records.count() == false:
self.curser.execute("INSERT into ? SET ?=?", (table, column, value))
self.curser.execute("SELECT id FROM ? WHERE ?=? LIMIT 1", (table, column, value))
print records
and I call it like this in a separate file
import sqlitedb
def main():
db = sqlitedb.SqliteDB()
db.connect
url_id = db.find_or_create('urls', 'url', 'http://www.example.com')
however I get this error,
Traceback (most recent call last):
File "update_urls.py", line 17, in <module>
main()
File "update_urls.py", line 11, in main
url_id = db.find_or_create('urls', 'url', 'http://www.example.com')
File "....../sqlitedb.py", line 16, in find_or_create
self.curser.execute("SELECT id FROM ? WHERE ?=? LIMIT 1", (table, column, value))
AttributeError: 'str' object has no attribute 'execute'
So it's almost like self.curser is not getting a curser, or is self not correct?
Not to sure if what I am doing is right here....
cheers
| [
"I don't know what's wrong, but at the very least:\ndb.connect \n\nshould be\ndb.connect()\n\ne.g. call the function.\nOK. S.Lott had the answer, I just found an other bug :)\n",
"Do Not Do This.\nclass SqliteDB:\n connection = ''\n curser = ''\n\nIt doesn't \"declare\" any variables. This isn't C++ or Ja... | [
7,
4,
1,
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004006257_python_sqlite.txt |
Q:
Is it possible to put strings in the copy buffer?
Preferentially using the standard libraries.
A:
Try googling "Python clipboard". There seem to be various solutions out there. Here's one called Pyperclip that claims to work across Windows/Mac/Linux
| Is it possible to put strings in the copy buffer? | Preferentially using the standard libraries.
| [
"Try googling \"Python clipboard\". There seem to be various solutions out there. Here's one called Pyperclip that claims to work across Windows/Mac/Linux\n"
] | [
2
] | [] | [] | [
"copy",
"copy_paste",
"python"
] | stackoverflow_0004006444_copy_copy_paste_python.txt |
Q:
Ignore last \n when using readlines with python
I have a file I read from that looks like:
1 value1
2 value2
3 value3
The file may or may not have a trailing \n in the last line.
The code I'm using works great, but if there is an trailing \n it fails.
Whats the best way to catch this?
My code for reference:
r=open(sys.argv[1], 'r');
for line in r.readlines():
ref=line.split();
print ref[0], ref[1]
Which would fail with a:
Traceback (most recent call last):
File "./test", line 14, in
print ref[0], ref[1]
IndexError: list index out of range
A:
You can ignore lines that contain only whitespace:
for line in r.readlines():
line = line.rstrip() # Remove trailing whitespace.
if line: # Only process non-empty lines.
ref = line.split();
print ref[0], ref[1]
A:
I don't think that you have told us the whole story. line.split() will give the same result irrespective of whether the last line is terminated by \n or not.
Note that the last line in a file being terminated by \n is the USUAL behaviour, and people are occasionally bothered by a line that's not so terminated.
If you were to do something like:
print repr(line), repr(ref)
instead of
print ref[0], ref[1]
you would be able to detect for yourself exactly what is going on, instead of leaving us to guess.
If as @Mark Byers surmises, your last line is empty or consists only of whitespace, you can ignore that line (and all other such lines) by this somewhat more simple code:
for line in r: # readlines is passe
ref = line.split() # split() ignores trailing whitespace
if ref:
print ref[0], ref[1]
Please also consider the possibility that you have only one field, not 0 or 2, in your last line.
| Ignore last \n when using readlines with python | I have a file I read from that looks like:
1 value1
2 value2
3 value3
The file may or may not have a trailing \n in the last line.
The code I'm using works great, but if there is an trailing \n it fails.
Whats the best way to catch this?
My code for reference:
r=open(sys.argv[1], 'r');
for line in r.readlines():
ref=line.split();
print ref[0], ref[1]
Which would fail with a:
Traceback (most recent call last):
File "./test", line 14, in
print ref[0], ref[1]
IndexError: list index out of range
| [
"You can ignore lines that contain only whitespace:\nfor line in r.readlines():\n line = line.rstrip() # Remove trailing whitespace.\n if line: # Only process non-empty lines.\n ref = line.split();\n print ref[0], ref[1]\n\n",
"I don't think that you have told us the whol... | [
8,
2
] | [] | [] | [
"python",
"readlines"
] | stackoverflow_0004006441_python_readlines.txt |
Q:
How to use the same variable in two classes
# I have this class:
class Test(webapp.RequestHandler):
myList = []
def get(self):
s = [self.request.get('sentence')]
self.myList.append(s)
htmlcode1 = HTML.table(self.myList)
myListLen = len(self.myList)
lastItem = self.myList[myListLen-2]
# I want to add the following to delete the contents of `myList` when I enter 'delete' in the form:
class Delete(webapp.RequestHandler):
def get(self):
if s == ['delete']:
del self.myList[:]
How can I use self.myList under Delete()?
A:
You would want to use
Test.myList
because myList is an attribute of the class, not a particular instance of that class.
| How to use the same variable in two classes | # I have this class:
class Test(webapp.RequestHandler):
myList = []
def get(self):
s = [self.request.get('sentence')]
self.myList.append(s)
htmlcode1 = HTML.table(self.myList)
myListLen = len(self.myList)
lastItem = self.myList[myListLen-2]
# I want to add the following to delete the contents of `myList` when I enter 'delete' in the form:
class Delete(webapp.RequestHandler):
def get(self):
if s == ['delete']:
del self.myList[:]
How can I use self.myList under Delete()?
| [
"You would want to use\nTest.myList\n\nbecause myList is an attribute of the class, not a particular instance of that class.\n"
] | [
6
] | [] | [] | [
"python"
] | stackoverflow_0004006518_python.txt |
Q:
Best way to keep an activity log in memcached
I'd like to build a "feed" for recent activity related to a specific section of my site. I haven't used memcache before, but I'm thinking of something like this:
When a new piece of information is submitted to the site, assign a unique key to it and also add it to memcache.
Add this key to the end of an existing list in memcache, so it can later be referenced.
When retrieving, first retrieve the list of keys from memcache
For each key retrieved, retrieve the individual piece of information
String the pieces together and return them as the "feed"
E.g., user comments: user writes, "Nice idea"
Assign a unique key to "Nice idea," let's say key "1234"
Insert a key/data pair into memcache, 1234 -> "Nice Idea"
Append "1234" to an existing list of keys: key_list -> {2341,41234,124,341,1234}
Now when retrieving, first query the key list: {2341,41234,124,341,1234}
For each key in the key list, retrieve the data:
2341 -> "Yes"
41234 -> "Good point"
124 -> "That's funny"
341 -> "I don't agree"
1234 -> "Nice Idea"
Is this a good approach?
Thanks!
A:
If the list of keys is bounded in size then it should be ok. memcache by default has a 1MB item size limit.
Sounds like memcache is the only storage for the data, is it a good idea?
| Best way to keep an activity log in memcached | I'd like to build a "feed" for recent activity related to a specific section of my site. I haven't used memcache before, but I'm thinking of something like this:
When a new piece of information is submitted to the site, assign a unique key to it and also add it to memcache.
Add this key to the end of an existing list in memcache, so it can later be referenced.
When retrieving, first retrieve the list of keys from memcache
For each key retrieved, retrieve the individual piece of information
String the pieces together and return them as the "feed"
E.g., user comments: user writes, "Nice idea"
Assign a unique key to "Nice idea," let's say key "1234"
Insert a key/data pair into memcache, 1234 -> "Nice Idea"
Append "1234" to an existing list of keys: key_list -> {2341,41234,124,341,1234}
Now when retrieving, first query the key list: {2341,41234,124,341,1234}
For each key in the key list, retrieve the data:
2341 -> "Yes"
41234 -> "Good point"
124 -> "That's funny"
341 -> "I don't agree"
1234 -> "Nice Idea"
Is this a good approach?
Thanks!
| [
"If the list of keys is bounded in size then it should be ok. memcache by default has a 1MB item size limit.\nSounds like memcache is the only storage for the data, is it a good idea?\n"
] | [
0
] | [] | [] | [
"feed",
"memcached",
"python"
] | stackoverflow_0003999496_feed_memcached_python.txt |
Q:
How to get raw XML back from lxml?
I'm using the following code to locate a div:
parser = etree.HTMLParser()
tree = etree.parse(StringIO(page), parser)
div = tree.xpath("//div[@class='content']")[0]
My only problem is, that after doing this I do not want to rely on lxml to extract the contents of said div: I just want to get back the raw XML the div contains. Is this doable or do I have to abandon this method entirely?
A:
I think you are looking for:
etree.tostring(div)
A:
Did you try tostring?
raw_xml = etree.tostring(div)
| How to get raw XML back from lxml? | I'm using the following code to locate a div:
parser = etree.HTMLParser()
tree = etree.parse(StringIO(page), parser)
div = tree.xpath("//div[@class='content']")[0]
My only problem is, that after doing this I do not want to rely on lxml to extract the contents of said div: I just want to get back the raw XML the div contains. Is this doable or do I have to abandon this method entirely?
| [
"I think you are looking for:\netree.tostring(div)\n\n",
"Did you try tostring?\nraw_xml = etree.tostring(div)\n\n"
] | [
14,
2
] | [] | [] | [
"html_parsing",
"lxml",
"python",
"xml"
] | stackoverflow_0004006668_html_parsing_lxml_python_xml.txt |
Q:
Find System Hard Disk Drive from Python?
I am working on a software installer for my current application. It needs to be installed to the System HDD. How owuld I detect the system drive and return the letter from Python?
Would the win32 extensions be useful? How about the os module pre packaged with Python?
A:
This is how to return the letter of the System drive on a Win32 platform:
import os
print os.getenv("SystemDrive")
The above snippet returns the system drive letter. In my case ( and most cases on windows) C:
A:
If you install the win32 extensions, the following will get you the information you want:
In [82]: import win32api
In [83]: drives = win32api.GetLogicalDriveStrings()
In [84]: drives
Out[84]: 'C:\\\x00D:\\\x00E:\\\x00'
In [85]: drives.split('\x00')
Out[85]: ['C:\\', 'D:\\', 'E:\\', '']
Ignore the last item, due to a terminating character in the string returned by win32's GetLogicalDriveStrings function.
| Find System Hard Disk Drive from Python? | I am working on a software installer for my current application. It needs to be installed to the System HDD. How owuld I detect the system drive and return the letter from Python?
Would the win32 extensions be useful? How about the os module pre packaged with Python?
| [
"This is how to return the letter of the System drive on a Win32 platform:\nimport os\nprint os.getenv(\"SystemDrive\")\n\nThe above snippet returns the system drive letter. In my case ( and most cases on windows) C:\n",
"If you install the win32 extensions, the following will get you the information you want:\nI... | [
16,
2
] | [] | [] | [
"disk",
"python",
"system",
"winapi"
] | stackoverflow_0004006730_disk_python_system_winapi.txt |
Q:
python re module - What regular expression to use to extract pieces of text
I have text which shows course numbers, names, grade and other information for courses taken by students. Specifically, the lines look like these:
0301 453 20071 LINEAR SYSTEMS I A 4 4 16.0
0301 481 20071 ELECTRONICS I WITH LAB A 4 4 16.0
0301 481 20084 ELECTRONICS II WITH LAB RE B 4 4 12.0
0301 713 20091 SOLID STATE PHYSICS NG 0 0 0.0
0511 454 20074 INT'L TRADE & FINANCE B 4 4 12.0
I want to write a regular expression that extracts:
LINEAR SYSTEMS I
ELECTRONICS I WITH LAB
ELECTRONICS II WITH LAB
SOLID STATE PHYSICS
INT'L TRADE & FINANCE
I wrote the following
pattCourseName = re.compile(r'([-/&A-Z\':\s]{2,})(\s+[A-Z])')
However, this gives me
LINEAR SYSTEMS I
ELECTRONICS I WITH LAB
ELECTRONICS II WITH LAB RE
SOLID STATE PHYSICS
INT'L TRADE & FINANCE
That is, I cannot get rid of the RE part.
Can someone please help with this? Thanks!
A:
If the layout is fixed as you show, then forget the regular expression, and just grab the columns you want:
course_name = line[16:45].strip()
A:
for line in open("file"):
s=filter(None,line.split(" ",4))
print s[3].replace(" ","|").split("|",1)[0]
output
$ python myscript.py
LINEAR SYSTEMS I
ELECTRONICS I WITH LAB
ELECTRONICS II WITH LAB
SOLID STATE PHYSICS
INT'L TRADE & FINANCE
| python re module - What regular expression to use to extract pieces of text | I have text which shows course numbers, names, grade and other information for courses taken by students. Specifically, the lines look like these:
0301 453 20071 LINEAR SYSTEMS I A 4 4 16.0
0301 481 20071 ELECTRONICS I WITH LAB A 4 4 16.0
0301 481 20084 ELECTRONICS II WITH LAB RE B 4 4 12.0
0301 713 20091 SOLID STATE PHYSICS NG 0 0 0.0
0511 454 20074 INT'L TRADE & FINANCE B 4 4 12.0
I want to write a regular expression that extracts:
LINEAR SYSTEMS I
ELECTRONICS I WITH LAB
ELECTRONICS II WITH LAB
SOLID STATE PHYSICS
INT'L TRADE & FINANCE
I wrote the following
pattCourseName = re.compile(r'([-/&A-Z\':\s]{2,})(\s+[A-Z])')
However, this gives me
LINEAR SYSTEMS I
ELECTRONICS I WITH LAB
ELECTRONICS II WITH LAB RE
SOLID STATE PHYSICS
INT'L TRADE & FINANCE
That is, I cannot get rid of the RE part.
Can someone please help with this? Thanks!
| [
"If the layout is fixed as you show, then forget the regular expression, and just grab the columns you want:\ncourse_name = line[16:45].strip()\n\n",
"for line in open(\"file\"):\n s=filter(None,line.split(\" \",4))\n print s[3].replace(\" \",\"|\").split(\"|\",1)[0]\n\noutput\n$ python myscript.py\nLINEAR... | [
5,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004006798_python_regex.txt |
Q:
Python list manipulation
I've got a python list
alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], [ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,999] ]
I need the result is
alist = [[0,4,8,13], [3, 4, 8, 999]]
It means first two and last two numbers in each alist element.
I need a fast way to do this as the list could be huge.
A:
[x[0][:2] + x[-1][-2:] for x in alist]
A:
The object is actually a tuple, rather than a list. This can trip you up if you're expecting it to be mutable and it's hard to read. Consider using the continuation character \ for long lines:
alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], [ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8, 999] ]
is clearer as
alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], \
[ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8, 999] ]
which also helps you spot the double bracket that makes this a tuple. For a list:
alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13], \
[ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8, 999] ]]
If list comprehension as suggested in Javier's answer doesn't meet your speed requirement, consider a numpy array.
| Python list manipulation | I've got a python list
alist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], [ [3, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,999] ]
I need the result is
alist = [[0,4,8,13], [3, 4, 8, 999]]
It means first two and last two numbers in each alist element.
I need a fast way to do this as the list could be huge.
| [
"[x[0][:2] + x[-1][-2:] for x in alist]\n\n",
"The object is actually a tuple, rather than a list. This can trip you up if you're expecting it to be mutable and it's hard to read. Consider using the continuation character \\ for long lines:\nalist = [ [0, 4, 5, 5], [2, 2, 4, 5], [6, 7, 8,13]], [ [3, 4, 5, 5], [2,... | [
12,
1
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004006794_list_python.txt |
Q:
how do I invoke jython from the python shell (ubuntu)
I like the python shell in ubuntu, it looks pretty, and I want to run jython from there. Can this be done somehow?
A:
Can't you just start a jython shell by typing jython?
Or are you trying to run ipython with jython? or do you want to run a jython program/script from an interactive python shell?
P.S.
Possibly
import subrocess
f=subprocess.Popen(['jython', '/usr/share/jython/Lib/test/test_xmllib.py'],stdout=subprocess)
for f.stdout.readline:
...
| how do I invoke jython from the python shell (ubuntu) | I like the python shell in ubuntu, it looks pretty, and I want to run jython from there. Can this be done somehow?
| [
"Can't you just start a jython shell by typing jython?\nOr are you trying to run ipython with jython? or do you want to run a jython program/script from an interactive python shell?\nP.S.\nPossibly\nimport subrocess \nf=subprocess.Popen(['jython', '/usr/share/jython/Lib/test/test_xml... | [
0
] | [] | [] | [
"jython",
"python",
"ubuntu"
] | stackoverflow_0004007009_jython_python_ubuntu.txt |
Q:
Using SoupStrainer to parse selectively
Im trying to parse a list of video game titles from a shopping site. however as the item list is all stored inside a tag .
This section of the documentation supposedly explains how to parse only part of the document but i cant work it out. my code:
from BeautifulSoup import BeautifulSoup
import urllib
import re
url = "Some Shopping Site"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
for a in soup.findAll('a',{'title':re.compile('.+') }):
print a.string
at present is prints the string inside any tag that has a not empty title reference. but it is also priting the items in the side bar that are the "specials". if i can only take the product list div, i will kill 2 birds with one stone.
Many thanks.
A:
Oh boy am i silly, i was searching for tags with atribute id = products, but it should have been product_list
heres the finaly code if anyone comes searching.
from BeautifulSoup import BeautifulSoup, SoupStrainer
import urllib
import re
start = time.clock()
url = "http://someplace.com"
html = urllib.urlopen(url).read()
product = SoupStrainer('div',{'id': 'products_list'})
soup = BeautifulSoup(html,parseOnlyThese=product)
for a in soup.findAll('a',{'title':re.compile('.+') }):
print a.string
A:
Try searching first for the product list div and then for the a tags with title:
product = soup.find('div',{'id': 'products'})
for a in product.findAll('a',{'title': re.compile('.+') }):
print a.string
| Using SoupStrainer to parse selectively | Im trying to parse a list of video game titles from a shopping site. however as the item list is all stored inside a tag .
This section of the documentation supposedly explains how to parse only part of the document but i cant work it out. my code:
from BeautifulSoup import BeautifulSoup
import urllib
import re
url = "Some Shopping Site"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
for a in soup.findAll('a',{'title':re.compile('.+') }):
print a.string
at present is prints the string inside any tag that has a not empty title reference. but it is also priting the items in the side bar that are the "specials". if i can only take the product list div, i will kill 2 birds with one stone.
Many thanks.
| [
"Oh boy am i silly, i was searching for tags with atribute id = products, but it should have been product_list\nheres the finaly code if anyone comes searching.\nfrom BeautifulSoup import BeautifulSoup, SoupStrainer\nimport urllib\nimport re\n\n\nstart = time.clock()\nurl = \"http://someplace.com\"\nhtml = urllib.u... | [
12,
0
] | [] | [] | [
"beautifulsoup",
"python",
"scrape"
] | stackoverflow_0004004979_beautifulsoup_python_scrape.txt |
Q:
How can I use a Perl module from Python?
There exists a Perl module that provides the perfect functionality for my Python app.
Is there any way for me to utilize it? (it is complicated, it would take me a month to port it)
I don't want to have to spawn a subprocess for every usage, as I need it several hundred thousand times (it is a specific type of data parser).
Thanks for your advice.
EDIT: asked for the module. It's Mail::DeliveryStatus::BounceParser. It matches mail delivery status notifications to a list of strings that may indicate a bounced mail. (it runs the DSN body/headers through a mass of regexes as well as other tests. it's a seriously awesome module.)
A:
I am not sure if this is still active but PyPerl may be of interest to you
http://wiki.python.org/moin/PyPerl
Still there should be support for most data parsers in python. It would be good, if you can point to the parser that you are looking at.
Alternatively, you could create a complete process with that perl module and use IPC, socket mechanisms to communicate data and results back and forth from your python and perl processes.
A:
I know you can use Python in Perl with Inline::Python but that isn't really your question. Perhaps there is a similar functionality in Python. Perhaps something like perlmodule?
A:
I'd use something like HTTP::Server::Simple to create a local web service. Then you just have to do queries against that. It's still an external process but it's only one.
| How can I use a Perl module from Python? | There exists a Perl module that provides the perfect functionality for my Python app.
Is there any way for me to utilize it? (it is complicated, it would take me a month to port it)
I don't want to have to spawn a subprocess for every usage, as I need it several hundred thousand times (it is a specific type of data parser).
Thanks for your advice.
EDIT: asked for the module. It's Mail::DeliveryStatus::BounceParser. It matches mail delivery status notifications to a list of strings that may indicate a bounced mail. (it runs the DSN body/headers through a mass of regexes as well as other tests. it's a seriously awesome module.)
| [
"I am not sure if this is still active but PyPerl may be of interest to you\n\nhttp://wiki.python.org/moin/PyPerl\n\nStill there should be support for most data parsers in python. It would be good, if you can point to the parser that you are looking at.\nAlternatively, you could create a complete process with that ... | [
5,
4,
2
] | [
"\nI don't want to have to spawn a subprocess for every usage, as I need it several hundred thousand times (it is a specific type of data parser).\n\nBad policy. The basic Linux shells do this kind of process forking all the time. Avoiding process spawning is a bad limitation.\nHowever, you can trivially do this.... | [
-3
] | [
"perl",
"python"
] | stackoverflow_0004002344_perl_python.txt |
Q:
Any good audio podcasts for Python and Django?
I listen to Python411 but is there any other great podcasts out there for Python and Django?
A:
I'm a fan of Django Dose.
| Any good audio podcasts for Python and Django? | I listen to Python411 but is there any other great podcasts out there for Python and Django?
| [
"I'm a fan of Django Dose.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004007005_django_python.txt |
Q:
Using python and the bittorrent protocol
I wanted to write a program with could send and receive data over a NAT router without having to set up port forwarding first. Do i need to use the bittorrent protocol or is there something better?
A:
BitTorrent is not a NAT traversal technology but a P2P file sharing protocol. Unless you want to transfer files BitTorrent probably won't help much.
Some routers will let you setup a port mapping using UPnP. (see this other question to find a Python UPnP client library)
An alternative would be to setup Teredo tunneling on your machine. That will hopefully take care of NAT traversal and give you a real unfirewalled IPv6 address behind your IPv4 NAT router.
| Using python and the bittorrent protocol | I wanted to write a program with could send and receive data over a NAT router without having to set up port forwarding first. Do i need to use the bittorrent protocol or is there something better?
| [
"BitTorrent is not a NAT traversal technology but a P2P file sharing protocol. Unless you want to transfer files BitTorrent probably won't help much.\nSome routers will let you setup a port mapping using UPnP. (see this other question to find a Python UPnP client library)\nAn alternative would be to setup Teredo tu... | [
2
] | [] | [] | [
"bittorrent",
"python"
] | stackoverflow_0004002286_bittorrent_python.txt |
Q:
What is a best practice method to log visits per page / object
Take my profile for example, or any question number of views on this site, what is the process of logging the number of visits per page or object on a website, which I presumably think includes:
Counting registered users once (this must be reflected in the db, which pages / objects the user has visited). this will also not include unregistered users
IP: log the visit of each IP per page / object; this could be troublesome as you might have 2 different people checking the same website; or you really do want to track repeat visitors.
Cookie: this will probably result in that people with multiple computers would be counted twice
other method goes here ....
The question is, what is the process and best practice to count user requests?
EDIT
I've added the computer languages to the list of tags as they are of interest to me. Feel free to include any libraries, modules, and/or extensions that achieve the task.
The question could be rephrased into:
How does someone go about measuring the number of imprints when a user goes on a page? The question is not intended to be similar to what Google analytics does, rather it should be something similar to when you click on a stackoverflow question or profile and see the number of views.
A:
The "correct" answer varies according to the situation; primarily the most desired statistic and the availability of resources to gather and process them:
eg:
Server Side
Raw web server logs
All webservers have some facility to log requests. The trouble with them is that it requires a lot of processing to get meaningful data out and, for your example scenario, they won't record application specific details; like whether or not the request was associated with a registered user.
This option won't work for what you're interested in.
File based application logs
The application programmer can apply custom code to the application to record the stuff you're most interested in to a log file. This is similiar to the webserver log; except that it can be application aware and record things like the member making the request.
The programmers may also need to build scripts which extract from these logs the stuff you're most interested. This option might be suited to a high traffic site with lots of disk space and sysadmins who know how to ensure the logs get rotated and pruned from the production servers before bad things happen.
Database based application logs
The application programmer can write custom code for the application which records every request in a database. This makes it relatively easy to run reports and makes the data instantly accessible. This solution incurs more system overhead at the time of each request so better suited to lesser traffic sites, or scenarios where the data is highly valued.
Client Side
Javascript postback
This is a consideration on top of the above options. Google analytics does this.
Each page includes some javascript code which tells the client to report back to the webserver that the page was viewed. The data might be recorded in a database, or written to file.
Has an strong advantage of improving accuracy in scenarios where impressions get lost due to heavy caching/proxying between the client and server.
Cookies
Every time a request is received from someone who doesn't present a cookie then you assume they're new and record that hit as 'anonymous' and return a uniquely identifying cookie after they login. It depends on your application as to how accurate this proves. Some applications don't lend themselves to caching so it will be quite accurate; others (high traffic) encourage caching which will reduce the accuracy. Obviously it's not much use till they re-authenticate whenever they switch browsers/location.
What's most interesting to you?
Then there's the question of what statistics are important to you. For example, in some situations you're keen to know:
how many times a page was viewed, period,
how many times a page was viewed, by a known user
how many of your known users have viewed a specific page
Thence you typically want to break it down into periods of time to see trending.
Respectively:
are we getting more views from random people?
or we getting more views from registered users?
or has pretty much every one who is going to see the page now seen it?
So back to your question: best practice for "number of imprints when a user goes on a page"?
It depends on your application.
My guess is that you're best off with a database backed application which records what is most interesting to your application and uses cookies to trace the member's sessions.
A:
The best practice for a hit counter depends on how much traffic you expect your site to receive. As wybiral suggested, you can implement something that writes to a database after every request. This might include the IP address if you want to count unique visitors, or it could be a simple as just incrementing a running total for each page or for each (page, user) pair.
But that requires a database write for every request, even if you just want to serve a static page. Ideally speaking, a scalable web app should serve as much as possible from an in-memory cache. Database or disk I/O should be avoided as much as possible.
So the ideal set up would be to build up some representation of the server's activity in-memory and then occasionally (say every 15 minutes) write those events to the database. You could conceivably queue up thousands of requests and then store them with a single database write.
There's a tutorial describing how to do exactly this in python using Celery and Carrot: http://packages.python.org/celery/tutorials/clickcounter.html. It also includes some examples of how to set up your database tables using Django models and what code to call whenever someone accesses a page.
This tutorial will certainly be helpful to you regardless of what you choose to implement, although this level of architecture might be overkill if you don't expect thousands of hits each hour.
A:
Use a database to keep a record of the unique IPs (if the IP doesn't exist in the DB, create it, otherwise continue as planned) and then query the database for the number of those entities. Index this with IP and URL to store views for individual pages. You wont have to worry about tracking registered users this way, they will be totaled into the unique IP count. As far as multiple people from one IP, there's not much you can do there short of requiring an account and counting user->to->page-views similarly.
A:
I would suggest using a persistent key/value store like Redis. If you use a list with the list key being the serialized identifier, you can store other serialized entries and use llen to find the list size.
Example (python) after initializing your Redis store:
def intializeAndPush(serializedKey, serializedValue):
if not redisStore.exists(serializedKey):
redisStore.push(serializedKey, serializedValue)
else:
if serializedValue not in redisStore.lrange(serializedKey, 0, -1):
redisStore.push(serializedKey, serializedValue)
def getSizeOf(serializedKey):
if redisStore.exists(serializedKey):
return redisStore.llen(serializedKey)
else:
return 0
Using this technique, you can use anything as serializedKey or serializedValue. If you want to store IPs with today's date or serialized login information, both are just as simple. Also, only unique serializedValues are stored since writes are locked on read (at least as I recall).
A:
I will try and implement pixel tracking to track views on your page/object. This method is used by google (google analytics) and other high profile media companies.
A:
Pixel tracking will be fine, since you can have point the trackingpixel to a HttpHandler specific for that purpose. That way you can seperate the load and even use some kind of queue for highload scenarios.
Also, you can incorporate user specific information in the tracking pixel such as WHO has visited the page.
eg:
<a href="fakeimages/imba.gif?uid=123&info2=a&info3=b" style="height:1px;width:1px;" />
Then you need to handle the request going to fakeimages/*.gif with a specific HttpHandler / php redirect/controller (whatever language you're using) and process the infos.
regards
| What is a best practice method to log visits per page / object | Take my profile for example, or any question number of views on this site, what is the process of logging the number of visits per page or object on a website, which I presumably think includes:
Counting registered users once (this must be reflected in the db, which pages / objects the user has visited). this will also not include unregistered users
IP: log the visit of each IP per page / object; this could be troublesome as you might have 2 different people checking the same website; or you really do want to track repeat visitors.
Cookie: this will probably result in that people with multiple computers would be counted twice
other method goes here ....
The question is, what is the process and best practice to count user requests?
EDIT
I've added the computer languages to the list of tags as they are of interest to me. Feel free to include any libraries, modules, and/or extensions that achieve the task.
The question could be rephrased into:
How does someone go about measuring the number of imprints when a user goes on a page? The question is not intended to be similar to what Google analytics does, rather it should be something similar to when you click on a stackoverflow question or profile and see the number of views.
| [
"The \"correct\" answer varies according to the situation; primarily the most desired statistic and the availability of resources to gather and process them:\neg:\nServer Side\nRaw web server logs\nAll webservers have some facility to log requests. The trouble with them is that it requires a lot of processing to g... | [
19,
5,
1,
1,
0,
0
] | [] | [] | [
"asp.net",
"php",
"python"
] | stackoverflow_0003673556_asp.net_php_python.txt |
Q:
Python 2.7/Windows: ttk combobox dropdown shows up underneath topmost root window
I'm experimenting with the new ttk Tile enhancements that ship with Python 2.7.
Windows 7: The code below demonstrates how the combobox dropdown shows up BEHIND our root window when the root window is configured as a topmost window ("always on top"). If you comment out the line """ root.attributes( '-topmost', 1 )""" then the combobox dropdown appears within the root window (as expected).
Anyone have any workarounds for this behavior so we can use comboboxes with 'topmost' windows?
# sample code that illustrates problem described above
import Tkinter as tkinter
import ttk
root = tkinter.Tk()
panelCombo = ttk.Frame( root )
panelCombo.pack( side='top', fill='x', padx=12, pady=8 )
valCombo = ( 'cat', 'dog', 'pig' )
varCombo = tkinter.StringVar()
varCombo.set( 'fish' )
cboCombo = ttk.Combobox( panelCombo, values=valCombo, textvariable=varCombo )
cboCombo.pack( side='left', anchor='w', padx=12, pady=8 )
# make our window 'alwaysontop'
root.attributes( '-topmost', 1 )
root.mainloop()
A:
That's a known bug in the Tk toolkit. It was fixed in release 8.5.6. Maybe you just need to wait until that release makes its way into Python.
| Python 2.7/Windows: ttk combobox dropdown shows up underneath topmost root window | I'm experimenting with the new ttk Tile enhancements that ship with Python 2.7.
Windows 7: The code below demonstrates how the combobox dropdown shows up BEHIND our root window when the root window is configured as a topmost window ("always on top"). If you comment out the line """ root.attributes( '-topmost', 1 )""" then the combobox dropdown appears within the root window (as expected).
Anyone have any workarounds for this behavior so we can use comboboxes with 'topmost' windows?
# sample code that illustrates problem described above
import Tkinter as tkinter
import ttk
root = tkinter.Tk()
panelCombo = ttk.Frame( root )
panelCombo.pack( side='top', fill='x', padx=12, pady=8 )
valCombo = ( 'cat', 'dog', 'pig' )
varCombo = tkinter.StringVar()
varCombo.set( 'fish' )
cboCombo = ttk.Combobox( panelCombo, values=valCombo, textvariable=varCombo )
cboCombo.pack( side='left', anchor='w', padx=12, pady=8 )
# make our window 'alwaysontop'
root.attributes( '-topmost', 1 )
root.mainloop()
| [
"That's a known bug in the Tk toolkit. It was fixed in release 8.5.6. Maybe you just need to wait until that release makes its way into Python.\n"
] | [
1
] | [] | [] | [
"python",
"tkinter",
"ttk",
"windows"
] | stackoverflow_0004007325_python_tkinter_ttk_windows.txt |
Q:
better way to pass data to print in python
I was going through http://web2py.com/book/default/chapter/02 and found this:
>>> print 'number is ' + str(3)
number is 3
>>> print 'number is %s' % (3)
number is 3
>>> print 'number is %(number)s' % dict(number=3)
number is 3
It has been given that The last notation is more explicit and less error prone, and is to be preferred.
I am wondering what is the advantage of using the last notation.. will it not have a performance overhead?
A:
>>> print 'number is ' + str(3)
number is 3
This is definitely the worst solution and might cause you problems if you do the beginner mistake "Value of obj: " + obj where obj is not a string or unicode object. For many concatenations, it's not readable at all - it's similar to something like echo "<p>Hello ".$username."!</p>"; in PHP (this can get arbitrarily ugly).
print 'number is %s' % (3)
number is 3
Now that is much better. Instead of a hard-to-read concatenation, you see the output format immediately. Coming back to the beginner mistake of outputting values, you can do print "Value of obj: %r" % obj, for example. I personally prefer this in most cases. But note that you cannot use it in gettext-translated strings if you have multiple format specifiers because the order might change in other languages.
As you forgot to mention it here, you can also use the new string formatting method which is similar:
>>> "number is {0}".format(3)
'number is 3'
Next, dict lookup:
>>> print 'number is %(number)s' % dict(number=3)
number is 3
As said before, gettext-translated strings might change the order of positional format specifiers, so this option is the best when working with translations. The performance drop should be negligible - if your program is not all about formatting strings.
As with the positional formatting, you can also do it in the new style:
>>> "number is {number}".format(number=3)
'number is 3'
It's hard to tell which one to take. I recommend you to use positional arguments with the % notation for simple strings and dict lookup formatting for translated strings.
A:
I can think of a few differences.
First to me is cumbersome, if more than one variable is involved. I can not speak of performance penalty on that. See additional arguments below.
The second example is positional dependent and it can be easy to change position causing errors. It also does not tell you anything about the variables.
The third example, the position of variables is not important. You use a dictionary. This makes it elegant as it does not rely on positional structuring of variables.
See the example below:
>>> print 'number is %s %s' % (3,4)
number is 3 4
>>> print 'number is %s %s' % (4,3)
number is 4 3
>>> print 'number is %(number)s %(two)s' % dict(number=3, two=4)
number is 3 4
>>> print 'number is %(number)s %(two)s' % dict(two=4, number=3)
number is 3 4
>>>
Also another part of discussion on this
"+" is the string concatenation operator.
"%" is string formatting.
In this trivial case, string formatting accomplishes the same result as concatenation. Unlike string formatting, string concatenation only works when everything is already a string. So if you miss to convert your variables to string, concatenation will cause error.
[Edit: My answer was biased towards templating since the question came from web2py where templates are so commonly involved]
As Ryan says below, the concatenation is faster than formatting.
Suggestion is
Use the first form - concatenation, if you are concatenating just two strings
Use the second form, if there are few variables. You can invariably see the positions and deal with them
Use the third form when you are doing templating i.e. formatting a large piece of string with variable data. The dictionary form helps in providing meaning to variables inside the large piece of text.
A:
I am wondering what is the advantage
of using the last notation..
Hm, as you said, the last notation is really more explicit and actually is less error prone.
will it not have a performance
overhead?
It will have little performance overhead, but it's minor if compared with data fetching from DB or network connections.
A:
It's a bad, unjustified piece of advice.
The third method is cumbersome, violates DRY, and error prone, except if:
You are writing a framework which don't have control over the format string. For example, logging module, web2py, or gettext.
The format string is extremely long.
The format string is read from a file from a config file.
The problem with the third method should be obvious when you consider that foo appears three times in this code: "%(foo)s" % dict(foo=foo). This is error prone. Most programs should not use the third method, unless they know they need to.
The second method is the simplest method, and is what you generally use in most programs. It is best used when the format string is immediate, e.g. 'values: %s %s %s' % (a, b, c) instead of taken from a variable, e.g. fmt % (a, b, c).
The first concatenation is almost never useful, except perhaps if you're building list by loops:
s = ''
for x in l:
s += str(x)
however, in that case, it's generally better and faster to use str.join():
s = ''.join(str(x) for x in l)
| better way to pass data to print in python | I was going through http://web2py.com/book/default/chapter/02 and found this:
>>> print 'number is ' + str(3)
number is 3
>>> print 'number is %s' % (3)
number is 3
>>> print 'number is %(number)s' % dict(number=3)
number is 3
It has been given that The last notation is more explicit and less error prone, and is to be preferred.
I am wondering what is the advantage of using the last notation.. will it not have a performance overhead?
| [
">>> print 'number is ' + str(3)\nnumber is 3\n\nThis is definitely the worst solution and might cause you problems if you do the beginner mistake \"Value of obj: \" + obj where obj is not a string or unicode object. For many concatenations, it's not readable at all - it's similar to something like echo \"<p>Hello ... | [
4,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004007358_python.txt |
Q:
GAE: what are the args of webapp.RequestHanderls get(*args)
I read the document
http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html
but I cant find any information of the args parameters
A:
Depends on the regular expressions in your URL matching. For example:
def main():
application = webapp.WSGIApplication([
('/rechnungsdatencontainer/([a-z0-9_-]+)', RechnungsdatencontainerHandler),
('/empfaenger/([A-Za-z0-9_-]+)/rechnungen/([A-Za-z0-9_-]+)\.?(json|pdf|xml|invoic|html)?', RechnungslisteHandler),
('/admin/credentials', CredentialsHandler),
('/', Homepage)],
debug=True)
util.run_wsgi_app(application)
RechnungsdatencontainerHandler.get() sees one parameter, RechnungslisteHandler().get() sees three and CredentialsHandler and Homepage get no parameters.
class RechnungsdatencontainerHandler(webapp.RequestHandler):
def get(containerid):
....
class RechnungslisteHandler(webapp.RequestHandler):
def get(empfaenger, rechung, fmt):
....
Basically every pair of (braces) in the RegExp results in a get parameter.
I assume you could also use named parameters, something like (?P<kundennr>[A-Za-z0-9_-]+) to get kwargs in your get function, but I haven't tried that.
| GAE: what are the args of webapp.RequestHanderls get(*args) | I read the document
http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html
but I cant find any information of the args parameters
| [
"Depends on the regular expressions in your URL matching. For example:\ndef main():\n application = webapp.WSGIApplication([\n ('/rechnungsdatencontainer/([a-z0-9_-]+)', RechnungsdatencontainerHandler),\n ('/empfaenger/([A-Za-z0-9_-]+)/rechnungen/([A-Za-z0-9_-]+)\\.?(json|pdf|xml|invoic|html)?', ... | [
6
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004007449_google_app_engine_python.txt |
Q:
How would I go about playing an alarm sound in python?
I have a clock I made and I'd like to make it an alarm clock.
A:
Assuming you're on Windows:
import winsound
winsound.PlaySound('alert.wav')
If you're on Linux (or Mac OS X I believe), you can either use pygame or call a Linux program (like mplayer) using popen. pygame example:
import pygame
pygame.init()
pygame.mixer.music.load("alert.ogg")
pygame.mixer.music.play()
pygame.event.wait()
Example using popen, which executes a command as if you were in the terminal:
from os import popen
cmd = "mplayer alert.ogg"
popen(cmd)
A:
If you have the mp3play module, and plan on playing an MP3 file, you can use this simple method.
import mp3play
filename = "C:/PATH/TO/FILE.mp3"
sound = mp3play.load(filename)
sound.play()
That code will play the entire MP3 file until it is done. If you want to only play that sound for a certain amount of time, use this:
import mp3play
import time
filename = "C:/PATH/TO/FILE.mp3"
sound = mp3play.load(filename)
time.sleep(min(30, sound.seconds())) # Plays the first 30 seconds of sound.
sound.stop()
The mp3play module can be downloaded from the Python package index
A:
On Debian/Ubuntu try this:
sudo apt-get install beep
and then:
import os
os.system('beep')
| How would I go about playing an alarm sound in python? | I have a clock I made and I'd like to make it an alarm clock.
| [
"Assuming you're on Windows: \nimport winsound\nwinsound.PlaySound('alert.wav')\n\nIf you're on Linux (or Mac OS X I believe), you can either use pygame or call a Linux program (like mplayer) using popen. pygame example:\nimport pygame\npygame.init()\n\npygame.mixer.music.load(\"alert.ogg\")\npygame.mixer.music.pla... | [
6,
3,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004006709_python_tkinter.txt |
Q:
Appending at run-time to a dictionary
I have a function named OpenAccount() which takes in the details from the User and appends it to my database dictionary.
I have a database file(module) which is imported in my function file.
I have a function called AppendRecord(key,**dictvalues) which appends values to my database file.
However I am not able to call the function and take in values at run-time to append.
It works fine with Hard-coded values.I'm posting the code.Please help me out.
def AppendRecord(key, **dictvalues):
salesDept[key] = dict(dictvalues)
and the call for hard coded values is ...
AppendRecord('Jill',Name='Jill', Acctype='Savings')
Now when I' trying to take in all the values along with the key from the user,I am not able to call the function.I'm just a beginner at Python so please pardon me for any errors:
Edited Code:
#!/usr/bin/python
import os #This module is imported so as to use clear function in the while-loop
import DB #Imports the data from database DB.py
def AppendRecord(key, **dictvalues):
DB.Accounts[key] = dict(dictvalues)
def OpenAccount(): #Opens a new a/c and appends to the database data-base.
while True:
os.system("clear") #Clears the screen once the loop is re-invoked
#Parameters taken from the user at Run-time so as to make entries in the database and append them
print '\n','Choose an Account Type'
print '\n','\n1)Savings Account','\n2)Current Account'
choice = input('Enter an optin: ')
if choice == 1:
name = raw_input('\nEnter a name: ')
depo = input('\nEnter amount(Rs.): ')
key = raw_input('\nEnter an alphanumeric-id: ')
acc= raw_input('\nEnter the Account-Type: ')
AppendRecord(key,Name=name,Initial_deposit=depo,Acctype=acc)
EDIT 1:
The Errors I get are.
File "/usr/lib/python2.5/shelve.py", line 124, in __setitem__
self.dict[key] = f.getvalue()
TypeError: 'int' object does not support item assignment
EDIT 2:
Following is the DB.py database file source code.
#!/usr/bin/python
import shelve #Module:Shelve is imported to achieve persistence
Victor = {'Name':'Victor Hughes','Acctype':'Savings'}
Xavier = {'Name':'Xavier Bosco','Acctype':'Savings'}
Louis = {'Name':'Louis Philip','Acctype':'Current'}
Beverly = {'Name':'Beverly Dsilva','Acctype':'Current'}
Accounts = shelve.open('shelfile.shl') #Accounts = {}
Accounts['Louis']= Louis
Accounts['Beverly']= Beverly
Accounts['Xavier']= Xavier
Accounts['Victor']= Victor
Accounts.close()
A:
Your problem is that the DB module is closing the shelf before you write to it. Get rid of the last line and it will work fine.
You will also need to provide a function to close it or do so manually.
#!/usr/bin/python
import shelve #Module:Shelve is imported to achieve persistence
Accounts = 0
Victor = {'Name':'Victor Hughes','Acctype':'Savings'} #???
Xavier = {'Name':'Xavier Bosco','Acctype':'Savings'}
Louis = {'Name':'Louis Philip','Acctype':'Current'}
Beverly = {'Name':'Beverly Dsilva','Acctype':'Current'}
def open_shelf(name='shelfile.shl'):
global Accounts
Accounts = shelve.open(name) #Accounts = {}
# why are you adding this every time? is this just debugging code?
Accounts['Louis']= Louis
Accounts['Beverly']= Beverly
Accounts['Xavier']= Xavier
Accounts['Victor']= Victor
def close_shelf():
Accounts.close()
You will now need to call the DB.open_shelf() function before you write to it and the DB.close_shelf function when you are done. I would recommend calling them at the beginning and end of your program respectively.
You'll note that this is really just wrapping shelve and adding pretty much zero value. I would scrap the whole DB module and just use shelve directly.
| Appending at run-time to a dictionary | I have a function named OpenAccount() which takes in the details from the User and appends it to my database dictionary.
I have a database file(module) which is imported in my function file.
I have a function called AppendRecord(key,**dictvalues) which appends values to my database file.
However I am not able to call the function and take in values at run-time to append.
It works fine with Hard-coded values.I'm posting the code.Please help me out.
def AppendRecord(key, **dictvalues):
salesDept[key] = dict(dictvalues)
and the call for hard coded values is ...
AppendRecord('Jill',Name='Jill', Acctype='Savings')
Now when I' trying to take in all the values along with the key from the user,I am not able to call the function.I'm just a beginner at Python so please pardon me for any errors:
Edited Code:
#!/usr/bin/python
import os #This module is imported so as to use clear function in the while-loop
import DB #Imports the data from database DB.py
def AppendRecord(key, **dictvalues):
DB.Accounts[key] = dict(dictvalues)
def OpenAccount(): #Opens a new a/c and appends to the database data-base.
while True:
os.system("clear") #Clears the screen once the loop is re-invoked
#Parameters taken from the user at Run-time so as to make entries in the database and append them
print '\n','Choose an Account Type'
print '\n','\n1)Savings Account','\n2)Current Account'
choice = input('Enter an optin: ')
if choice == 1:
name = raw_input('\nEnter a name: ')
depo = input('\nEnter amount(Rs.): ')
key = raw_input('\nEnter an alphanumeric-id: ')
acc= raw_input('\nEnter the Account-Type: ')
AppendRecord(key,Name=name,Initial_deposit=depo,Acctype=acc)
EDIT 1:
The Errors I get are.
File "/usr/lib/python2.5/shelve.py", line 124, in __setitem__
self.dict[key] = f.getvalue()
TypeError: 'int' object does not support item assignment
EDIT 2:
Following is the DB.py database file source code.
#!/usr/bin/python
import shelve #Module:Shelve is imported to achieve persistence
Victor = {'Name':'Victor Hughes','Acctype':'Savings'}
Xavier = {'Name':'Xavier Bosco','Acctype':'Savings'}
Louis = {'Name':'Louis Philip','Acctype':'Current'}
Beverly = {'Name':'Beverly Dsilva','Acctype':'Current'}
Accounts = shelve.open('shelfile.shl') #Accounts = {}
Accounts['Louis']= Louis
Accounts['Beverly']= Beverly
Accounts['Xavier']= Xavier
Accounts['Victor']= Victor
Accounts.close()
| [
"Your problem is that the DB module is closing the shelf before you write to it. Get rid of the last line and it will work fine.\nYou will also need to provide a function to close it or do so manually.\n#!/usr/bin/python\n\nimport shelve #Module:Shelve is imported to achieve persistence\n\n\nAcco... | [
1
] | [] | [] | [
"append",
"dictionary",
"python",
"runtime"
] | stackoverflow_0004007522_append_dictionary_python_runtime.txt |
Q:
Multiple ModelManager filter methods
def by_this(self):
return super(MyModelManager, self).get_query_set().filter(this=True)
def by_that(self):
return super(MyModelManager, self).get_query_set().filter(that=True)
If i do MyModel.objects.by_this() or by_that() it works.
But i want to do: MyModel.objects.by_this().by_that()
A:
As others say, you need custom QuerySet. Here are some examples of how to do this:
http://djangosnippets.org/snippets/562/
http://adam.gomaa.us/blog/2009/feb/16/subclassing-django-querysets/index.html
A:
MyModel.objects will return your ModelManager type, but by_this returns a queryset. So you can't call by_that on the returned object and the chaining doesn't work. You could do: MyModel.objects.by_this().filter(that=True). Or just define a by_this_and_that method in your ModelManager derived class.
A:
As ars says, your methods return a queryset. So what you need to do is to create a custom subclass of QuerySet, which contains the by_this and by_that methods, and then in MyModelManager.get_query_set return your subclassed queryset.
| Multiple ModelManager filter methods | def by_this(self):
return super(MyModelManager, self).get_query_set().filter(this=True)
def by_that(self):
return super(MyModelManager, self).get_query_set().filter(that=True)
If i do MyModel.objects.by_this() or by_that() it works.
But i want to do: MyModel.objects.by_this().by_that()
| [
"As others say, you need custom QuerySet. Here are some examples of how to do this: \nhttp://djangosnippets.org/snippets/562/\nhttp://adam.gomaa.us/blog/2009/feb/16/subclassing-django-querysets/index.html\n",
"MyModel.objects will return your ModelManager type, but by_this returns a queryset. So you can't call b... | [
1,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004007240_django_django_models_python.txt |
Q:
Can't read appended data using pickle.load() method
I have written two scripts Write.py and Read.py.
Write.py opens friends.txt in append mode and takes input for name, email ,phone no and then dumps the dictionary into the file using pickle.dump() method and every thing works fine in this script.
Read.py opens friends.txt in read mode and then loads the contents into dictionary using pickle.load() method and displays the contents of dictionary.
The main problem is in Read.py script, it justs shows the old data, it never shows the appended data ?
Write.py
#!/usr/bin/python
import pickle
ans = "y"
friends={}
file = open("friends.txt", "a")
while ans == "y":
name = raw_input("Enter name : ")
email = raw_input("Enter email : ")
phone = raw_input("Enter Phone no : ")
friends[name] = {"Name": name, "Email": email, "Phone": phone}
ans = raw_input("Do you want to add another record (y/n) ? :")
pickle.dump(friends, file)
file.close()
Read.py
#!/usr/bin/py
import pickle
file = open("friends.txt", "r")
friend = pickle.load(file)
file.close()
for person in friend:
print friend[person]["Name"], "\t", friend[person]["Email"] , "\t", friend[person]["Phone"]
What must be the problem, the code looks fine. Can some one point me in the right direction ?
Thanks.
A:
You have to call pickle.load once for each time you called pickle.dump. You write routine does not add an entry to the dictionary, it adds another dictionary. You will have to call pickle.load until the entire file is read, but this will give you several dictionaries you would have to merge. The easier way for this would be just to store the values in CSV-format. This is as simple as
with open("friends.txt", "a") as file:
file.write("{0},{1},{2}\n".format(name, email, phone))
To load the values into a dictionary you would do:
with open("friends.txt", "a") as file:
friends = dict((name, (name, email, phone)) for line in file for name, email, phone in line.split(","))
A:
You have to load from the file several times. Each writing process ignores the others, so it creates a solid block of data independent from the others in the file. If you read it afterwards, it reads only one block at a time. So you could try:
import pickle
friend = {}
with open('friends.txt') as f:
while 1:
try:
friend.update(pickle.load(f))
except EOFError:
break # no more data in the file
for person in friend.values():
print '{Name}\t{Email}\t{Phone}'.format(**person)
| Can't read appended data using pickle.load() method | I have written two scripts Write.py and Read.py.
Write.py opens friends.txt in append mode and takes input for name, email ,phone no and then dumps the dictionary into the file using pickle.dump() method and every thing works fine in this script.
Read.py opens friends.txt in read mode and then loads the contents into dictionary using pickle.load() method and displays the contents of dictionary.
The main problem is in Read.py script, it justs shows the old data, it never shows the appended data ?
Write.py
#!/usr/bin/python
import pickle
ans = "y"
friends={}
file = open("friends.txt", "a")
while ans == "y":
name = raw_input("Enter name : ")
email = raw_input("Enter email : ")
phone = raw_input("Enter Phone no : ")
friends[name] = {"Name": name, "Email": email, "Phone": phone}
ans = raw_input("Do you want to add another record (y/n) ? :")
pickle.dump(friends, file)
file.close()
Read.py
#!/usr/bin/py
import pickle
file = open("friends.txt", "r")
friend = pickle.load(file)
file.close()
for person in friend:
print friend[person]["Name"], "\t", friend[person]["Email"] , "\t", friend[person]["Phone"]
What must be the problem, the code looks fine. Can some one point me in the right direction ?
Thanks.
| [
"You have to call pickle.load once for each time you called pickle.dump. You write routine does not add an entry to the dictionary, it adds another dictionary. You will have to call pickle.load until the entire file is read, but this will give you several dictionaries you would have to merge. The easier way for thi... | [
1,
1
] | [] | [] | [
"dictionary",
"file_io",
"pickle",
"python"
] | stackoverflow_0004007753_dictionary_file_io_pickle_python.txt |
Q:
lxml memory problem
I'm trying to parse large XML files (>3GB) like this:
context = lxml.etree.iterparse(path)
for action,el in self.context:
# do sth. with el
With iterparse I thought the data is not completely loaded into RAM, but according to this article I'm wrong:
http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ (see Listing 4)
Though when I apply this solution to my code, some elements are obviously cleared which have not been parsed so far (especially child-elements of el).
Is there any other solution to this memory problem?
Thanks in advance!
A:
Don't forget to use clear(), optionally also clearing the root element, as explained here. But as I understand, you're already doing this, but apparently you are trying to access content that you have already cleared, or that is not yet parsed. It would be helpful if you could provide something more than "do sth. with el". Are you using getnext() or getprevious()? Xpath expressions?
Another option, if you really don't want to build a tree, is to use the target parser interface, which is like SAX for lxml/etree (but easier).
A:
I solved this issue by selecting the tag directly with the context:
lxml.etree.iterparse(path, tag=tag)
and not with an additional if-clause.
Thank you very much for your support!
| lxml memory problem | I'm trying to parse large XML files (>3GB) like this:
context = lxml.etree.iterparse(path)
for action,el in self.context:
# do sth. with el
With iterparse I thought the data is not completely loaded into RAM, but according to this article I'm wrong:
http://www.ibm.com/developerworks/xml/library/x-hiperfparse/ (see Listing 4)
Though when I apply this solution to my code, some elements are obviously cleared which have not been parsed so far (especially child-elements of el).
Is there any other solution to this memory problem?
Thanks in advance!
| [
"Don't forget to use clear(), optionally also clearing the root element, as explained here. But as I understand, you're already doing this, but apparently you are trying to access content that you have already cleared, or that is not yet parsed. It would be helpful if you could provide something more than \"do sth.... | [
2,
1
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0004004672_lxml_python_xml.txt |
Q:
Python: how to get the edge values from this list
I've got a python list like
a = [
[[1,2,(3,4)],[1,2,(5)],[-3,3,(3)],[8,-2,(5)]],
[[1,2,(3,4,5)],[-1,222,(3,4,5)],[99,2,(3)],[8,-2,(4,5)]]
]
The tuple in each list element is total useless, please ignore that but delete them
I want to get the max min value from each list element in each position
The exepected output structure is
li = [[xmin, ymin, xmax, ymax], [xmin, ymin, xmax, ymax] ]
In this case li is [[-3, -2, 8, 3], [-1, -2,99, 222]]
So is there any easy to do ?Thank
A:
If you have access to numpy, you can use numpy.amax. You can use the axis parameter to get the maximum of a certain column of the array.
A:
You can use zip:
a = [ [[1,2,(3,4)],[1,2,(5)],[-3,3,(3)],[8,-2,(5)] ],
[[1,2,(3,4,5)],[-1,222,(3,4,5)],[99,2,(3)],[8,-2,(4,5)] ] ]
>>> i, h = zip(*a[0]), zip(*a[1])
>>> [min(i[0]), min(i[1]), max(i[0]), max(i[1])]
[-3, -2, 8, 3]
>>> [min(h[0]), min(h[1]), max(h[0]), max(h[1])]
[-1, -2, 99, 222]
A:
First, a minor stylistic point, you should use tuples for small fix-length lists. I.e.: use (xmin, ymin, xmax, ymax) instead of [xmin, ymin, xmax, ymax].
[(min(t[0] for t in lst),
min(t[1] for t in lst),
max(t[0] for t in lst),
max(t[1] for t in lst))
for lst in a]
| Python: how to get the edge values from this list | I've got a python list like
a = [
[[1,2,(3,4)],[1,2,(5)],[-3,3,(3)],[8,-2,(5)]],
[[1,2,(3,4,5)],[-1,222,(3,4,5)],[99,2,(3)],[8,-2,(4,5)]]
]
The tuple in each list element is total useless, please ignore that but delete them
I want to get the max min value from each list element in each position
The exepected output structure is
li = [[xmin, ymin, xmax, ymax], [xmin, ymin, xmax, ymax] ]
In this case li is [[-3, -2, 8, 3], [-1, -2,99, 222]]
So is there any easy to do ?Thank
| [
"If you have access to numpy, you can use numpy.amax. You can use the axis parameter to get the maximum of a certain column of the array.\n",
"You can use zip:\na = [ [[1,2,(3,4)],[1,2,(5)],[-3,3,(3)],[8,-2,(5)] ],\n[[1,2,(3,4,5)],[-1,222,(3,4,5)],[99,2,(3)],[8,-2,(4,5)] ] ]\n\n>>> i, h = zip(*a[0]), zip(*a[1])\n... | [
1,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004007880_list_python.txt |
Q:
Python C extension not threadsafe?
I made a c extension out of a python script that was fairly labour intensive. The code itself is well tested and simple. The c extension is called with a few large lists, and it then performs some clever arithmetic and returns a few new lists. The c extension is 100% self sufficient, it doesn't use any other c functions nor does it use any of the python objects' methods (it does use these standard Python methods however: PyFloat_AsDouble, PyList_GetItem, PyList_Size, PyList_New, Py_BuildValue, PyList_Append). Up until now I have only used it in a non-multithreaded environment.
Today I started using it in a multithreaded GUI environment and all hell broke lose. I have a few test cases I use for debugging, and weirdly enough the smaller ones pass through ok while the larger ones cause bus errors and segmentation faults (crashing the GUI completely and bringing up the 'Problem Report For Python' window in OS X). Is the problem that my c extension isn't threadsafe? If so, how can I make it threadsafe? I tried googling the subject, but I haven't really found any good info that I can make sense of. I checked this and this page out, but I don't really understand what they are saying. Which type of code will need the GIL and which won't?
For what it's worth here is the dump:
Date/Time: 2010-10-23 03:48:02.714 +0800
OS Version: Mac OS X 10.6.4 (10F569)
Report Version: 6
Interval Since Last Report: 323080 sec
Crashes Since Last Report: 60
Per-App Interval Since Last Report: 110157 sec
Per-App Crashes Since Last Report: 59
Anonymous UUID: 5BD8D75B-9B21-4267-98A4-BAA31E56CB5C
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x00000000b009286c
Crashed Thread: 2
Thread 0: Dispatch queue: com.apple.main-thread
0 ...ple.CoreServices.CarbonCore 0x90b024c8 ConvertFromUnicodeToTextImplementation + 1976
1 com.apple.HIToolbox 0x951c99e5 CEncodingTranslator::TranslateFromUnicode(char*, unsigned long, unsigned long*, unsigned long*, unsigned long*, unsigned long, short, short) + 549
2 com.apple.HIToolbox 0x951c9d01 CEncodingTranslator::Translate(char*, unsigned long, unsigned long*, unsigned long*, unsigned long*, unsigned long, unsigned long, short, short, short*, unsigned long) + 101
3 com.apple.HIToolbox 0x951a9e51 TXNGetDataEncoded + 278
4 libwx_macd-2.8.0.dylib 0x0188c7ee wxMacMLTEControl::GetLastPosition() const + 52
5 libwx_macd-2.8.0.dylib 0x0188bf73 wxTextCtrl::SetInsertionPointEnd() + 21
6 libwx_macd-2.8.0.dylib 0x0188bfc9 wxTextCtrl::AppendText(wxString const&) + 25
7 _controls_.so 0x1397e357 _wrap_TextCtrl_AppendText + 247 (wxPython.h:48)
8 org.python.python 0x000ca58b PyEval_EvalFrameEx + 21147
9 org.python.python 0x000cc4ba PyEval_EvalCodeEx + 2042
10 org.python.python 0x00041ca2 function_call + 162
11 org.python.python 0x0000f375 PyObject_Call + 85
12 org.python.python 0x000c7d5b PyEval_EvalFrameEx + 10859
13 org.python.python 0x000cc4ba PyEval_EvalCodeEx + 2042
14 org.python.python 0x00041ca2 function_call + 162
15 org.python.python 0x0000f375 PyObject_Call + 85
16 org.python.python 0x000c435e PyEval_CallObjectWithKeywords + 78
17 _core_.so 0x011859f0 wxPyCallback::EventThunker(wxEvent&) + 234 (helpers.cpp:1759)
18 libwx_macd-2.8.0.dylib 0x0180e360 wxEvtHandler::ProcessEventIfMatches(wxEventTableEntryBase const&, wxEvtHandler*, wxEvent&) + 108
19 libwx_macd-2.8.0.dylib 0x0180e406 wxEvtHandler::SearchDynamicEventTable(wxEvent&) + 80
20 libwx_macd-2.8.0.dylib 0x0180f205 wxEvtHandler::ProcessEvent(wxEvent&) + 225
21 libwx_macd-2.8.0.dylib 0x0180ef4a wxEvtHandler::ProcessPendingEvents() + 86
22 libwx_macd-2.8.0.dylib 0x0176cd02 wxAppConsole::ProcessPendingEvents() + 102
23 libwx_macd-2.8.0.dylib 0x01806873 wxMacProcessNotifierAndPendingEvents + 33
24 libwx_macd-2.8.0.dylib 0x0183107e wxApp::MacHandleOneEvent(void*) + 90
25 libwx_macd-2.8.0.dylib 0x0183110e wxApp::MacDoOneEvent() + 120
26 libwx_macd-2.8.0.dylib 0x0184b570 wxEventLoop::Dispatch() + 32
27 libwx_macd-2.8.0.dylib 0x01906e71 wxEventLoopManual::Run() + 97
28 libwx_macd-2.8.0.dylib 0x018dd364 wxAppBase::MainLoop() + 76
29 _core_.so 0x0117c75c wxPyApp::MainLoop() + 52 (helpers.cpp:215)
30 _core_.so 0x011c9e66 _wrap_PyApp_MainLoop + 82 (_core_wrap.cpp:31686)
31 org.python.python 0x000ca58b PyEval_EvalFrameEx + 21147
32 org.python.python 0x000cc4ba PyEval_EvalCodeEx + 2042
33 org.python.python 0x00041ca2 function_call + 162
34 org.python.python 0x0000f375 PyObject_Call + 85
35 org.python.python 0x00021c66 instancemethod_call + 422
36 org.python.python 0x0000f375 PyObject_Call + 85
37 org.python.python 0x000c8ad6 PyEval_EvalFrameEx + 14310
38 org.python.python 0x000cbc88 PyEval_EvalFrameEx + 27032
39 org.python.python 0x000cc4ba PyEval_EvalCodeEx + 2042
40 org.python.python 0x000cc647 PyEval_EvalCode + 87
41 org.python.python 0x000f0ae8 PyRun_FileExFlags + 168
42 org.python.python 0x000f1a23 PyRun_SimpleFileExFlags + 867
43 org.python.python 0x0010a42b Py_Main + 3163
44 org.python.python 0x00001f82 0x1000 + 3970
45 org.python.python 0x00001ea9 0x1000 + 3753
Thread 1: Dispatch queue: com.apple.libdispatch-manager
0 libSystem.B.dylib 0x96068942 kevent + 10
1 libSystem.B.dylib 0x9606905c _dispatch_mgr_invoke + 215
2 libSystem.B.dylib 0x96068519 _dispatch_queue_invoke + 163
3 libSystem.B.dylib 0x960682be _dispatch_worker_thread2 + 240
4 libSystem.B.dylib 0x96067d41 _pthread_wqthread + 390
5 libSystem.B.dylib 0x96067b86 start_wqthread + 30
Thread 2 Crashed:
0 ccookies.so 0x0060a949 my_calc + 249 (ccookies.c:23)
1 org.python.python 0x000ca3e0 PyEval_EvalFrameEx + 20720
2 org.python.python 0x000cbc88 PyEval_EvalFrameEx + 27032
3 org.python.python 0x000cbc88 PyEval_EvalFrameEx + 27032
4 org.python.python 0x000cbc88 PyEval_EvalFrameEx + 27032
5 org.python.python 0x000cc4ba PyEval_EvalCodeEx + 2042
6 org.python.python 0x00041ca2 function_call + 162
7 org.python.python 0x0000f375 PyObject_Call + 85
8 org.python.python 0x00021c66 instancemethod_call + 422
9 org.python.python 0x0000f375 PyObject_Call + 85
10 org.python.python 0x000c435e PyEval_CallObjectWithKeywords + 78
11 org.python.python 0x0010c79c t_bootstrap + 76
12 libSystem.B.dylib 0x9606f81d _pthread_start + 345
13 libSystem.B.dylib 0x9606f6a2 thread_start + 34
Thread 2 crashed with X86 Thread State (32-bit):
eax: 0x0007d090 ebx: 0x0060a85d ecx: 0x000ef236 edx: 0xb010f920
edi: 0x02315180 esi: 0xb0092890 ebp: 0xb018d378 esp: 0xb0092870
ss: 0x0000001f efl: 0x00010282 eip: 0x0060a949 cs: 0x00000017
ds: 0x0000001f es: 0x0000001f fs: 0x0000001f gs: 0x00000037
cr2: 0xb009286c
A:
I finally managed to get rid of the problem, but in a pretty long winded way. Here goes.
I spent a very very long time trying to make sense of the documentation for c extensions and their thread-safeness. On one of the many google trajectories that night I stumbled on this page describing how to use numpy arrays in c extensions. Since my problems seemed to be performance related (the original c extension worked for smaller datasets) I suspected that my implementation of looping through the python lists and using PyList_GetItem to get the data into their c array counterparts was not up to scratch. (I deduced the following actual number crunching in the c extension wasn't the issue since it was very generic c without any special stuff at all.)
Hence I decided to undertake a complete rewrite of the c extension and my calling python script to use numpy arrays instead of lists. It took a good two days including all the debugging. But now it works like a charm. All datasets are processed ok, there are no signs of any bus errors nor segmentation faults.
TLDR: Use numpy arrays instead of python lists when working with large datasets and python c extensions to avoid bus errors and segmentation faults.
A:
cPython is not thread safe. That is the purpose of the GIL, which must be used whenever accessing or modifying the interpreter state.
If you need threading and python, then you will need to use an implementation other than cPython (the standard one), such as IronPython or Jython, both of which are perfectly robust in the case of threading. There are some modified cPython's such as Stackless python that might work better as well.
| Python C extension not threadsafe? | I made a c extension out of a python script that was fairly labour intensive. The code itself is well tested and simple. The c extension is called with a few large lists, and it then performs some clever arithmetic and returns a few new lists. The c extension is 100% self sufficient, it doesn't use any other c functions nor does it use any of the python objects' methods (it does use these standard Python methods however: PyFloat_AsDouble, PyList_GetItem, PyList_Size, PyList_New, Py_BuildValue, PyList_Append). Up until now I have only used it in a non-multithreaded environment.
Today I started using it in a multithreaded GUI environment and all hell broke lose. I have a few test cases I use for debugging, and weirdly enough the smaller ones pass through ok while the larger ones cause bus errors and segmentation faults (crashing the GUI completely and bringing up the 'Problem Report For Python' window in OS X). Is the problem that my c extension isn't threadsafe? If so, how can I make it threadsafe? I tried googling the subject, but I haven't really found any good info that I can make sense of. I checked this and this page out, but I don't really understand what they are saying. Which type of code will need the GIL and which won't?
For what it's worth here is the dump:
Date/Time: 2010-10-23 03:48:02.714 +0800
OS Version: Mac OS X 10.6.4 (10F569)
Report Version: 6
Interval Since Last Report: 323080 sec
Crashes Since Last Report: 60
Per-App Interval Since Last Report: 110157 sec
Per-App Crashes Since Last Report: 59
Anonymous UUID: 5BD8D75B-9B21-4267-98A4-BAA31E56CB5C
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x00000000b009286c
Crashed Thread: 2
Thread 0: Dispatch queue: com.apple.main-thread
0 ...ple.CoreServices.CarbonCore 0x90b024c8 ConvertFromUnicodeToTextImplementation + 1976
1 com.apple.HIToolbox 0x951c99e5 CEncodingTranslator::TranslateFromUnicode(char*, unsigned long, unsigned long*, unsigned long*, unsigned long*, unsigned long, short, short) + 549
2 com.apple.HIToolbox 0x951c9d01 CEncodingTranslator::Translate(char*, unsigned long, unsigned long*, unsigned long*, unsigned long*, unsigned long, unsigned long, short, short, short*, unsigned long) + 101
3 com.apple.HIToolbox 0x951a9e51 TXNGetDataEncoded + 278
4 libwx_macd-2.8.0.dylib 0x0188c7ee wxMacMLTEControl::GetLastPosition() const + 52
5 libwx_macd-2.8.0.dylib 0x0188bf73 wxTextCtrl::SetInsertionPointEnd() + 21
6 libwx_macd-2.8.0.dylib 0x0188bfc9 wxTextCtrl::AppendText(wxString const&) + 25
7 _controls_.so 0x1397e357 _wrap_TextCtrl_AppendText + 247 (wxPython.h:48)
8 org.python.python 0x000ca58b PyEval_EvalFrameEx + 21147
9 org.python.python 0x000cc4ba PyEval_EvalCodeEx + 2042
10 org.python.python 0x00041ca2 function_call + 162
11 org.python.python 0x0000f375 PyObject_Call + 85
12 org.python.python 0x000c7d5b PyEval_EvalFrameEx + 10859
13 org.python.python 0x000cc4ba PyEval_EvalCodeEx + 2042
14 org.python.python 0x00041ca2 function_call + 162
15 org.python.python 0x0000f375 PyObject_Call + 85
16 org.python.python 0x000c435e PyEval_CallObjectWithKeywords + 78
17 _core_.so 0x011859f0 wxPyCallback::EventThunker(wxEvent&) + 234 (helpers.cpp:1759)
18 libwx_macd-2.8.0.dylib 0x0180e360 wxEvtHandler::ProcessEventIfMatches(wxEventTableEntryBase const&, wxEvtHandler*, wxEvent&) + 108
19 libwx_macd-2.8.0.dylib 0x0180e406 wxEvtHandler::SearchDynamicEventTable(wxEvent&) + 80
20 libwx_macd-2.8.0.dylib 0x0180f205 wxEvtHandler::ProcessEvent(wxEvent&) + 225
21 libwx_macd-2.8.0.dylib 0x0180ef4a wxEvtHandler::ProcessPendingEvents() + 86
22 libwx_macd-2.8.0.dylib 0x0176cd02 wxAppConsole::ProcessPendingEvents() + 102
23 libwx_macd-2.8.0.dylib 0x01806873 wxMacProcessNotifierAndPendingEvents + 33
24 libwx_macd-2.8.0.dylib 0x0183107e wxApp::MacHandleOneEvent(void*) + 90
25 libwx_macd-2.8.0.dylib 0x0183110e wxApp::MacDoOneEvent() + 120
26 libwx_macd-2.8.0.dylib 0x0184b570 wxEventLoop::Dispatch() + 32
27 libwx_macd-2.8.0.dylib 0x01906e71 wxEventLoopManual::Run() + 97
28 libwx_macd-2.8.0.dylib 0x018dd364 wxAppBase::MainLoop() + 76
29 _core_.so 0x0117c75c wxPyApp::MainLoop() + 52 (helpers.cpp:215)
30 _core_.so 0x011c9e66 _wrap_PyApp_MainLoop + 82 (_core_wrap.cpp:31686)
31 org.python.python 0x000ca58b PyEval_EvalFrameEx + 21147
32 org.python.python 0x000cc4ba PyEval_EvalCodeEx + 2042
33 org.python.python 0x00041ca2 function_call + 162
34 org.python.python 0x0000f375 PyObject_Call + 85
35 org.python.python 0x00021c66 instancemethod_call + 422
36 org.python.python 0x0000f375 PyObject_Call + 85
37 org.python.python 0x000c8ad6 PyEval_EvalFrameEx + 14310
38 org.python.python 0x000cbc88 PyEval_EvalFrameEx + 27032
39 org.python.python 0x000cc4ba PyEval_EvalCodeEx + 2042
40 org.python.python 0x000cc647 PyEval_EvalCode + 87
41 org.python.python 0x000f0ae8 PyRun_FileExFlags + 168
42 org.python.python 0x000f1a23 PyRun_SimpleFileExFlags + 867
43 org.python.python 0x0010a42b Py_Main + 3163
44 org.python.python 0x00001f82 0x1000 + 3970
45 org.python.python 0x00001ea9 0x1000 + 3753
Thread 1: Dispatch queue: com.apple.libdispatch-manager
0 libSystem.B.dylib 0x96068942 kevent + 10
1 libSystem.B.dylib 0x9606905c _dispatch_mgr_invoke + 215
2 libSystem.B.dylib 0x96068519 _dispatch_queue_invoke + 163
3 libSystem.B.dylib 0x960682be _dispatch_worker_thread2 + 240
4 libSystem.B.dylib 0x96067d41 _pthread_wqthread + 390
5 libSystem.B.dylib 0x96067b86 start_wqthread + 30
Thread 2 Crashed:
0 ccookies.so 0x0060a949 my_calc + 249 (ccookies.c:23)
1 org.python.python 0x000ca3e0 PyEval_EvalFrameEx + 20720
2 org.python.python 0x000cbc88 PyEval_EvalFrameEx + 27032
3 org.python.python 0x000cbc88 PyEval_EvalFrameEx + 27032
4 org.python.python 0x000cbc88 PyEval_EvalFrameEx + 27032
5 org.python.python 0x000cc4ba PyEval_EvalCodeEx + 2042
6 org.python.python 0x00041ca2 function_call + 162
7 org.python.python 0x0000f375 PyObject_Call + 85
8 org.python.python 0x00021c66 instancemethod_call + 422
9 org.python.python 0x0000f375 PyObject_Call + 85
10 org.python.python 0x000c435e PyEval_CallObjectWithKeywords + 78
11 org.python.python 0x0010c79c t_bootstrap + 76
12 libSystem.B.dylib 0x9606f81d _pthread_start + 345
13 libSystem.B.dylib 0x9606f6a2 thread_start + 34
Thread 2 crashed with X86 Thread State (32-bit):
eax: 0x0007d090 ebx: 0x0060a85d ecx: 0x000ef236 edx: 0xb010f920
edi: 0x02315180 esi: 0xb0092890 ebp: 0xb018d378 esp: 0xb0092870
ss: 0x0000001f efl: 0x00010282 eip: 0x0060a949 cs: 0x00000017
ds: 0x0000001f es: 0x0000001f fs: 0x0000001f gs: 0x00000037
cr2: 0xb009286c
| [
"I finally managed to get rid of the problem, but in a pretty long winded way. Here goes.\nI spent a very very long time trying to make sense of the documentation for c extensions and their thread-safeness. On one of the many google trajectories that night I stumbled on this page describing how to use numpy arrays ... | [
4,
1
] | [] | [] | [
"cpython",
"python",
"python_c_extension",
"thread_safety"
] | stackoverflow_0003999900_cpython_python_python_c_extension_thread_safety.txt |
Q:
WMI querying issues in Python
I've recently been working on a Squish test script, and trying to do something like what's described in the solution at:
Total memory used by Python process?
The relevant snippets from my code are as follows:
def measureMemory():
w = wmi.WMI('.')
result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE Name=\"some_program\"")
print result
for WorkingSet in result:
print WorkingSet
subset = result[0]
print subset['WorkingSet']
# return result[0]['WorkingSet']
for i in range(50):
memory = measureMemory()
if memory:
# test.passes("%d memory used during undo." % memory)
print memory
Unfortunately, I've run into an error whenever I actually try to run the thing, as can be seen below.
[<_wmi_object: \\USER-PC\root\cimv2:Win32_PerfRawData_PerfProc_Process.Name="some_program">]
instance of Win32_PerfRawData_PerfProc_Process
{
Name = "some_program";
WorkingSet = "19386368";
};
Traceback (most recent call last):
File "C:\Python26\Test scripts\Testify", line 25, in -toplevel-
memory = measureMemory()
File "C:\Python26\Test scripts\Testify", line 19, in measureMemory
print subset['WorkingSet']
File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 242, in __getitem__
raise TypeError("This object does not support enumeration")
TypeError: This object does not support enumeration
I'm not sure why this should be throwing an error, as I don't think I've changed anything significant from the example I took code from.
I'm using Python 2.4.4, if that's significant, and unfortunately I can't really upgrade, no matter how much it might help.
A:
The WMI syntax seems to have changed from the examples. Try using subset.WorkingSet instead of subset['WorkingSet']
| WMI querying issues in Python | I've recently been working on a Squish test script, and trying to do something like what's described in the solution at:
Total memory used by Python process?
The relevant snippets from my code are as follows:
def measureMemory():
w = wmi.WMI('.')
result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE Name=\"some_program\"")
print result
for WorkingSet in result:
print WorkingSet
subset = result[0]
print subset['WorkingSet']
# return result[0]['WorkingSet']
for i in range(50):
memory = measureMemory()
if memory:
# test.passes("%d memory used during undo." % memory)
print memory
Unfortunately, I've run into an error whenever I actually try to run the thing, as can be seen below.
[<_wmi_object: \\USER-PC\root\cimv2:Win32_PerfRawData_PerfProc_Process.Name="some_program">]
instance of Win32_PerfRawData_PerfProc_Process
{
Name = "some_program";
WorkingSet = "19386368";
};
Traceback (most recent call last):
File "C:\Python26\Test scripts\Testify", line 25, in -toplevel-
memory = measureMemory()
File "C:\Python26\Test scripts\Testify", line 19, in measureMemory
print subset['WorkingSet']
File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 242, in __getitem__
raise TypeError("This object does not support enumeration")
TypeError: This object does not support enumeration
I'm not sure why this should be throwing an error, as I don't think I've changed anything significant from the example I took code from.
I'm using Python 2.4.4, if that's significant, and unfortunately I can't really upgrade, no matter how much it might help.
| [
"The WMI syntax seems to have changed from the examples. Try using subset.WorkingSet instead of subset['WorkingSet']\n"
] | [
2
] | [] | [] | [
"python",
"wmi",
"wmi_query"
] | stackoverflow_0002105668_python_wmi_wmi_query.txt |
Q:
Storing JSON in MySQL?
I have some things that do not need to be indexed or searched (game configurations) so I was thinking of storing JSON on a BLOB. Is this a good idea at all? Or are there alternatives?
A:
If you need to query based on the values within the JSON, it would be better to store the values separately.
If you are just loading a set of configurations like you say you are doing, storing the JSON directly in the database works great and is a very easy solution.
A:
No different than people storing XML snippets in a database (that doesn't have XML support). Don't see any harm in it, if it really doesn't need to be searched at the DB level. And the great thing about JSON is how parseable it is.
A:
I don't see why not. As a related real-world example, WordPress stores serialized PHP arrays as a single value in many instances.
A:
I think,It's beter serialize your XML.If you are using python language ,cPickle is good choice.
| Storing JSON in MySQL? | I have some things that do not need to be indexed or searched (game configurations) so I was thinking of storing JSON on a BLOB. Is this a good idea at all? Or are there alternatives?
| [
"If you need to query based on the values within the JSON, it would be better to store the values separately.\nIf you are just loading a set of configurations like you say you are doing, storing the JSON directly in the database works great and is a very easy solution.\n",
"No different than people storing XML sn... | [
5,
2,
2,
0
] | [] | [] | [
"json",
"mysql",
"python"
] | stackoverflow_0004001314_json_mysql_python.txt |
Q:
How do I programmatically check if a url needs unescaping in python?
Working on a small web spider in python, using the lxml module I have a segment of code which does an xpath query of the document and places all the links from 'a href' tags into a list. what I'd like to do is check each link as it is being added to the list, and if it is needed, unescape it. I understand using the urllib.unquote() function, but the problem I'm experiencing is that the urllib method throws an exception which I believe is due to not every link that is passed to the method needs unescaping. Can anyone point me in the right direction? Here's the code I have so far:
import urllib
import urllib2
from lxml.html import parse, tostring
class Crawler():
def __init__(self, url):
self.url = url
self.links = []
def crawl(self):
doc = parse("http://" + self.url).getroot()
doc.make_links_absolute(self.url, resolve_base_href=True)
for tag in doc.xpath("//a"):
old = tag.get('href')
fixed = urllib.unquote(old)
self.links.append(fixed)
print(self.links)
A:
unquote doesn't throw exceptions because of URLs that don't need escaping. You haven't shown us the exception, but I'll guess that the problem is that old isn't a string, it's probably None, because you have an <a> tag with no href attribute.
Check the value of old before you try to use it.
A:
url.find('%') > -1
or wrap urllib.unquote in a try..except clause.
A:
You could do something like this. Although I don't have a url which causes an exception. So this is just hypothesis at this point. See if this approach works.
from urllib import unquote
#get url from your parse tree.
url_unq = unquote(url or '')
if not url_unq:
url_unq = url
See if this works? It would be great if you could give an actual example of the URL which causes exception. What Exception? Could you post the StackTrace?
Worst-case you could always use a try-except around that block & go about your business.
| How do I programmatically check if a url needs unescaping in python? | Working on a small web spider in python, using the lxml module I have a segment of code which does an xpath query of the document and places all the links from 'a href' tags into a list. what I'd like to do is check each link as it is being added to the list, and if it is needed, unescape it. I understand using the urllib.unquote() function, but the problem I'm experiencing is that the urllib method throws an exception which I believe is due to not every link that is passed to the method needs unescaping. Can anyone point me in the right direction? Here's the code I have so far:
import urllib
import urllib2
from lxml.html import parse, tostring
class Crawler():
def __init__(self, url):
self.url = url
self.links = []
def crawl(self):
doc = parse("http://" + self.url).getroot()
doc.make_links_absolute(self.url, resolve_base_href=True)
for tag in doc.xpath("//a"):
old = tag.get('href')
fixed = urllib.unquote(old)
self.links.append(fixed)
print(self.links)
| [
"unquote doesn't throw exceptions because of URLs that don't need escaping. You haven't shown us the exception, but I'll guess that the problem is that old isn't a string, it's probably None, because you have an <a> tag with no href attribute.\nCheck the value of old before you try to use it.\n",
"url.find('%') ... | [
1,
0,
0
] | [] | [] | [
"escaping",
"python"
] | stackoverflow_0004007141_escaping_python.txt |
Q:
Python: I am unable to comprehend the concept of a For Loop, apparently
I've got a list of 400 numbers, and i want to but them in a 20x20 grid using Python.
I've made a "2d array" (not really because Python doesn't support them, I've had to use a list of lists.)
When i try to loop through and assign each subsequnt item to the next box in the grid, it fails. i end up assinging the last item in the list to every box.
Here's the code:
numbers = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48"
grid = [[0 for col in range(20)] for row in range(20)]
for x in range(0, 1200, 3):
y = x + 2
a = numbers[x:y]
for i in range(20):
for j in range(20):
grid[i][j] = a
print(grid)
I can see why it's going wrong: the two loops that generate the list coordinates are inside the loop that gets each items from the list, so each time they run the value they are assigning doesn't change.
Therefore I guess seeing as they don't work in the loop, they need to be out of it.
The problem is that I can't work out where exactly.
Anyone give me a hand?
A:
This is the sort of thing that list comprehensions are good for.
nums = iter(numbers.split())
grid = [[next(nums) for col in range(20)] for row in range(20)]
Alternatively, as a for loop:
grid = [[0]*20 for row in range(20)]
nums = iter(numbers.split())
for i in xrange(20):
for j in xrange(20):
grid[i][j] = next(nums)
I'm not recommending that you do this, but the way to do it if you don't just want to split the list and then call next on its iterator is to write a generator to parse the list the way that you were and then call next on that. I point this out because there are situations where builtins wont do it for you so you should see the pattern (not Design Pattern, just pattern for the pedantic):
def items(numbers):
for x in range(0, len(numbers), 3):
yield numbers[x:x+2]
nums = items(numbers)
for i in xrange(20):
for j in xrange(20):
grid[i][j] = next(nums)
This lets you step through the two loops in parallel.
A:
Another alternative is to use the grouper idiom:
nums = iter(numbers.split())
grid = zip(*[nums]*20)
Note that this makes a list of tuples, not a list of lists.
If you need a list of lists, then
grid = map(list,zip(*[nums]*20))
A:
Your for loop confusion stems from having more loops than you need.
Instead, one approach is to start by looping over your grid squares and then figuring out the needed offset into your list of numbers:
for i in range(20):
for j in range(20):
offset = i*20*3 + j*3
grid[i][j] = numbers[offset:offset+2]
In this case, the offset has a few constants. i is the row, so for each row you need to skip over a row's worth of characters (60) in your list. j is the column index; each column is 3 characters wide.
You could, of course, do this operation in reverse. In that case, you would loop over your list of numbers and then figure out to which grid square it belongs. It works very similarly, except you'd be using division and modulo arithmetic instead of multiplication in the offset above.
Hopefully this provides some insight into how to use for loops to work with multiple objects and multiple dimensions.
| Python: I am unable to comprehend the concept of a For Loop, apparently | I've got a list of 400 numbers, and i want to but them in a 20x20 grid using Python.
I've made a "2d array" (not really because Python doesn't support them, I've had to use a list of lists.)
When i try to loop through and assign each subsequnt item to the next box in the grid, it fails. i end up assinging the last item in the list to every box.
Here's the code:
numbers = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48"
grid = [[0 for col in range(20)] for row in range(20)]
for x in range(0, 1200, 3):
y = x + 2
a = numbers[x:y]
for i in range(20):
for j in range(20):
grid[i][j] = a
print(grid)
I can see why it's going wrong: the two loops that generate the list coordinates are inside the loop that gets each items from the list, so each time they run the value they are assigning doesn't change.
Therefore I guess seeing as they don't work in the loop, they need to be out of it.
The problem is that I can't work out where exactly.
Anyone give me a hand?
| [
"This is the sort of thing that list comprehensions are good for.\nnums = iter(numbers.split())\ngrid = [[next(nums) for col in range(20)] for row in range(20)]\n\nAlternatively, as a for loop:\ngrid = [[0]*20 for row in range(20)]\nnums = iter(numbers.split())\nfor i in xrange(20):\n for j in xrange(20):\n ... | [
6,
5,
3
] | [] | [] | [
"loops",
"multidimensional_array",
"python"
] | stackoverflow_0004008055_loops_multidimensional_array_python.txt |
Q:
Python: Sorting this list
`li = [(1106257, (255, 255, 255)), (1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (9, (249, 249, 249)), (1, (64, 64, 126)), (406, (247, 247, 251))]`
I want to sort li depending on the first number in each element eg.1106257, 1, 1,1,9,1,406
How to do this fast? Thanks
A:
have you tried li.sort() or sorted(li)?
A:
>>> li = [(1106257, (255, 255, 255)), (1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (9, (249, 249, 249)), (1, (64, 64, 126)), (406, (247, 247, 251))]
>>> li.sort()
>>> li
[(1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (1, (64, 64, 126)), (9, (249, 249, 249)), (406, (247, 247, 251)), (1106257, (255, 255, 255))]
Default behavior when comparing tuples is to compare first the first one, then the second one etc. You can override this by giving a custom compare function as argument to the sort().
A:
What you ask is the default behaviour when comparing tuples. However, the generic answer to your question can be:
>>> import operator
>>> li = [(1106257, (255, 255, 255)), (1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (9, (249, 249, 249)), (1, (64, 64, 126)), (406, (247, 247, 251))]
>>> li.sort(key=operator.itemgetter(0))
>>> li
[(1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (1, (64, 64, 126)),
(9, (249, 249, 249)), (406, (247, 247, 251)), (1106257, (255, 255, 255))]
If you want to sort based on columns other than the first (0), change that number. For example, if you want to sort based on columns 2 then 1, you would provide operator.itemgetter(2, 1) as key.
| Python: Sorting this list | `li = [(1106257, (255, 255, 255)), (1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (9, (249, 249, 249)), (1, (64, 64, 126)), (406, (247, 247, 251))]`
I want to sort li depending on the first number in each element eg.1106257, 1, 1,1,9,1,406
How to do this fast? Thanks
| [
"have you tried li.sort() or sorted(li)?\n",
">>> li = [(1106257, (255, 255, 255)), (1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (9, (249, 249, 249)), (1, (64, 64, 126)), (406, (247, 247, 251))]\n>>> li.sort()\n>>> li\n[(1, (16, 16, 118)), (1, (32, 32, 128)), (1, (48, 48, 122)), (1, (64, 64, 126)),... | [
2,
2,
1
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0004006438_list_python_sorting.txt |
Q:
Modifying *.RC file with python (regexp involved)
What I need is to parce my projects' resource files and change its version number. I have a working JS script but I would like to implement it with python.
So, the problem stands in using re.sub:
version = "2,3,4,5"
modified_str = re.sub(r"(/FILEVERSION )\d+,\d+,\d+,\d+(\s)/g", version, str_text)
I understand that because of using capturing groups my code is incorrect. And I tried to do smth like:
modified_str = re.sub(r"(/FILEVERSION )(\d+,\d+,\d+,\d+)(\s)/g", r"2,3,4,5\2", str_text)
And still no effect. Please help!
A:
That's not the way to make multiline regexes in python. You have to compile the regex with the MULTILINE flag:
regex = re.compile(r"\bFILEVERSION \d+,\d+,\d+,\d+\b", re.MULTILINE)
Also, since you're using re.sub(), the FILEVERSION part of your string will disappear if you don't specify it again in the replacement string:
version = "FILEVERSION 2,3,4,5"
modified_str = re.sub(regex, version, str_text)
To match other things than FILEVERSION, introduce a capture group with an alternation:
regex = re.compile(r"\b(FILEVERSION|FileVersion|PRODUCTVERSION|ProductVersion) \d+,\d+,\d+,\d+\b", re.MULTILINE)
Then you can inject the captured expression into the replacement string using the backreference \1:
version = r"\1 2,3,4,5"
modified_str = re.sub(regex, version, str_text)
A:
Just want to summarize (probably will help someone):
I had to modify 4 lines in *.rc files, e.g.:
FILEVERSION 6,0,20,163
PRODUCTVERSION 6,0,20,163
...
VALUE "FileVersion", "6, 0, 20, 163"
VALUE "ProductVersion", "6, 0, 20, 163"
For the first two lines I used regexp given by Frederic Hamidi (thx a lot). For the last two I wrote another one:
regex_2 = re.compile(r"\b(VALUE\s*\"FileVersion\",\s*\"|VALUE\s*\"ProductVersion\",\s*\").*?(\")", re.MULTILINE)
And:
pass_1 = re.sub(regex_1, r"\1 " + v, source_text)
v = re.sub(",", ", ", v) #replacing "x,y,v,z" with "x, y, v, z"
pass_2 = re.sub(regex_2, r"\g<1>" + v + r"\2", pass_1)
Cheers.
| Modifying *.RC file with python (regexp involved) | What I need is to parce my projects' resource files and change its version number. I have a working JS script but I would like to implement it with python.
So, the problem stands in using re.sub:
version = "2,3,4,5"
modified_str = re.sub(r"(/FILEVERSION )\d+,\d+,\d+,\d+(\s)/g", version, str_text)
I understand that because of using capturing groups my code is incorrect. And I tried to do smth like:
modified_str = re.sub(r"(/FILEVERSION )(\d+,\d+,\d+,\d+)(\s)/g", r"2,3,4,5\2", str_text)
And still no effect. Please help!
| [
"That's not the way to make multiline regexes in python. You have to compile the regex with the MULTILINE flag:\nregex = re.compile(r\"\\bFILEVERSION \\d+,\\d+,\\d+,\\d+\\b\", re.MULTILINE)\n\nAlso, since you're using re.sub(), the FILEVERSION part of your string will disappear if you don't specify it again in the ... | [
4,
4
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004003725_python_regex.txt |
Q:
how to implement the options/arguments for the command line functions in python
my python version is 2.4.3.
Now I am developing a CLI with cmd module from python for a CD player. I have some classes like CDContainer (with method like addCD, removeCD, etc), CD (with method like play, stop, pause). Now, I want to add some options for the commands and also if the options inputs are not correct, the CLI could return proper information about either wrong input type or wrong values. e.g., I want to have "addcd --track 3 --cdname thriller". what I am doing now is to get all the arguments via , split it, and assign it to the relevant variables, as follows.
my question is in python, is there some module that is handy for my case to parse and analyse the options or arguments ?
REVISION: OK, I edit it, thanks to gclj5 comments.
import cmd
class CDContainerCLI(cmd.Cmd):
def do_addcd(self, line):
args=line.split()
parser = OptionParser()
parser.add_option("-t", "--track", dest="track_number", type="int",
help="track number")
parser.add_option("-n", "--cdname", dest="cd_name", type="string",
help="CD name")
(options, positional_args) = parser.parse_args(args)
cd_obj= CD()
cd_obj.addCD(options.track_number, options.cd_name)
If possible, could you write some code samples, just to show how to do it?
Thank you very much!!
A:
my question is in python, is there some module that is handy for my case to parse and analyse the options or arguments ?
Yes, the argparse module.
If you're already familiar with the getopt library from C, that's also available as a python module - though less easy to use, if you're not already used to it.
A:
Depending on your Python version, you should take a look at either optparse (since version 2.3, deprecated since version 2.7) or argparse (since version 2.7).
Some sample code using optparse (line is the string you read from stdin in your CLI):
from optparse import OptionParser
args = line.split()
parser = OptionParser()
parser.add_option("-t", "--track", dest="track_number", type="int",
help="track number")
parser.add_option("-n", "--cdname", dest="cd_name", type="string",
help="CD name")
# args[0] contains the actual command ("addcd" in this example).
(options, positional_args) = add_cd_parser.parse_args(args[1:])
if options.track_number != None and options.cd_name != None:
cd_obj= CD()
cd_obj.addCD(options.track_number, options.cd_name)
print "add CD (track %d, name %s)" % (options.track_number, options.cd_name)
This parser only handles your "addcd" command. For more commands you could use several OptionParser objects in a dictionary with the command name as the key, for instance. You could parse the options like this then:
(options, args) = parsers[args[0]].parse_args(args[1:])
Take a look at the documentation for optparse for more information. It's very easy to output usage information, for instance. There is also a tutorial available.
A:
Here's a demo script I wrote a few months ago when my co-workers and I were learning the argparse module. It illustrates several of the module's behaviors and features:
import sys
import argparse
def parse_command_line():
# Define our argument parser.
ap = argparse.ArgumentParser(
description = 'This is a demo app for the argparse module.',
epilog = 'This text will appear after options.',
usage = '%(prog)s [options]', # Auto-generated by default.
add_help = False, # Default is True.
)
# A grouping of options in the help text.
gr = ap.add_argument_group('Required arguments')
# A positional argument. This is indicated by the absense
# of leading minus signs.
gr.add_argument(
'task',
choices = ['get', 'put'],
help = 'Task to be performed.', # Help text about an option.
metavar = 'TASK', # Placeholder to be used in an option's help text.
# The default in this case would be "{get,put}".
)
# Another group.
gr = ap.add_argument_group('Common options')
# A basic option.
gr.add_argument(
'-s', '--subtask',
action = 'store', # This is the default.
# One value will be stored, as a string,
# in opt.subtask
)
# A required option, with type conversion.
gr.add_argument(
'-u', '--user',
required = True, # Options can be made mandatory.
# However, positional arguments can't be made optional.
type = int, # Convert opt.user to an integer.
# By default, it would be a string.
)
# A flag option.
gr.add_argument(
'--overwrite',
dest = 'clobber', # Store in opt.clobber rather than opt.overwrite.
action = 'store_true', # If option is supplied, opt.clobber == True.
)
# Another group.
gr = ap.add_argument_group('Some other options')
# An option with multiple values.
gr.add_argument(
'--datasets',
metavar = 'DATASET', # Default would be DATASETS.
nargs = '+', # If option is used, it takes 1 or more arguments.
# Will be stored as a list in opt.datasets.
help = "The datasets to use for frobnication.",
)
# An option with a specific N of values.
gr.add_argument(
'--bar',
nargs = 1, # Takes exactly one argument. Differs from a basic
# option because opt.bar will be a list rather
# than a string.
default = [], # Default would be None.
)
# A file option.
gr.add_argument(
'--log',
type = argparse.FileType('w'), # Will open a file for writing.
default = sys.stdout,
help = 'Log file (default: STDOUT)',
)
# Another group.
gr = ap.add_argument_group('Program information')
# A version option.
gr.add_argument(
'-v', '--version',
action = 'version', # Will display version text and exit.
version = 'argparse_demo v1.2.0', # The version text.
)
# A help option.
gr.add_argument(
'-h', '--help',
action = 'help', # Will display help text and exit.
)
# Parse the options.
# If given no arguments, parse_args() works with sys.argv[1:].
# And the object it returns will be of type Namespace.
opt = ap.parse_args()
return opt
command_lines = [
'argparse_demo.py put -u 1',
'argparse_demo.py get -u 234 --over --data a b c --bar XYZ -s munch --log _log.txt',
'argparse_demo.py -h', # Will exit() here.
]
for c in command_lines:
sys.argv = c.split()
opt = parse_command_line()
print opt
| how to implement the options/arguments for the command line functions in python | my python version is 2.4.3.
Now I am developing a CLI with cmd module from python for a CD player. I have some classes like CDContainer (with method like addCD, removeCD, etc), CD (with method like play, stop, pause). Now, I want to add some options for the commands and also if the options inputs are not correct, the CLI could return proper information about either wrong input type or wrong values. e.g., I want to have "addcd --track 3 --cdname thriller". what I am doing now is to get all the arguments via , split it, and assign it to the relevant variables, as follows.
my question is in python, is there some module that is handy for my case to parse and analyse the options or arguments ?
REVISION: OK, I edit it, thanks to gclj5 comments.
import cmd
class CDContainerCLI(cmd.Cmd):
def do_addcd(self, line):
args=line.split()
parser = OptionParser()
parser.add_option("-t", "--track", dest="track_number", type="int",
help="track number")
parser.add_option("-n", "--cdname", dest="cd_name", type="string",
help="CD name")
(options, positional_args) = parser.parse_args(args)
cd_obj= CD()
cd_obj.addCD(options.track_number, options.cd_name)
If possible, could you write some code samples, just to show how to do it?
Thank you very much!!
| [
"\nmy question is in python, is there some module that is handy for my case to parse and analyse the options or arguments ?\n\nYes, the argparse module.\nIf you're already familiar with the getopt library from C, that's also available as a python module - though less easy to use, if you're not already used to it.\n... | [
3,
3,
1
] | [] | [] | [
"command_line",
"command_line_arguments",
"python"
] | stackoverflow_0004008048_command_line_command_line_arguments_python.txt |
Q:
Do all Mac OS X versions (above 10.4) have python preinstalled?
Do all Mac OS X versions (above 10.4) have python preinstalled?
A:
Yes, but the Python version may be different. OS X 10.5 shipped with Python 2.5, OS X 10.6 with Python 2.6.
A:
Yes, they do all have python preinstalled.
| Do all Mac OS X versions (above 10.4) have python preinstalled? | Do all Mac OS X versions (above 10.4) have python preinstalled?
| [
"Yes, but the Python version may be different. OS X 10.5 shipped with Python 2.5, OS X 10.6 with Python 2.6.\n",
"Yes, they do all have python preinstalled.\n"
] | [
5,
4
] | [
"Yes they do. Use it from Terminal.\n"
] | [
-1
] | [
"macos",
"python"
] | stackoverflow_0004007801_macos_python.txt |
Q:
Python Regular Expression Matching: ## ##
I'm searching a file line by line for the occurrence of ##random_string##. It works except for the case of multiple #...
pattern='##(.*?)##'
prog=re.compile(pattern)
string='lala ###hey## there'
result=prog.search(string)
print re.sub(result.group(1), 'FOUND', string)
Desired Output:
"lala #FOUND there"
Instead I get the following because its grabbing the whole ###hey##:
"lala FOUND there"
So how would I ignore any number of # at the beginning or end, and only capture "##string##".
A:
To match at least two hashes at either end:
pattern='##+(.*?)##+'
A:
Your problem is with your inner match. You use ., which matches any character that isn't a line end, and that means it matches # as well. So when it gets ###hey##, it matches (.*?) to #hey.
The easy solution is to exclude the # character from the matchable set:
prog = re.compile(r'##([^#]*)##')
Protip: Use raw strings (e.g. r'') for regular expressions so you don't have to go crazy with backslash escapes.
Trying to allow # inside the hashes will make things much more complicated.
EDIT: If you do not want to allow blank inner text (i.e. "####" shouldn't match with an inner text of ""), then change it to:
prog = re.compile(r'##([^#]+)##')
+ means "one or more."
A:
'^#{2,}([^#]*)#{2,}' -- any number of # >= 2 on either end
be careful with using lazy quantifiers like (.*?) because it'd match '##abc#####' and capture 'abc###'. also lazy quantifiers are very slow
A:
Try the "block comment trick": /##((?:[^#]|#[^#])+?)##/
A:
Adding + to regex, which means to match one or more character.
pattern='#+(.*?)#+'
prog=re.compile(pattern)
string='###HEY##'
result=prog.search(string)
print result.group(1)
Output:
HEY
A:
have you considered doing it non-regex way?
>>> string='lala ####hey## there'
>>> string.split("####")[1].split("#")[0]
'hey'
A:
>>> import re
>>> text= 'lala ###hey## there'
>>> matcher= re.compile(r"##[^#]+##")
>>> print matcher.sub("FOUND", text)
lala #FOUND there
>>>
| Python Regular Expression Matching: ## ## | I'm searching a file line by line for the occurrence of ##random_string##. It works except for the case of multiple #...
pattern='##(.*?)##'
prog=re.compile(pattern)
string='lala ###hey## there'
result=prog.search(string)
print re.sub(result.group(1), 'FOUND', string)
Desired Output:
"lala #FOUND there"
Instead I get the following because its grabbing the whole ###hey##:
"lala FOUND there"
So how would I ignore any number of # at the beginning or end, and only capture "##string##".
| [
"To match at least two hashes at either end:\npattern='##+(.*?)##+'\n\n",
"Your problem is with your inner match. You use ., which matches any character that isn't a line end, and that means it matches # as well. So when it gets ###hey##, it matches (.*?) to #hey.\nThe easy solution is to exclude the # characte... | [
3,
3,
1,
0,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004001980_python_regex.txt |
Q:
Passing user data with glade/gtkbuilder
I am a newbie of glade/pygtk.
I am doing with some radio menu items.
I created a signal handler on the signals tab,
handler: on_group_menu_change
user data: 7
what I expected is pass the int(or str) value 7 as user param to the handler. However, at startup, I found such warning:
Could not lookup object 0 on signal
group_changed of object radiomenuitem1
I know gtkBuilder treat 7 as an object reference.
So how can I just pass an int/str to the handler ?
A:
It seems this is still on the Glade/GtkBuilder todo-list: http://live.gnome.org/Glade/Roadmap/RealUsableSignals
Currently you can only pass references to objects that you define in your xml.
Edit: Since gtk+3, the devs have broken more than just the API... The archived link above is:
https://web.archive.org/web/20100510072526/http://live.gnome.org/Glade/Roadmap/RealUsableSignals
| Passing user data with glade/gtkbuilder | I am a newbie of glade/pygtk.
I am doing with some radio menu items.
I created a signal handler on the signals tab,
handler: on_group_menu_change
user data: 7
what I expected is pass the int(or str) value 7 as user param to the handler. However, at startup, I found such warning:
Could not lookup object 0 on signal
group_changed of object radiomenuitem1
I know gtkBuilder treat 7 as an object reference.
So how can I just pass an int/str to the handler ?
| [
"It seems this is still on the Glade/GtkBuilder todo-list: http://live.gnome.org/Glade/Roadmap/RealUsableSignals\nCurrently you can only pass references to objects that you define in your xml.\nEdit: Since gtk+3, the devs have broken more than just the API... The archived link above is:\nhttps://web.archive.org/web... | [
1
] | [] | [] | [
"glade",
"gtk",
"pygtk",
"python"
] | stackoverflow_0004008309_glade_gtk_pygtk_python.txt |
Q:
Creating views in django (string indentation problems)
I am new to both Python (and django) - but not to programming.
I am having no end of problems with identation in my view. I am trying to generate my html dynamically, so that means a lot of string manipulation. Obviously - I cant have my entire HTML page in one line - so what is required in order to be able to dynamically build an html string, i.e. mixing strings and other variables?
For example, using PHP, the following trivial example demonstrates generating an HTML doc containing a table
<?php
$output = '<html><head><title>Getting worked up over Python indentations</title></head><body>';
output .= '<table><tbody>'
for($i=0; $i< 10; $i++){
output .= '<tr class="'.(($i%2) ? 'even' : 'odd').'"><td>Row: '.$i;
}
$output .= '</tbody></table></body></html>'
echo $output;
I am trying to do something similar in Python (in my views.py), and I get errors like:
EOL while scanning string literal (views.py, line 21)
When I put everything in a single line, it gets rid of the error.
Could someone show how the little php script above will be written in python?, so I can use that as a template to fix my view.
[Edit]
My python code looks something like this:
def just_frigging_doit(request):
html = '<html>
<head><title>What the funk<title></head>
<body>'
# try to start builing dynamic HTML from this point onward...
# but server barfs even further up, on the html var declaration line.
[Edit2]
I have added triple quotes like suggested by Ned and S.Lott, and that works fine if I want to print out static text. If I want to create dynamic html (for example a row number), I get an exception - cannot concatenate 'str' and 'int' objects.
A:
I am trying to generate my html dynamically, so that means a lot of string manipulation.
Don't do this.
Use Django's templates. They work really, really well. If you can't figure out how to apply them, do this. Ask a question showing what you want to do. Don't ask how to make dynamic HTML. Ask about how to create whatever page feature you're trying to create. 80% of the time, a simple {%if%} or {%for%} does everything you need. The rest of the time you need to know how filters and the built-in tags work.
Use string.Template if you must fall back to "dynamic" HTML. http://docs.python.org/library/string.html#template-strings Once you try this, you'll find Django's is better.
Do not do string manipulation to create HTML.
cannot concatenate 'str' and 'int' objects.
Correct. You cannot.
You have three choices.
Convert the int to a string. Use the str() function. This doesn't scale well. You have lots of ad-hoc conversions and stuff. Unpleasant.
Use the format() method of a string to insert values into the string. This is slightly better than complex string manipulation. After doing this for a while, you figure out why templates are a good idea.
Use a template. You can try string.Template. After a while, you figure out why Django's are a good idea.
my_template.html
<html><head><title>Getting worked up over Python indentations</title></head><body>
<table><tbody>
{%for object in objects%}
<tr class="{%cycle 'even' 'odd'%}"><td>Row: {{object}}</td></tr>
{%endfor%}
</tbody></table></body></html>
views.py
def myview( request ):
render_to_response( 'my_template.html',
{ 'objects':range(10) }
)
I think that's all you'd need for a mockup.
A:
In Python, a string can span lines if you use triple-quoting:
"""
This is a
multiline
string
"""
You probably want to use Django templates to create your HTML. Read a Django tutorial to see how it's done.
Python is strongly typed, meaning it won't automatically convert types for you to make your expressions work out, the way PHP will. So you can't concatenate strings and numbers like this: "hello" + num.
| Creating views in django (string indentation problems) | I am new to both Python (and django) - but not to programming.
I am having no end of problems with identation in my view. I am trying to generate my html dynamically, so that means a lot of string manipulation. Obviously - I cant have my entire HTML page in one line - so what is required in order to be able to dynamically build an html string, i.e. mixing strings and other variables?
For example, using PHP, the following trivial example demonstrates generating an HTML doc containing a table
<?php
$output = '<html><head><title>Getting worked up over Python indentations</title></head><body>';
output .= '<table><tbody>'
for($i=0; $i< 10; $i++){
output .= '<tr class="'.(($i%2) ? 'even' : 'odd').'"><td>Row: '.$i;
}
$output .= '</tbody></table></body></html>'
echo $output;
I am trying to do something similar in Python (in my views.py), and I get errors like:
EOL while scanning string literal (views.py, line 21)
When I put everything in a single line, it gets rid of the error.
Could someone show how the little php script above will be written in python?, so I can use that as a template to fix my view.
[Edit]
My python code looks something like this:
def just_frigging_doit(request):
html = '<html>
<head><title>What the funk<title></head>
<body>'
# try to start builing dynamic HTML from this point onward...
# but server barfs even further up, on the html var declaration line.
[Edit2]
I have added triple quotes like suggested by Ned and S.Lott, and that works fine if I want to print out static text. If I want to create dynamic html (for example a row number), I get an exception - cannot concatenate 'str' and 'int' objects.
| [
"\nI am trying to generate my html dynamically, so that means a lot of string manipulation.\n\nDon't do this.\n\nUse Django's templates. They work really, really well. If you can't figure out how to apply them, do this. Ask a question showing what you want to do. Don't ask how to make dynamic HTML. Ask about h... | [
4,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004008748_django_python.txt |
Q:
Merging .xlsx file with Python
Two-headed question here guys,
First, I've been trying to do some searching for a way to read .xlsx files in python. Does xlrd read .xlsx files now? If not, what's the recommended way to read/write to such a file?
Second, I have two files with similar information. One primary field with scoping subfields (like coordinates(the primary field) -> city -> state -> country). In the older file, the information is given an ID number while the newer file (with records deleted/added) does not have these ID's. In python, I'd 1) open the two files 2) check the primary field of the older file against the primary field of the newer file and merge their information to a new file if they match. Given that its not too big of a file, I don't mind the O(n^2) complexity. My question is this: is there a well-defined way to do this in VBA or excel? Everything I think of using excel's library seems too slow and I'm not excellent with VBA.
A:
I frequently access excel files through python and xlrd, python and the Excel COM object. For this job, xlrd won't work because it does not support the xlsx format. But no matter, both approaches are overkill for what you are looking for. Simple Excel formulas will deliver what you want, specifically VLOOKUP.
VLOOKUP "looks for a value in the lefmost column of a table, and then returns a value in the same row from the column you specify".
Some advice on VLOOKUP, First, if you want to match on multiple cells, create a "key" cell which concatenates the cells you are interested in (in both workbooks). Second, make sure to set the last argument to VLOOKUP as FALSE because you will only want exact matches.
Regarding performance, excel formulas are often very fast.
Read the help file on VLOOKUP and ask further questions here.
Late edit (from Mark Baker's answer): There is now a python solution for xlsx. Openpyxl was created this year by Eric Gazoni to read and write Excel's xlsx format.
A:
I only heard about this project this morning, so I've not had an opportunity to look at it, and have no idea what it's like; but take a look at Eric' Gazoni's openpyxl project. The code can be found on bitbucket. The driving force behind this was the ability to read/write xlsx files from Python.
A:
Try http://www.python-excel.org/
My mistake - I missed the .xlsx detail.
I guess it's a question of what's easier: finding or writing a library that handles .xlsx format natively OR save all the Excel spreadsheets as .xls and get on with it with the libraries that merely handle the older format.
A:
Adding on the answer of Steven Rubalski:
You might want to be able to have your lookup value in any other than the leftmost column. In those cases the Index and Match functions come in handy.
See: http://www.mrexcel.com/articles/excel-vlookup-index-match.php
| Merging .xlsx file with Python | Two-headed question here guys,
First, I've been trying to do some searching for a way to read .xlsx files in python. Does xlrd read .xlsx files now? If not, what's the recommended way to read/write to such a file?
Second, I have two files with similar information. One primary field with scoping subfields (like coordinates(the primary field) -> city -> state -> country). In the older file, the information is given an ID number while the newer file (with records deleted/added) does not have these ID's. In python, I'd 1) open the two files 2) check the primary field of the older file against the primary field of the newer file and merge their information to a new file if they match. Given that its not too big of a file, I don't mind the O(n^2) complexity. My question is this: is there a well-defined way to do this in VBA or excel? Everything I think of using excel's library seems too slow and I'm not excellent with VBA.
| [
"I frequently access excel files through python and xlrd, python and the Excel COM object. For this job, xlrd won't work because it does not support the xlsx format. But no matter, both approaches are overkill for what you are looking for. Simple Excel formulas will deliver what you want, specifically VLOOKUP. \... | [
4,
2,
0,
0
] | [] | [] | [
"excel",
"python",
"vba"
] | stackoverflow_0003997745_excel_python_vba.txt |
Q:
extending an irc bot with modules
I've created an IRC bot in Python from scratch just for the fun of it. I've got a way to load modules into it, but you have to manually type out the code to load each module as below:
if data.find('PRIVMSG %s :add_mod foo\r\n' % channel)
enabled_mods.append(foo)
if data.find('PRIVMSG %s :rm_mod foo\r\n' % channel)
enabled_mods.remove(foo)
if data.find('PRIVMSG %s :add_mod bar\r\n' % channel)
enabled_mods.append(bar)
if data.find('PRIVMSG %s :rm_mod bar\r\n' % channel)
enabled_mods.remove(bar)
for mod in enabled_mods:
mod(data,irc,channel,nick)
Is there any way to load each module using a for loop for example? Any other suggestions? Such as:
modules = [foo,bar]
for module in modules:
if data.find('PRIVMSG %s :add_mod %s\r\n' % (channel,module))
enabled_mods.append(module)
if data.find('PRIVMSG %s :rm_mod %s\r\n' % (channel,module))
enabled_mods.remove(module)
SOLVED.
A:
Are you looking for the __import__ function?
| extending an irc bot with modules | I've created an IRC bot in Python from scratch just for the fun of it. I've got a way to load modules into it, but you have to manually type out the code to load each module as below:
if data.find('PRIVMSG %s :add_mod foo\r\n' % channel)
enabled_mods.append(foo)
if data.find('PRIVMSG %s :rm_mod foo\r\n' % channel)
enabled_mods.remove(foo)
if data.find('PRIVMSG %s :add_mod bar\r\n' % channel)
enabled_mods.append(bar)
if data.find('PRIVMSG %s :rm_mod bar\r\n' % channel)
enabled_mods.remove(bar)
for mod in enabled_mods:
mod(data,irc,channel,nick)
Is there any way to load each module using a for loop for example? Any other suggestions? Such as:
modules = [foo,bar]
for module in modules:
if data.find('PRIVMSG %s :add_mod %s\r\n' % (channel,module))
enabled_mods.append(module)
if data.find('PRIVMSG %s :rm_mod %s\r\n' % (channel,module))
enabled_mods.remove(module)
SOLVED.
| [
"Are you looking for the __import__ function?\n"
] | [
0
] | [] | [] | [
"irc",
"module",
"python"
] | stackoverflow_0004008935_irc_module_python.txt |
Q:
How to debug Python inside a WSC
We're programming classic ASP for a big (legacy) web application. This works quite well using WSC (Windows script components) to separate GUI from business logic; the WSCs contain the business logic, classic asp is used for displaying returned information. The WSC's return stringvalues, ADO recordsets and in some cases vbscript-objects.
Currently we're trying to switch from using VBscript inside the WSCs to Python (pyscript), so that at least the language used is modern and has more modern features available (like SOAP, ORM solutions or Memcached).
Using Python code in classic ASP works fine using pywin32 and registering Python as a scripting language, but we're experiencing two fundamental problems:
In a WSC, using the "implements" tag should make all of IIS' standard objects (server, session, request, response, etc.) available to the code inside the WSC. When using Python, It just doesn't seem to work. Maybe I'm using an incorrect syntax, or I need some extra definitions in the Python code, but I can't seem to figure out how to get to these objects.
More info on WSC's: http://aspalliance.com/414
When an error occurs on an ASP page, the traceback is displayed in the browser and all is well. However, if an error occurs inside a WSC, there is little or no feedback to the browser. When using VBscript, Windows allows the developer to choose a debugger, and (in our case) Visual Studio kicks in and shows us the error and the line that contains the error. This works as long as you're developing locally (so the local development machine runs IIS).
When using Python, nothing happens, just a very vague message in the browser, i.e:
error '80020009'
Exception occurred.
I have tried different ways of working around this problem; I've tried importing win32traceutil and opening a trace collector window. The strange thing is that it will capture all of my print() statements, but not the Python error messages. It almost seems as though stdout is captured, but stderr isn't. If there are any other ways in Python to redirect or show error messages I'd like to try those too. I've even considered using a very big try..except, but besides being very bad style, the WSC contains a bunch of separate functions, and it would mean implementing try..except in every function. I really don't want to go there.
If anyone can help me with these two problems (especially nr 2 is a big showstopper for using Python in our company) it would be greatly appreciated. If there is any other way to make the Python traceback visible somehow it would be a big step forward.
By the way, I have posted this question to different mailing lists already, including the pywin32 mailing list, but until now no-one has been able to help us.
So, help me stackoverflow, you're my only hope...
Thanks All,
Erik
I have a very simple example below, consisting of an ASP page and a Python WSC, the ASP page instantiates the WSC and calls some functions from it.
The Response.write will not work, because for some reason the Response object can't be used (problem nr.1), also if there is an error in the Python code, the browser will not show a tracebackor any clear message (problem nr.2).
The code needs to be run under IIS ofcourse, and Python and PyWin32 need to be installed (or the activestate Python distribution, which will already include PyWin32)
python.wsc:
<?xml version="1.0" encoding="Windows-1252" ?>
<component>
<?component error="true" debug="true"?>
<registration
description="python"
progid="python.WSC"
version="1.00"
classid="{F236F59E-3F6F-44EA-A374-DBFA9F90ECB3}"
</registration>
<public>
<method name="testmethod">
</method>
<method name="helloWho">
<PARAMETER name="who"/>
</method>
</public>
<implements type="ASP" id="ASP"/>
<script language="Python">
<![CDATA[
def testmethod():
Response.Write('output of results converted to a string')
def helloWho(who):
return "Hello "+who+"!"
]]>
</script>
</component>
ASP page:
<%@ Language=VBscript %>
<%
set pythonwsc= GetObject("script:"&Server.MapPath("./python.wsc"))
response.write(pythonwsc.helloWho("world")&"<br>")
pythonwsc.testmethod()
%>
A:
as for #2, you need to catch exceptions in the VBScript that calls the component. A WSC is just a com component. Ignore for a moment that there is python running when you invoke your WSC. It's just a COM component.
Errors may occur when invoking that component. It's good practice when invoking a component that may fail, to use error handling. In VBSCript, that means On Error Resume or whatever.
In Javascript, it means a try..catch clause.
Curious: why use python in the WSC? Why not just Jscript - much more mainstream, also quite modern.
| How to debug Python inside a WSC | We're programming classic ASP for a big (legacy) web application. This works quite well using WSC (Windows script components) to separate GUI from business logic; the WSCs contain the business logic, classic asp is used for displaying returned information. The WSC's return stringvalues, ADO recordsets and in some cases vbscript-objects.
Currently we're trying to switch from using VBscript inside the WSCs to Python (pyscript), so that at least the language used is modern and has more modern features available (like SOAP, ORM solutions or Memcached).
Using Python code in classic ASP works fine using pywin32 and registering Python as a scripting language, but we're experiencing two fundamental problems:
In a WSC, using the "implements" tag should make all of IIS' standard objects (server, session, request, response, etc.) available to the code inside the WSC. When using Python, It just doesn't seem to work. Maybe I'm using an incorrect syntax, or I need some extra definitions in the Python code, but I can't seem to figure out how to get to these objects.
More info on WSC's: http://aspalliance.com/414
When an error occurs on an ASP page, the traceback is displayed in the browser and all is well. However, if an error occurs inside a WSC, there is little or no feedback to the browser. When using VBscript, Windows allows the developer to choose a debugger, and (in our case) Visual Studio kicks in and shows us the error and the line that contains the error. This works as long as you're developing locally (so the local development machine runs IIS).
When using Python, nothing happens, just a very vague message in the browser, i.e:
error '80020009'
Exception occurred.
I have tried different ways of working around this problem; I've tried importing win32traceutil and opening a trace collector window. The strange thing is that it will capture all of my print() statements, but not the Python error messages. It almost seems as though stdout is captured, but stderr isn't. If there are any other ways in Python to redirect or show error messages I'd like to try those too. I've even considered using a very big try..except, but besides being very bad style, the WSC contains a bunch of separate functions, and it would mean implementing try..except in every function. I really don't want to go there.
If anyone can help me with these two problems (especially nr 2 is a big showstopper for using Python in our company) it would be greatly appreciated. If there is any other way to make the Python traceback visible somehow it would be a big step forward.
By the way, I have posted this question to different mailing lists already, including the pywin32 mailing list, but until now no-one has been able to help us.
So, help me stackoverflow, you're my only hope...
Thanks All,
Erik
I have a very simple example below, consisting of an ASP page and a Python WSC, the ASP page instantiates the WSC and calls some functions from it.
The Response.write will not work, because for some reason the Response object can't be used (problem nr.1), also if there is an error in the Python code, the browser will not show a tracebackor any clear message (problem nr.2).
The code needs to be run under IIS ofcourse, and Python and PyWin32 need to be installed (or the activestate Python distribution, which will already include PyWin32)
python.wsc:
<?xml version="1.0" encoding="Windows-1252" ?>
<component>
<?component error="true" debug="true"?>
<registration
description="python"
progid="python.WSC"
version="1.00"
classid="{F236F59E-3F6F-44EA-A374-DBFA9F90ECB3}"
</registration>
<public>
<method name="testmethod">
</method>
<method name="helloWho">
<PARAMETER name="who"/>
</method>
</public>
<implements type="ASP" id="ASP"/>
<script language="Python">
<![CDATA[
def testmethod():
Response.Write('output of results converted to a string')
def helloWho(who):
return "Hello "+who+"!"
]]>
</script>
</component>
ASP page:
<%@ Language=VBscript %>
<%
set pythonwsc= GetObject("script:"&Server.MapPath("./python.wsc"))
response.write(pythonwsc.helloWho("world")&"<br>")
pythonwsc.testmethod()
%>
| [
"as for #2, you need to catch exceptions in the VBScript that calls the component. A WSC is just a com component. Ignore for a moment that there is python running when you invoke your WSC. It's just a COM component. \nErrors may occur when invoking that component. It's good practice when invoking a component tha... | [
0
] | [] | [] | [
"asp_classic",
"python",
"vbscript"
] | stackoverflow_0003879788_asp_classic_python_vbscript.txt |
Q:
pytz and Etc/GMT-5
I'm having trouble understanding the conversion between the "Etc/GMT-5" timezone and UTC in pytz.
>>> dt = datetime(2009, 9, 9, 10, 0) # September 9 2009, 10:00
>>> gmt_5 = pytz.timezone("Etc/GMT-5")
>>> gmt_5.localize(dt)
datetime.datetime(2009, 9, 9, 10, 0, tzinfo=<StaticTzInfo 'Etc/GMT-5'>)
Everything is fine so far, but then I try to convert that to UTC:
>>> gmt_5.localize(dt).astimezone(pytz.utc)
datetime.datetime(2009, 9, 9, 5, 0, tzinfo=<UTC>)
So to me it seems that when converting from 10:00 in GMT-5 to UTC I get 05:00? I would expect pytz to give me 15:00 instead.
What am I missing?
EDIT: I have confirmed that timezone conversion for the US/Eastern timezone works just as I'd expect:
>>> eastern = pytz.timezone("US/Eastern")
>>> eastern.localize(dt)
datetime.datetime(2009, 9, 9, 10, 0, tzinfo=...) # Too long
>>> pytz.utc.normalize(eastern.localize(dt).astimezone(pytz.utc))
datetime.datetime(2009, 9, 9, 14, 0, tzinfo=<UTC>)
EDIT 2: I have confirmed that when I use Etc/GMT+5 I get 15:00, which is what I'd expect to get from Etc/GMT-5. Is this a pytz bug?
A:
This is apparently a POSIX thing. From Wikipedia:
In order to conform with the POSIX style, those zones beginning with "Etc/GMT" have their sign reversed from what most people expect. In this style, zones west of GMT have a positive sign and those east have a negative sign.
A:
This bug report explains this behavior. Apparently they know that it is all inverted, but that's because anything else would break compatibility.
| pytz and Etc/GMT-5 | I'm having trouble understanding the conversion between the "Etc/GMT-5" timezone and UTC in pytz.
>>> dt = datetime(2009, 9, 9, 10, 0) # September 9 2009, 10:00
>>> gmt_5 = pytz.timezone("Etc/GMT-5")
>>> gmt_5.localize(dt)
datetime.datetime(2009, 9, 9, 10, 0, tzinfo=<StaticTzInfo 'Etc/GMT-5'>)
Everything is fine so far, but then I try to convert that to UTC:
>>> gmt_5.localize(dt).astimezone(pytz.utc)
datetime.datetime(2009, 9, 9, 5, 0, tzinfo=<UTC>)
So to me it seems that when converting from 10:00 in GMT-5 to UTC I get 05:00? I would expect pytz to give me 15:00 instead.
What am I missing?
EDIT: I have confirmed that timezone conversion for the US/Eastern timezone works just as I'd expect:
>>> eastern = pytz.timezone("US/Eastern")
>>> eastern.localize(dt)
datetime.datetime(2009, 9, 9, 10, 0, tzinfo=...) # Too long
>>> pytz.utc.normalize(eastern.localize(dt).astimezone(pytz.utc))
datetime.datetime(2009, 9, 9, 14, 0, tzinfo=<UTC>)
EDIT 2: I have confirmed that when I use Etc/GMT+5 I get 15:00, which is what I'd expect to get from Etc/GMT-5. Is this a pytz bug?
| [
"This is apparently a POSIX thing. From Wikipedia:\n\nIn order to conform with the POSIX style, those zones beginning with \"Etc/GMT\" have their sign reversed from what most people expect. In this style, zones west of GMT have a positive sign and those east have a negative sign.\n\n",
"This bug report explains t... | [
18,
1
] | [] | [] | [
"python",
"pytz",
"timezone",
"utc"
] | stackoverflow_0004008960_python_pytz_timezone_utc.txt |
Q:
Removing duplicates members from a list of tuples
this question might have similars in SO but my case is a bit different. and I tried to adapt those answers to my problem but couldn't.
so here is the thing:
I have this list :
[(['c', 'a', 'b'], 10), (['c', 'a', 'b'], 9),(['h','b'],2)] for example.
I want to remove the duplicates in this list by keeping tuple that has the larger number associated with it. so the list should look like this:
[(['c', 'a', 'b'], 10),(['h','b'],2)]
can anyone help me? the order of the items inside the inner lists is very important.
thanks
A:
>>> lst = [(['c', 'a', 'b'], 10), (['c', 'a', 'b'], 9),(['h','b'],2)]
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i, j in lst:
d[tuple(i)] = max(d[tuple(i)], j) # assuming positive numbers
>>> d
defaultdict(<class 'int'>, {('h', 'b'): 2, ('c', 'a', 'b'): 10})
A:
If, as your example suggests, the items are already sorted by the numbers (in your case reverse), you can do:
d = dict(reversed(lst))
list(d.iteritems())
The default behavior of the dict() function is that the last seen value for the key is stored. So if they are sorted in reverse order, the last seen value when iterating in reverse order will be the largest. Otherwise, use @SilentGhost`s answer.
| Removing duplicates members from a list of tuples | this question might have similars in SO but my case is a bit different. and I tried to adapt those answers to my problem but couldn't.
so here is the thing:
I have this list :
[(['c', 'a', 'b'], 10), (['c', 'a', 'b'], 9),(['h','b'],2)] for example.
I want to remove the duplicates in this list by keeping tuple that has the larger number associated with it. so the list should look like this:
[(['c', 'a', 'b'], 10),(['h','b'],2)]
can anyone help me? the order of the items inside the inner lists is very important.
thanks
| [
">>> lst = [(['c', 'a', 'b'], 10), (['c', 'a', 'b'], 9),(['h','b'],2)]\n>>> from collections import defaultdict\n>>> d = defaultdict(int)\n>>> for i, j in lst:\n d[tuple(i)] = max(d[tuple(i)], j) # assuming positive numbers\n\n\n>>> d\ndefaultdict(<class 'int'>, {('h', 'b'): 2, ('c', 'a', 'b'): 10})\n\n... | [
3,
2
] | [] | [] | [
"duplicates",
"list",
"python",
"tuples"
] | stackoverflow_0004009304_duplicates_list_python_tuples.txt |
Q:
Use URLLIB without system default proxy Python
I have a small script that needs to communicate with me, it is part of my proxy. The script needs to run before the proxy starts, but the system is set to use the proxy, so it does not go through. How would I use urllib, but not the default proxy?
A:
urllib docs:
urllib.urlopen(url[, data[, proxies]])
[...]
Alternatively, the optional proxies argument may be used to explicitly specify proxies. It must be a dictionary mapping scheme names to proxy URLs, where an empty dictionary causes no proxies to be used, and None (the default value) causes environmental proxy settings to be used as discussed above. [...]
So just use proxies={}.
| Use URLLIB without system default proxy Python | I have a small script that needs to communicate with me, it is part of my proxy. The script needs to run before the proxy starts, but the system is set to use the proxy, so it does not go through. How would I use urllib, but not the default proxy?
| [
"urllib docs:\n\nurllib.urlopen(url[, data[, proxies]])\n\n[...]\n Alternatively, the optional proxies argument may be used to explicitly specify proxies. It must be a dictionary mapping scheme names to proxy URLs, where an empty dictionary causes no proxies to be used, and None (the default value) causes environm... | [
2
] | [] | [] | [
"overriding",
"proxy",
"python",
"urllib"
] | stackoverflow_0004009305_overriding_proxy_python_urllib.txt |
Q:
An algorithm to create HTML table from this row data?
I have come unstuck on a relatively (almost) trivial problem. I have a row of data that I want to display in tabular form (HTML). For some reason (possibly long day [again] behind the computer), I am not coming up with any elegant solutions (algorithms) to do this.
I have presented some sample data, and how such data would be displayed in the table. I would be grateful for some ideas on algos to implement this.
The output table has rows labelled with the various scores and the indices are displayed at the bottom.
I would like to be able to have a variable determine the number of columns to print, before a new table is printed underneath - to prevent ridiculously long tables.
so I want to write a function with the following signature (ignoring data types):
function create_table_html_from_rows(datarows, max_cols_per_table)
Here is the sample data and mock output table presentation
Row data:
index, Score, amount
1, level 1, 12.24
3, level 4, 14.61
9, level 10, 42.35
15, level 2, -8.12
Scores
======
Level 1 12.24
Level 2 -8.12
Level 3
Level 4 14.61
.....
Level 10 42.35
----------------------------------------
| 1 | 3 | 9 | 15 <- Index
Pseudocode should be sufficient, however, if you snippet is in a programming language, it is perharps worth pointing out that I will be implementing my algorithm in Python, however any snippets in any of the following languages would be fine:
Python, C, C++, PHP, C#
A:
I assumed you have Raw data stored similar to what I have below.
Also, the level is non-unique.
<?
$rowData = array(
0=> array('index'=>1, 'Score'=>"level 1", 'amount'=>12.24),
1=> array('index'=>3, 'Score'=>"level 4", 'amount'=>14.61),
2=> array('index'=>9, 'Score'=>"level 10", 'amount'=>42.35),
3=> array('index'=>15, 'Score'=>"level 2", 'amount'=>-8.12),
4=> array('index'=>12, 'Score'=>"level 10", 'amount'=>16.5)
// example Raw Data with non-unique levels
);
$numOfScores = 15; // Predefined Score Level Max
foreach($rowData as $c){
$cols[] = $c['index']; //Create index row
$score = str_replace("level ","",$c['Score']); // split the score so it is only numeric
$levels[$score][] = $c; //create a 2-D array based on the level
}
echo "<table><tr><th colspan=".(sizeof($cols)+1).">Scores:</th></tr>";
for($ii = 1; $ii < $numOfScores; $ii++){ // Go through the levels
echo "<tr><td>Level ".$ii."</td>";
for($i = 0; $i < sizeof($cols); $i++){
echo "<td>";
if(isset($levels[$ii])){ // If I have a level, let's print it in the right column
foreach($levels[$ii] as $lvl)
if($cols[$i] == $lvl['index']) echo $lvl['amount'];
}
echo "</td>";
}
echo "<tr>";
}
echo "<td>Index:</td>";
foreach($cols as $c){
echo "<td>$c</td>";
}
echo "</table>";
?>
I get the following output:
Scores:
Level 1 12.24
Level 2 -8.12
Level 3
Level 4 14.61
Level 5
Level 6
Level 7
Level 8
Level 9
Level 10 42.35 16.5
Level 11
Level 12
Level 13
Level 14
Index: 1 3 9 15 12
It is tabbed correctly on my screen, probably won't appear to be.
As you can see, I added an extra row in your data to simulate a non-unique row. Should work!
A:
Tomorrow is a new day. The problem is really trivial. Also there can not be elegant solution, just long one.
Also you can write even solution (with no respect to its elegancy or other), just to get your work done. And after that you will get ideas of where your thinking was stuck and how to code better solution.
A:
I'd do it in the following way (Note: the code is not tested / debugged at all!):
<?php
$lines = file ("data.txt");
foreach ($lines as $line) {
$array = explode(",", $line);
$level = $array[1];
$index = $array[0];
$amount = $array[2];
$result[level][index] = $amount;
$indeces[] = $index;
}
echo "Scores<br>\n======<br>\n"
echo "<table>";
foreach ($result as $level => $row) {
echo "<tr>\n<td>$level\n";
foreach ($indeces as $index) {
echo "<td>";
if (!isset($row[$index])) {
echo " ";
} else {
echo $row[$index];
}
echo "\n";
}
}
echo "<tr>\n<td>\n";
foreach ($indeces as $index) {
echo "<td>$index\n";
?>
| An algorithm to create HTML table from this row data? | I have come unstuck on a relatively (almost) trivial problem. I have a row of data that I want to display in tabular form (HTML). For some reason (possibly long day [again] behind the computer), I am not coming up with any elegant solutions (algorithms) to do this.
I have presented some sample data, and how such data would be displayed in the table. I would be grateful for some ideas on algos to implement this.
The output table has rows labelled with the various scores and the indices are displayed at the bottom.
I would like to be able to have a variable determine the number of columns to print, before a new table is printed underneath - to prevent ridiculously long tables.
so I want to write a function with the following signature (ignoring data types):
function create_table_html_from_rows(datarows, max_cols_per_table)
Here is the sample data and mock output table presentation
Row data:
index, Score, amount
1, level 1, 12.24
3, level 4, 14.61
9, level 10, 42.35
15, level 2, -8.12
Scores
======
Level 1 12.24
Level 2 -8.12
Level 3
Level 4 14.61
.....
Level 10 42.35
----------------------------------------
| 1 | 3 | 9 | 15 <- Index
Pseudocode should be sufficient, however, if you snippet is in a programming language, it is perharps worth pointing out that I will be implementing my algorithm in Python, however any snippets in any of the following languages would be fine:
Python, C, C++, PHP, C#
| [
"I assumed you have Raw data stored similar to what I have below.\nAlso, the level is non-unique. \n<?\n $rowData = array( \n 0=> array('index'=>1, 'Score'=>\"level 1\", 'amount'=>12.24), \n 1=> array('index'=>3, 'Score'=>\"level 4\", 'amount'=>14.61),\n 2=> array('index'=>9, 'Score'=>\"leve... | [
1,
0,
0
] | [] | [] | [
"c#",
"c++",
"html",
"php",
"python"
] | stackoverflow_0004009250_c#_c++_html_php_python.txt |
Q:
Read dynamic xml using element tree
Environment: Windows,Python,wxpython and Element tree as xml parser.
I am developing a stand alone where it reads the xml and creates a tree.
My application reads the xml and creates tree but when xml changes next time(when DEPTH of xml increases- i mean when two child elements are added).Application fails to read(Logic fails :( )
For e.g.
I have written a logic which can read any xml which has a depth of 5.But when it reads an xml with a depth more than 5 , it fails.
Please let me know how to read xml whose depth is dynamic.
A:
You should use recursive calls, something more like:
def recurse_tree(node):
tree = {}
for element in node:
name = element.get('name')
tree[name] = recurse_tree(element)
if tree:
return tree
else:
return 'No children.'
Not all of your elements had 'name' attributes. So you will need to adjust this to match your exact data structure.
| Read dynamic xml using element tree | Environment: Windows,Python,wxpython and Element tree as xml parser.
I am developing a stand alone where it reads the xml and creates a tree.
My application reads the xml and creates tree but when xml changes next time(when DEPTH of xml increases- i mean when two child elements are added).Application fails to read(Logic fails :( )
For e.g.
I have written a logic which can read any xml which has a depth of 5.But when it reads an xml with a depth more than 5 , it fails.
Please let me know how to read xml whose depth is dynamic.
| [
"You should use recursive calls, something more like:\ndef recurse_tree(node):\n tree = {}\n for element in node:\n name = element.get('name')\n tree[name] = recurse_tree(element)\n if tree:\n return tree\n else:\n return 'No children.'\n\nNot all of your elements had 'name' ... | [
2
] | [] | [] | [
"elementtree",
"python",
"xml"
] | stackoverflow_0004009268_elementtree_python_xml.txt |
Q:
Appengine: How can I set another cookie when use google OAuth login logout
I want set another cookie when user login, I use google.appenine.api.users.create_loginurl() to create the login url, it's /_ah/login, how can I extend this handler and add another cookie. The same as logout.
A:
One option: You could create landing pages to set or unset your app cookies. create_login_url takes a destination url as an argument, redirect to your page that sets up your cookie. To logout, forward users to a page that unsets the cookie then redirects them on to the log out page.
Another choice would be to check the user is logged in, if they are make sure the right cookie is set. If they are not logged in make sure the cookie is not set. The specifics of setting this up will depend on how which framework you are using.
A common approach is to create a BaseRequestHandler class as a subclass of webapp.Requesthandler. BaseRequestHandler can then ensure users have the correct permissions to view a particular page, handle errors, setup up template rendering paths, and setup user sessions in a standard way for your app.
| Appengine: How can I set another cookie when use google OAuth login logout | I want set another cookie when user login, I use google.appenine.api.users.create_loginurl() to create the login url, it's /_ah/login, how can I extend this handler and add another cookie. The same as logout.
| [
"One option: You could create landing pages to set or unset your app cookies. create_login_url takes a destination url as an argument, redirect to your page that sets up your cookie. To logout, forward users to a page that unsets the cookie then redirects them on to the log out page.\nAnother choice would be to ... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004008466_google_app_engine_python.txt |
Q:
Data persistence for python when a lot of lookups but few writes?
I am working on a project that basically monitors a set remote directories (FTP, networked paths, and another), if the file is considered new and meets criteria we download it and process it. However i am stuck on what the best way is to keep track of the files we already downloaded. I don't want to download any duplicate files, so i need to keep track of what is already downloaded.
Orignally i was storing it as a tree:
server->directory->file_name
When the service shuts down it writes it to a file, and rereads it back when it starts up. However given that when there is around 20,000 or so files in the tree stuff starts to slow down alot.
Is there a better way to do this?
EDIT
The lookup times start to slowdown alot, my basic implementation is a dict of a dict. The storing stuff on the disk is fine, its more or less just the lookup time. I know i can optimize the tree and partition it. However that seems excessive for such a small project i was hoping python would have something like that.
A:
I would create a set of tuples, then pickle it to a file. The tuples would be (server, directory, file_name), or even just (server, full_file_name_including_directory). There's no need for a multiple-level data structure. The tuples will hash into the set, and give you a O(1) lookup.
You mention "stuff starts to slow down alot," but you don't say if it's reading and writing time, or lookup times that are slowing down. If your lookup times are slowing down, you may be paging. Is your data structure approaching a significant fraction of your physical memory?
One way to get back some memory is to intern() the server names. This way, each server name will be stored only once in memory.
An interesting alternative is to use a Bloom filter. This will let you use far less memory, but will occasionally download a file that you didn't have to. This might be a reasonable trade-off, depending on why you didn't want to download the file twice.
| Data persistence for python when a lot of lookups but few writes? | I am working on a project that basically monitors a set remote directories (FTP, networked paths, and another), if the file is considered new and meets criteria we download it and process it. However i am stuck on what the best way is to keep track of the files we already downloaded. I don't want to download any duplicate files, so i need to keep track of what is already downloaded.
Orignally i was storing it as a tree:
server->directory->file_name
When the service shuts down it writes it to a file, and rereads it back when it starts up. However given that when there is around 20,000 or so files in the tree stuff starts to slow down alot.
Is there a better way to do this?
EDIT
The lookup times start to slowdown alot, my basic implementation is a dict of a dict. The storing stuff on the disk is fine, its more or less just the lookup time. I know i can optimize the tree and partition it. However that seems excessive for such a small project i was hoping python would have something like that.
| [
"I would create a set of tuples, then pickle it to a file. The tuples would be (server, directory, file_name), or even just (server, full_file_name_including_directory). There's no need for a multiple-level data structure. The tuples will hash into the set, and give you a O(1) lookup.\nYou mention \"stuff starts... | [
1
] | [] | [] | [
"persistence",
"python"
] | stackoverflow_0004009696_persistence_python.txt |
Q:
process closing while saving a file - Python - Windows XP
I'm working on a project for school where e-mails will be pulled from an inbox and downloaded to different locations depending on how things are parsed. The language I'm writing in is Python, and the environment it will be run on is Windows XP. The idea is that the program will run in the background with no interaction from the user until they basically shutdown their computer. A concern I had is what this will mean if they shut it down while a file is in the process of being saved, and what I can do to handle it.
Will it just be a file.part thing? Will the shutdown throw the "Waiting to close X application" message and finish saving before terminating on its own?
A:
You should really check this out: Link (How Windows Shuts Down)
A:
use atexit module
A:
easy crossplatform/crosslanguage way of handling partial file saving:
save to a temporary filename like "file.ext.part"
after you're done saving, rename to "file.ext"
| process closing while saving a file - Python - Windows XP | I'm working on a project for school where e-mails will be pulled from an inbox and downloaded to different locations depending on how things are parsed. The language I'm writing in is Python, and the environment it will be run on is Windows XP. The idea is that the program will run in the background with no interaction from the user until they basically shutdown their computer. A concern I had is what this will mean if they shut it down while a file is in the process of being saved, and what I can do to handle it.
Will it just be a file.part thing? Will the shutdown throw the "Waiting to close X application" message and finish saving before terminating on its own?
| [
"You should really check this out: Link (How Windows Shuts Down)\n",
"use atexit module\n",
"easy crossplatform/crosslanguage way of handling partial file saving:\n\nsave to a temporary filename like \"file.ext.part\"\nafter you're done saving, rename to \"file.ext\"\n\n"
] | [
1,
1,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0004009130_python_windows.txt |
Q:
Python - default arguments in function
Looking at the python doc http://docs.python.org/library/urllib2.html
urllib2.urlopen(url[, data][, timeout])
So, I pass in a url, then optional data and timeout variables (from how I read it).
So if I want to pass a timeout, but not the data... whats the default variable for data? Do you just do,
urlopen('http://www.example.com/', , 5)
Thanks :)
A:
You use the parameter names:
urlopen('http://www.exmaple.com/', timeout=5)
A:
urlopen('http://www.example.com/',timeout=5)
| Python - default arguments in function | Looking at the python doc http://docs.python.org/library/urllib2.html
urllib2.urlopen(url[, data][, timeout])
So, I pass in a url, then optional data and timeout variables (from how I read it).
So if I want to pass a timeout, but not the data... whats the default variable for data? Do you just do,
urlopen('http://www.example.com/', , 5)
Thanks :)
| [
"You use the parameter names:\nurlopen('http://www.exmaple.com/', timeout=5)\n\n",
"urlopen('http://www.example.com/',timeout=5)\n\n"
] | [
8,
1
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0004009863_python_urllib2.txt |
Q:
python - undefined variable?
Does python have some undefined variable / debug mode which will output a notice/warning?
PHP allows you to modify the error_reporting to turn on notice warnings which mean doing
<?php
echo $foo;
will throw an "Undefined variable foo on line 2.......
does python have something similar?
I had a bug where I was doing
db.connect
instead of
db.connect()
and I was hoping python would throw a
undefined variable connect...
can you bump up the error reporting level or similar in python?
A:
Python complains about undefined variables, without any adjustments to its warning system:
h[1] >>> print x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
In your case db.connect actually has a value, namely a function object. So your connection isn't undefined.
h[1] >>> def hello(): pass
...
h[1] >>> x = hello
h[1] >>> print x
<function hello at 0x100461c80>
A:
This is not an undefined variable. You refer to the existing method connect - if there wasn't one, you'd get a NameError as The MYYN shows - but you don't call it. That's perfectly valid as far as the language is concerned - in fact, this behaviour (when part of a bigger expression) is sometimes extremely useful. But let alone, it's pointless of course. I suppose static analysis tools such as pylint or PyChecker might complain about this (I'm not sure though, I rarely make this kind of mistake) and using them won't hurt anyway.
A:
As far as I know, there is no such option in Python. However, there are tools like PyChecker, which will help you finds bugs which in other languages are caught by a compiler.
A:
You can use a tool like pylint http://www.logilab.org/project/pylint
Example
class A(object):
def fun():
return None
a = A()
a.fun
Pylint snippet warning:
R: 2:A.fun: Method could be a function
| python - undefined variable? | Does python have some undefined variable / debug mode which will output a notice/warning?
PHP allows you to modify the error_reporting to turn on notice warnings which mean doing
<?php
echo $foo;
will throw an "Undefined variable foo on line 2.......
does python have something similar?
I had a bug where I was doing
db.connect
instead of
db.connect()
and I was hoping python would throw a
undefined variable connect...
can you bump up the error reporting level or similar in python?
| [
"Python complains about undefined variables, without any adjustments to its warning system:\nh[1] >>> print x\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'x' is not defined\n\nIn your case db.connect actually has a value, namely a function object. So your connection... | [
9,
3,
0,
0
] | [] | [] | [
"debugging",
"error_reporting",
"python",
"variables"
] | stackoverflow_0004009795_debugging_error_reporting_python_variables.txt |
Q:
Python Twitter library: which one?
I realize this is a bit of a lazyweb question, but I wanted to see which python library for Twitter people have had good experiences with.
I've used Python Twitter Tools and like its brevity and beauty of interface, but it doesn't seem to be one of the popular ones - it's not even listed on the Twitter Libraries page.
There are, however, plenty of others listed:
oauth-python-twitter2 by Konpaku Kogasa. Combines python-twitter and oauth-python-twitter to create an evolved OAuth Pokemon.
python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API.
python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client.
twitty-twister by Dustin Sallings. A Twisted interface to Twitter.
twython by Ryan McGrath. REST and Search library inspired by python-twitter.
Tweepy by Josh Roesslein. Supports OAuth, Search API, Streaming API.
My requirements are fairly simple:
Be able to use OAuth
Be able to follow a user
Be able to send a direct message
Be able to post
Streaming API would be nice
Twisted one aside (I'm not using twisted in this case), have you used any of the others, and if so, do you recommend them?
[Update] FWIW, I ended up going with Python Twitter Tools again. The new version supported OAuth nicely, and it's a very clever API, so I stuck to it.
A:
python-twitter should cover the first four requirements. I've used it before, and it's fairly easy to start developing with it. For leveraging Twitter's streaming API, I would recommend tweetstream. It's a fantastic Python module that grabs tweets in real-time as they are posted. Based on whether you have gardenhose/firehose access to the twitter stream, you'll only get a small fraction of tweets posted. With tweetstream, you can also provide a list of search predicates to filter specific tweets that you are looking for. I used it for a project that involved mining tweets over an 8 hour period and it worked flawlessly. Both of these modules should be available through Python's easy-install.
EDIT: I don't know what you intend on doing with Python/Twitter but if you do plan on capturing a lot of tweets, keep in mind that Twitter receives myriad tweets in languages besides English. Remember to encode everything properly.
A:
Full disclosure: I'm the author of Twython.
As such, I'd recommend using mine. It supports OAuth now, and ships with a skeleton Django application to get you up and running in ~5 minutes.
It can handle everything you're looking for, sans the Streaming API - I'm of the opinion that something like that should be implemented on a case-by-case basis, as it's generally a fairly custom setup. There's been very little demand for library support for it, either, so I've a hard time dedicating cycles to supporting it.
pip install twython
http://github.com/ryanmcgrath/twython
A:
I've used tweepy for playing around and thought it was pretty easy and fun to use. Didn't really look that much into the alternatives however so take my opinion with suitable amount of salt :).
| Python Twitter library: which one? | I realize this is a bit of a lazyweb question, but I wanted to see which python library for Twitter people have had good experiences with.
I've used Python Twitter Tools and like its brevity and beauty of interface, but it doesn't seem to be one of the popular ones - it's not even listed on the Twitter Libraries page.
There are, however, plenty of others listed:
oauth-python-twitter2 by Konpaku Kogasa. Combines python-twitter and oauth-python-twitter to create an evolved OAuth Pokemon.
python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API.
python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client.
twitty-twister by Dustin Sallings. A Twisted interface to Twitter.
twython by Ryan McGrath. REST and Search library inspired by python-twitter.
Tweepy by Josh Roesslein. Supports OAuth, Search API, Streaming API.
My requirements are fairly simple:
Be able to use OAuth
Be able to follow a user
Be able to send a direct message
Be able to post
Streaming API would be nice
Twisted one aside (I'm not using twisted in this case), have you used any of the others, and if so, do you recommend them?
[Update] FWIW, I ended up going with Python Twitter Tools again. The new version supported OAuth nicely, and it's a very clever API, so I stuck to it.
| [
"python-twitter should cover the first four requirements. I've used it before, and it's fairly easy to start developing with it. For leveraging Twitter's streaming API, I would recommend tweetstream. It's a fantastic Python module that grabs tweets in real-time as they are posted. Based on whether you have gardenho... | [
24,
21,
1
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0003577399_python_twitter.txt |
Q:
Responding to httpRequest after using threading.Timer to delay response
I'm trying to patch a testing framework built in python for javascript called mootools-test-runner (i'm a front end developer by day, so my python skills are pretty weak... really weak.)
The use case is we want to be able to make a json request to the server and have it delay x amount of time before it returns -- originally it was written to use a sleep method, but that prevented multiple simultaneous requests. Sooo... after poking around for about a day i arrived at the code below. The problem i'm seeing (although there could well be many problems with my code) is:
The view test_runner.views.echo_json didn't return an HttpResponse object.
if anyone could offer any advice or point me in the right direction I would be super grateful -- thanks!
def echo_json(req, wasDelayed=False):
if req.REQUEST.get('delay') and wasDelayed == False:
sleeper(req, echo_jsonp)
else:
response = {}
callback = req.REQUEST.get('callback', False)
noresponse_eys = ['callback', 'delay']
for key, value in req.REQUEST.items():
if key not in noresponse_keys:
response.update({key: value})
response = simplejson.dumps(response)
if callback:
response = '%s(%s);' % (callback, response)
return HttpResponse(response, mimetype='application/javascript')
def sleeper(req, callback)
delay = float(req.REQUEST.get('delay'))
t = threading.Timer(delay, functools.partial(callback, req, true))
t.start()
A:
Are you sure you want the return statement inside the for key, value loop? You're only allowing a single iteration, and returning.
Also, check the flow of the function. There are cases in which it will return None. Easiest way to do this is printing out your request object and examining it in the cases in which the function doesn't return an HttpResponse object.
See that your function will return None if:
req.request contains the key 'delay' and wasDelayed is True
req.REQUEST.items() is empty
I can't be sure, but I think the 2 problems are the else: and the return there. Shouldn't the code below the else: be executing whether the response is delayed or not? And shouldn't the return statement be outside the for loop?
| Responding to httpRequest after using threading.Timer to delay response | I'm trying to patch a testing framework built in python for javascript called mootools-test-runner (i'm a front end developer by day, so my python skills are pretty weak... really weak.)
The use case is we want to be able to make a json request to the server and have it delay x amount of time before it returns -- originally it was written to use a sleep method, but that prevented multiple simultaneous requests. Sooo... after poking around for about a day i arrived at the code below. The problem i'm seeing (although there could well be many problems with my code) is:
The view test_runner.views.echo_json didn't return an HttpResponse object.
if anyone could offer any advice or point me in the right direction I would be super grateful -- thanks!
def echo_json(req, wasDelayed=False):
if req.REQUEST.get('delay') and wasDelayed == False:
sleeper(req, echo_jsonp)
else:
response = {}
callback = req.REQUEST.get('callback', False)
noresponse_eys = ['callback', 'delay']
for key, value in req.REQUEST.items():
if key not in noresponse_keys:
response.update({key: value})
response = simplejson.dumps(response)
if callback:
response = '%s(%s);' % (callback, response)
return HttpResponse(response, mimetype='application/javascript')
def sleeper(req, callback)
delay = float(req.REQUEST.get('delay'))
t = threading.Timer(delay, functools.partial(callback, req, true))
t.start()
| [
"Are you sure you want the return statement inside the for key, value loop? You're only allowing a single iteration, and returning.\nAlso, check the flow of the function. There are cases in which it will return None. Easiest way to do this is printing out your request object and examining it in the cases in which t... | [
0
] | [] | [] | [
"django",
"httpresponse",
"multithreading",
"python",
"timer"
] | stackoverflow_0004010071_django_httpresponse_multithreading_python_timer.txt |
Q:
Bash Script for MythTV which requires Python Dependencies
I wrote a bash script which renames MythTV files based upon data it receives. I wrote it in bash because bash has the strong points of textual data manipulation and ease of use.
You can see the script itself here: http://code.google.com/p/mythicallibrarian/source/browse/trunk/mythicalLibrarian
I have several users which are first time Linux users. I've created an installation script here which checks dependencies and sets things up in a graphical manner. You can see the setup script here: http://code.google.com/p/mythicallibrarian/source/browse/trunk/mythicalSetup.sh
Recently, there were some changes to MythTV which require me to migrate the mysql database access in mythicalLibrarian to a Python bindings script. here: http://code.google.com/p/mythicallibrarian/source/browse/trunk/pythonBindings/MythDataGrabber
Previously, I've tested dependencies using a system like this:
test "`uname`" != "Darwin" && LinuxDep=1 || LinuxDep=0
if which agrep >/dev/null; then
echo "Verified agrep exists"
else
test "$LinuxDep" = "1" && echo "Please install 'agrep' on your system" || echo "Please obtain MacPorts and install package agrep"
d="agrep "
fi
.........................
if which agrep>/dev/null && which curl>/dev/null && which dialog>/dev/null; then
echo "All checks complete!!!"
else
echo "the proper dependencies must be installed..."
echo "The missing dependencies are $a$b$c$d$e"
test "$LinuxDep" = "1" && echo "Debian based users run: apt-get install $a$b$c$d$e" || echo "Please obtain MacPorts and run: port install $a$b$c"
if [ "$LinuxDep" = "0" ]; then
read -n1 -p " Would you like some help on installing MacPorts? Select: (y)/n" MacPortsHelp
The python dependencies make it a bit more difficult. I don't know how to test if I have the linux pacakge "libmyth-python" and "python-lxml" on the system.
How, from BASH, can I test that my Python script MythDataGrabber has its
from MythTV import MythDB
requirement satisfied?
A:
You can check the status code of:
python -c "import MythDB.MythTV"
If it returns non-zero, there was an error, likely an ImportError.
A:
Write a Python script:
try:
from MythTV import MythDB
print "Yes"
except ImportError:
print "No"
then run the Python script from your Bash script, and check its output.
| Bash Script for MythTV which requires Python Dependencies | I wrote a bash script which renames MythTV files based upon data it receives. I wrote it in bash because bash has the strong points of textual data manipulation and ease of use.
You can see the script itself here: http://code.google.com/p/mythicallibrarian/source/browse/trunk/mythicalLibrarian
I have several users which are first time Linux users. I've created an installation script here which checks dependencies and sets things up in a graphical manner. You can see the setup script here: http://code.google.com/p/mythicallibrarian/source/browse/trunk/mythicalSetup.sh
Recently, there were some changes to MythTV which require me to migrate the mysql database access in mythicalLibrarian to a Python bindings script. here: http://code.google.com/p/mythicallibrarian/source/browse/trunk/pythonBindings/MythDataGrabber
Previously, I've tested dependencies using a system like this:
test "`uname`" != "Darwin" && LinuxDep=1 || LinuxDep=0
if which agrep >/dev/null; then
echo "Verified agrep exists"
else
test "$LinuxDep" = "1" && echo "Please install 'agrep' on your system" || echo "Please obtain MacPorts and install package agrep"
d="agrep "
fi
.........................
if which agrep>/dev/null && which curl>/dev/null && which dialog>/dev/null; then
echo "All checks complete!!!"
else
echo "the proper dependencies must be installed..."
echo "The missing dependencies are $a$b$c$d$e"
test "$LinuxDep" = "1" && echo "Debian based users run: apt-get install $a$b$c$d$e" || echo "Please obtain MacPorts and run: port install $a$b$c"
if [ "$LinuxDep" = "0" ]; then
read -n1 -p " Would you like some help on installing MacPorts? Select: (y)/n" MacPortsHelp
The python dependencies make it a bit more difficult. I don't know how to test if I have the linux pacakge "libmyth-python" and "python-lxml" on the system.
How, from BASH, can I test that my Python script MythDataGrabber has its
from MythTV import MythDB
requirement satisfied?
| [
"You can check the status code of:\npython -c \"import MythDB.MythTV\"\n\nIf it returns non-zero, there was an error, likely an ImportError.\n",
"Write a Python script:\ntry:\n from MythTV import MythDB\n print \"Yes\"\nexcept ImportError:\n print \"No\"\n\nthen run the Python script from your Bash scrip... | [
5,
0
] | [] | [] | [
"bash",
"dependencies",
"python"
] | stackoverflow_0004010200_bash_dependencies_python.txt |
Q:
comparing two lists, python
I should define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. For the sake of the exercise, I should write it using two nested for-loops. What am I doing wrong?
def overlapping(a,b):
for char in a:
for char2 in b:
return char in char2
Any suggestions how to make it work?
A:
You should use == and not the in operator
def overlapping(list_a,list_b):
for char_in_list_a in list_a:
for char_in_list_b in list_b:
if char_in_list_a == char_in_list_b:
return True
return False
If you want something using set:
def overlapping(a,b):
return bool(set(a) & set(b))
A:
If you really need to use 2 loops:
def overlapping(a,b):
for char1 in a:
for char2 in b:
if char1 == char2: return True
return False
But the solution with sets is much better.
A:
Return ends the function immediately when executed. Since this is a homework, you should figure working solution by yourself. You might consider using a set.
| comparing two lists, python | I should define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. For the sake of the exercise, I should write it using two nested for-loops. What am I doing wrong?
def overlapping(a,b):
for char in a:
for char2 in b:
return char in char2
Any suggestions how to make it work?
| [
"You should use == and not the in operator\ndef overlapping(list_a,list_b):\n for char_in_list_a in list_a:\n for char_in_list_b in list_b:\n if char_in_list_a == char_in_list_b:\n return True\n return False\n\nIf you want something using set:\ndef overlapping(a,b):\n ... | [
2,
2,
0
] | [] | [] | [
"for_loop",
"nested",
"python"
] | stackoverflow_0004010218_for_loop_nested_python.txt |
Q:
Simplify the changing of this binary variable
When I am writing my code, I find the following situation many times:
def Mwindow_stayontop(self, event):
if CFG["AlwOnTop"] == 1:
self.SetWindowStyle(wx.DEFAULT_FRAME_STYLE)
CFG["AlwOnTop"] = 0
else:
self.SetWindowStyle(wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP)
CFG["AlwOnTop"] = 1
Can anybody think of a simpler way of doing this? I tried to use SIN and COS to alternate the value between 0 and 1, but couldn't.
Ideas?
A:
CFG["AlwOnTop"] = 1 - CFG["AlwOnTop"]
or
CFG["AlwOnTop"] = not CFG["AlwOnTop"]
The complete function could be:
def Mwindow_stayontop(self, event):
CFG["AlwOnTop"] = 1 - CFG["AlwOnTop"]
self.SetWindowStyle(wx.DEFAULT_FRAME_STYLE | CFG["AlwOnTop"]*wx.STAY_ON_TOP)
though some might consider that too compacted.
A:
Here's a short version:
def Mwindow_stayontop(self, event):
CFG["AlwOnTop"] = not CFG["AlwOnTop"]
self.setWindowStyle(wx.DEFAULT_FRAME_STYLE |
(wx.STAY_ON_TOP if CFG["AlwOnTop"] else 0))
If you want to consider the AlwOnTop as a boolean property, you can use the fact that 0 is False and 1 is True to your advantage. not will alternate the states.
| Simplify the changing of this binary variable | When I am writing my code, I find the following situation many times:
def Mwindow_stayontop(self, event):
if CFG["AlwOnTop"] == 1:
self.SetWindowStyle(wx.DEFAULT_FRAME_STYLE)
CFG["AlwOnTop"] = 0
else:
self.SetWindowStyle(wx.DEFAULT_FRAME_STYLE | wx.STAY_ON_TOP)
CFG["AlwOnTop"] = 1
Can anybody think of a simpler way of doing this? I tried to use SIN and COS to alternate the value between 0 and 1, but couldn't.
Ideas?
| [
"CFG[\"AlwOnTop\"] = 1 - CFG[\"AlwOnTop\"]\n\nor\nCFG[\"AlwOnTop\"] = not CFG[\"AlwOnTop\"]\n\nThe complete function could be:\ndef Mwindow_stayontop(self, event):\n CFG[\"AlwOnTop\"] = 1 - CFG[\"AlwOnTop\"]\n self.SetWindowStyle(wx.DEFAULT_FRAME_STYLE | CFG[\"AlwOnTop\"]*wx.STAY_ON_TOP)\n\nthough some might ... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004010301_python.txt |
Q:
List membership in Python without "in"
How to define a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise I should pretend Python did not have this operator.
This is what I've come up with, but it doesn't work!
def is_member(x, a):
return x == a[::]
A:
I can think of two (edit: three) ways to do this:
First:
def is_member(array, value):
try:
array.index(value)
except ValueError:
return False
else:
return True
Second:
def is_member(array, value):
for item in array:
if item == value:
return True
return False
EDIT: Also, third:
def is_member(array, value):
return array.count(value) > 0
A:
Recursive solution:
def is_member(value, array):
if len(array) == 0:
return False
return value == array[0] or is_member(value, array[1:])
A:
Using a generator expression (note that this in operator has nothing to do with the another one)
def is_member(x, a):
return any(x == y for y in a)
>>> is_member(10, xrange(1000000000000000))
True
A:
You could simply just iterate over every element in the list then:
def is_member(col, a):
for i in xrange(len(col)):
if a == col[i]: return True
return False
>> a = [1,2,3,4]
>> is_member(a, 2)
True
>> is_member(a, 5)
False
A:
Without using the "in" operator:
from itertools import imap
def is_member( item, array ):
return any( imap(lambda x: x == item, array ) )
which will cycle through the items of the list, one at a time, and short circuit when it hits a value that is True.
A:
Well, there are a lot of ways to do this, of course -- but you're a little hamstrung by the prohibition of "in" anywhere in the code. Here are a few things to try.
Variations on a theme ...
def is_member(item, seq):
return sum(map(lambda x: x == item, seq)) > 0
def is_member(item, seq):
return len(filter(lambda x: x != item, seq)) != len(seq)
You may have heard that asking for forgiveness is better than asking for permission ...
def is_member(item, seq):
try:
seq.index(item)
return True
except:
return False
Or something a little more functional-flavored ...
import itertools, operator, functools
def is_member(item, seq):
not_eq = functools.partial(operator.ne, item)
return bool(list(itertools.dropwhile(not_eq, seq)))
But, since your requirements preclude the use of the looping construct which would be most reasonable, I think the experts would recommend writing your own looping framework. Something like ...
def loop(action, until):
while True:
action()
if until():
break
def is_member(item, seq):
seq = seq
sigil = [False]
def check():
if seq[0] == item:
sigil[0] = True
def til():
seq.remove(seq[0])
return not len(seq)
loop(check, til)
return sigil[0]
Let us know how it goes.
| List membership in Python without "in" | How to define a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise I should pretend Python did not have this operator.
This is what I've come up with, but it doesn't work!
def is_member(x, a):
return x == a[::]
| [
"I can think of two (edit: three) ways to do this:\nFirst:\ndef is_member(array, value):\n try:\n array.index(value)\n except ValueError:\n return False\n else:\n return True\n\nSecond:\ndef is_member(array, value):\n for item in array:\n if item == value:\n return... | [
4,
3,
2,
1,
1,
0
] | [] | [] | [
"membership",
"python"
] | stackoverflow_0004008380_membership_python.txt |
Q:
Is Python bad at XML?
EDIT
The use of the phrase "bad at XML" in this question has been a point of contention, so I'd like to start out by providing a very clear definition of what I mean by this term in this context: if support for standard XML APIs is poor, and forces one to use a language-specific API, in which namespaces seem to be an afterthought, then I would be inclined to characterize that language as being not as well suited to using XML as other mainstream languages that do not have these issues. "Bad at XML" is just a shorthand for these conditions, and I think it is a fair way to characterize it. As I will describe, my initial experience with Python has raised concerns about whether it fulfils these conditions; but, because in general my experience with Python has been quite positive, it seems likely that I'm missing something, thus motivating this question.
I'm trying to do some very simple XML processing with Python. I had initially hoped to be able to reuse my knowledge of standard W3C DOM API's, and happily found that the xml.dom and xml.dom.minidom modules did a good job of supporting these API's. Unfortunately, however, serialization proved to be problematic, for the following reasons:
xml.dom does not come with a serializer
the PyXML library, which includes a serializer for xml.dom, is no longer maintained, AND
minidom does not support serialization of namespaces, even though namespaces are supported in the API
I looked through the list of other W3C-like libraries here:
http://wiki.python.org/moin/PythonXml#W3CDOM-likelibraries
I found that many other libraries, such as 4Suite and libxml2dom, are also not maintained.
On the other hand, itools at first glance appears to be maintained, but there does not appear to be an Ubuntu/Debian package available, and so would be difficult to deploy and maintain.
At this point, it seemed like trying to use W3C DOM API's in my Python application was going to be dead-end, and I began to look at the ElementTree API. But the way the eTree API supports namespaces I think is horribly ugly, requiring one to use string concatenation every time an element in a particular namespace is created:
http://lxml.de/tutorial.html#namespaces
So, my question is, have I overlooked something, or is support for XML (in particular W3C DOM) actually quite bad in Python?
EDIT
Here follows a list of more precise questions, the answers to which would really help me:
Is there reasonable support for W3C DOM in Python?
If not xml.dom, do you use e.g. etree instead of W3C DOM?
If so, which library is best, and how do you overcome the issues regarding namespacing in the API?
If you use W3C DOM instead, are you aware of a library that implements serialization with support for namespaces?
A:
I would say python handles XML pretty well. The number of different libraries available speaks to that - you have lots of options. And if there are features missing from libraries that you would like to use, feel free to contribute some patches!
I personally use the DOM and lxml.etree (etree is really fast). However, I feel your pain about the namespace thing. I wrote a quick helper function to deal with it:
DEFAULT_NS = "http://www.domain.org/path/to/xml"
def add_xml_namespace(path, namespace=DEFAULT_NS):
"""Adds namespaces to an XPath-ish expression path for etree
Test simple expression:
>>> add_xml_namespace('image/namingData/fileBaseName')
'{http://www.domain.org/path/to/xml}image/{http://www.domain.org/path/to/xml}namingData/{http://www.domain.org/path/to/xml}fileBaseName'
More complicated expression
>>> add_xml_namespace('.//image/*')
'.//{http://www.domain.org/path/to/xml}image/*'
>>> add_xml_namespace('.//image/text()')
'.//{http://www.domain.org/path/to/xml}image/text()'
"""
pattern = re.compile(r'^[A-Za-z0-9-]+$')
tags = path.split('/')
for i in xrange(len(tags)):
if pattern.match(tags[i]):
tags[i] = "{%s}%s" % (namespace, tags[i])
return '/'.join(tags)
I use it like so:
from lxml import etree
from utilities import add_xml_namespace as ns
tree = etree.parse('file.xml')
node = tree.get_root().find(ns('root/group/subgroup'))
# etc.
If you don't know the namespace ahead of time, you can extract it from a root node:
tree = etree.parse('file.xml')
root = tree.getroot().tag
namespace = root[1:root.index('}')]
ns = lambda path: add_xml_namespace(path, namespace)
...
Additional comment: There is a little work involved here, but work is necessary when dealing with XML. That's not a python issue, it's an XML issue.
A:
Python is great at handling XML, I consider lxml to be the best xml library I have ever worked with, it is powerful and significantly simpler the DOM. The namespace handling took some getting used to, but I think it is another great way lxml keeps things simple.
EDIT
After re reading the question, it is unclear exactly whether the the author meant the serialization of python objects, or just the DOM tree. The portion of my answer bellow assumed the former.
XML serialization is a completely different issue. Personal I don't think it is very important. Most XML serializers produce output that its pretty specific to the language or runtime, which defeats the purpose of having such an open format. I realize that there are some generic XML serialization schema, but Python provides 2 solutions that are superior for 95% of situations, Pickling and JSON.
If your application doesn't have to share objects with non-python systems, Pickling is the fastest and most powerful serialization solution you will find. JSON is significantly faster to parse and generate, and much easier to work with than XML. JSON has plenty of limitations, but it is frequently easier to work around them, than deal with the headaches of XML.
There are plenty of other serialization formats that, depending on the application, I would recommend ahead of XML (E.G.: Google Protocol Buffers, or YAML.)
Also, don't forget about SAX. Event driven parsers are only useful for reading XML, but I have found that it is still the best solution for some problems.
A:
But the way the eTree API supports namespaces I think is horribly ugly, requiring one to use string concatenation every time an element in a particular namespace is created
Here's how you create an element with a namespace in .NET's System.Linq.Xml DOM:
XNamespace ns = "my-namespace";
XElement elm = new XElement(ns + "foo");
Here's how you create an element in a namespace in lxml:
ns = "{my-namespace}"
elm = etree.Element(ns + "foo")
I'm not seeing horrible ugliness here. In fact, the developers of the .NET API have bent over backwards, creating base classes that support operator overloading, to make it possible for their API to handle namespaces as intuitively as lxml's does.
How this is uglier than the W3C DOM requiring you to use different methods to create elements with and without namespaces is beyond me.
| Is Python bad at XML? | EDIT
The use of the phrase "bad at XML" in this question has been a point of contention, so I'd like to start out by providing a very clear definition of what I mean by this term in this context: if support for standard XML APIs is poor, and forces one to use a language-specific API, in which namespaces seem to be an afterthought, then I would be inclined to characterize that language as being not as well suited to using XML as other mainstream languages that do not have these issues. "Bad at XML" is just a shorthand for these conditions, and I think it is a fair way to characterize it. As I will describe, my initial experience with Python has raised concerns about whether it fulfils these conditions; but, because in general my experience with Python has been quite positive, it seems likely that I'm missing something, thus motivating this question.
I'm trying to do some very simple XML processing with Python. I had initially hoped to be able to reuse my knowledge of standard W3C DOM API's, and happily found that the xml.dom and xml.dom.minidom modules did a good job of supporting these API's. Unfortunately, however, serialization proved to be problematic, for the following reasons:
xml.dom does not come with a serializer
the PyXML library, which includes a serializer for xml.dom, is no longer maintained, AND
minidom does not support serialization of namespaces, even though namespaces are supported in the API
I looked through the list of other W3C-like libraries here:
http://wiki.python.org/moin/PythonXml#W3CDOM-likelibraries
I found that many other libraries, such as 4Suite and libxml2dom, are also not maintained.
On the other hand, itools at first glance appears to be maintained, but there does not appear to be an Ubuntu/Debian package available, and so would be difficult to deploy and maintain.
At this point, it seemed like trying to use W3C DOM API's in my Python application was going to be dead-end, and I began to look at the ElementTree API. But the way the eTree API supports namespaces I think is horribly ugly, requiring one to use string concatenation every time an element in a particular namespace is created:
http://lxml.de/tutorial.html#namespaces
So, my question is, have I overlooked something, or is support for XML (in particular W3C DOM) actually quite bad in Python?
EDIT
Here follows a list of more precise questions, the answers to which would really help me:
Is there reasonable support for W3C DOM in Python?
If not xml.dom, do you use e.g. etree instead of W3C DOM?
If so, which library is best, and how do you overcome the issues regarding namespacing in the API?
If you use W3C DOM instead, are you aware of a library that implements serialization with support for namespaces?
| [
"I would say python handles XML pretty well. The number of different libraries available speaks to that - you have lots of options. And if there are features missing from libraries that you would like to use, feel free to contribute some patches!\nI personally use the DOM and lxml.etree (etree is really fast). Howe... | [
4,
1,
1
] | [] | [] | [
"dom",
"python",
"xml"
] | stackoverflow_0004005641_dom_python_xml.txt |
Q:
Ackermann function versus n nested loops
I'm working my way thorugh a book on computation (Minksy 1967) and am having a hard time with relating a recursive function to a function defined in terms of loops. Specifically he asks to find the relationship between two functions:
The Ackermann function (all code in python):
def a(n,m):
if n==0:
return m+1
if m==0:
return a(n-1,1)
return a(n-1,a(n,m-1))
And a function that computes with n nested loops:
def p(n,m):
for i_1 in range(m):
for i_2 in range(m):
...
for i_n in range(m):
m+=1
A recursive way of writing this (with one loop) is:
def p(n,m):
if n==0:
return m+1
for i in range(m):
m=p(n-1,m)
return m
Or a fully recursive way to write it would be:
def p(n,m):
return P(n,m,m)
def P(n,k,m):
if n==0:
return m+1
if k==1:
return P(n-1,m,m)
m=P(n,k-1,m)
return P(n-1,m,m)
Is there some simple way these two functions are related? I feel like I'm crawling around in a fog - any insight you could give me into how to approach these sorts of problems would be greatly appreciated. Also, is there a way to implement the fully recursive loop function without the introduction of a third parameter? Thanks.
A:
Uhm... I don't think this will help you much, I'm kinda baffled too, but here are my thoughts.
Ackerman(0, m) == p(0, m)
Ackerman(1, m + 1) == p(1, m)
edit -- wait I think I miscopied the function. I'll give this more thought later, and if I think of something I'll update!
| Ackermann function versus n nested loops | I'm working my way thorugh a book on computation (Minksy 1967) and am having a hard time with relating a recursive function to a function defined in terms of loops. Specifically he asks to find the relationship between two functions:
The Ackermann function (all code in python):
def a(n,m):
if n==0:
return m+1
if m==0:
return a(n-1,1)
return a(n-1,a(n,m-1))
And a function that computes with n nested loops:
def p(n,m):
for i_1 in range(m):
for i_2 in range(m):
...
for i_n in range(m):
m+=1
A recursive way of writing this (with one loop) is:
def p(n,m):
if n==0:
return m+1
for i in range(m):
m=p(n-1,m)
return m
Or a fully recursive way to write it would be:
def p(n,m):
return P(n,m,m)
def P(n,k,m):
if n==0:
return m+1
if k==1:
return P(n-1,m,m)
m=P(n,k-1,m)
return P(n-1,m,m)
Is there some simple way these two functions are related? I feel like I'm crawling around in a fog - any insight you could give me into how to approach these sorts of problems would be greatly appreciated. Also, is there a way to implement the fully recursive loop function without the introduction of a third parameter? Thanks.
| [
"Uhm... I don't think this will help you much, I'm kinda baffled too, but here are my thoughts.\n\nAckerman(0, m) == p(0, m)\nAckerman(1, m + 1) == p(1, m)\n\nedit -- wait I think I miscopied the function. I'll give this more thought later, and if I think of something I'll update!\n"
] | [
1
] | [] | [] | [
"computability",
"computer_science",
"python"
] | stackoverflow_0004010367_computability_computer_science_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.