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: Iterating through model fields - Django I'm trying to iterate through fields as they are written down within my model: currently I'm using this: def attrs(self): for attr, value in self.__dict__.iteritems(): yield attr, value but the order seems pretty much random :( Any ideas? A: The _meta attribute on Model classes and instances is a django.db.models.options.Options which provides access to all sorts of useful information about the Model in question. For fields, it will give you them in the order they were created (i.e. the same order they were declared). def attrs(self): for field in self._meta.fields: yield field.name, getattr(self, field.name)
Iterating through model fields - Django
I'm trying to iterate through fields as they are written down within my model: currently I'm using this: def attrs(self): for attr, value in self.__dict__.iteritems(): yield attr, value but the order seems pretty much random :( Any ideas?
[ "The _meta attribute on Model classes and instances is a django.db.models.options.Options which provides access to all sorts of useful information about the Model in question.\nFor fields, it will give you them in the order they were created (i.e. the same order they were declared).\ndef attrs(self):\n for field...
[ 24 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003159614_django_django_models_python.txt
Q: Problem with scraping data using BeautifulSoup I have written the following trial code to retreive the title of legislative acts from the European parliament. import urllib2 from BeautifulSoup import BeautifulSoup search_url = "http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-%.4d&language=EN" for number in xrange(1,10): url = search_url % number page = urllib2.urlopen(url).read() soup = BeautifulSoup(page) title = soup.findAll("title") print title However, whenever I run it i get the following error: Traceback (most recent call last): File "<stdin>", line 20, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 70: ordinal not in range(128) I have narrowed it down to BeautifulSoup not being able to read the fourth document in the loop. Can anyone explain to me what I am doing wrong? With kind regards Thomas A: BeautifulSoup works in Unicode, so it's not responsible for that decoding error. More likely, your problem comes with the print statement -- your standard output seems to be in ascii (i.e., sys.stdout.encoding = 'ascii' or absent) and therefore you would indeed get such errors if trying to print a string containing non-ascii characters. What's your OS? How is your console AKA terminal set (e.g. if on Windows what "codepage")? Did you set in the environment PYTHONIOENCODING to control sys.stdout.encoding or are you just hoping the encoding will be picked up automatically? On my Mac, where the encoding is correct detected, running your code (save for also printing the number together with each title, for clarity) works fine and shows: $ python ebs.py 1 [<title>REPORT Report on the proposal for a Council regulation temporarily suspending autonomous Common Customs Tariff duties on imports of certain industrial products into the autonomous regions of Madeira and the Azores - A7-0001/2010</title>] 2 [<title>REPORT Report on the proposal for a Council directive concerning mutual assistance for the recovery of claims relating to taxes, duties and other measures - A7-0002/2010</title>] 3 [<title>REPORT Report on the proposal for a regulation of the European Parliament and of the Council amending Council Regulation (EC) No 1085/2006 of 17 July 2006 establishing an Instrument for Pre-Accession Assistance (IPA) - A7-0003/2010</title>] 4 [<title>REPORT on equality between women and men in the European Union – 2009 - A7-0004/2010</title>] 5 [<title>REPORT Report on the proposal for a Council decision on the conclusion by the European Community of the Convention on the International Recovery of Child Support and Other Forms of Family Maintenance - A7-0005/2010</title>] 6 [<title>REPORT on the proposal for a Council directive on administrative cooperation in the field of taxation - A7-0006/2010</title>] 7 [<title>REPORT Report on promoting good governance in tax matters - A7-0007/2010</title>] 8 [<title>REPORT Report on the proposal for a Council Directive amending Directive 2006/112/EC as regards an optional and temporary application of the reverse charge mechanism in relation to supplies of certain goods and services susceptible to fraud - A7-0008/2010</title>] 9 [<title>REPORT Recommendation on the proposal for a Council decision concerning the conclusion, on behalf of the European Community, of the Additional Protocol to the Cooperation Agreement for the Protection of the Coasts and Waters of the North-East Atlantic against Pollution - A7-0009/2010</title>] $ A: Replacing print title with for t in title: print(t) or print('\n'.join(t.string for t in title)) works. I'm not entirely sure why print <somelist> sometimes works, and sometimes doesn't however. A: If you want to print the titles to a file, you need to specify some encoding that can represent the non-ascii char, utf8 should work fine. To do this, you need to add: out = codecs.open('titles.txt', 'w', 'utf8') at the top of the script and print to the file: print >> out, title
Problem with scraping data using BeautifulSoup
I have written the following trial code to retreive the title of legislative acts from the European parliament. import urllib2 from BeautifulSoup import BeautifulSoup search_url = "http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-%.4d&language=EN" for number in xrange(1,10): url = search_url % number page = urllib2.urlopen(url).read() soup = BeautifulSoup(page) title = soup.findAll("title") print title However, whenever I run it i get the following error: Traceback (most recent call last): File "<stdin>", line 20, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 70: ordinal not in range(128) I have narrowed it down to BeautifulSoup not being able to read the fourth document in the loop. Can anyone explain to me what I am doing wrong? With kind regards Thomas
[ "BeautifulSoup works in Unicode, so it's not responsible for that decoding error. More likely, your problem comes with the print statement -- your standard output seems to be in ascii (i.e., sys.stdout.encoding = 'ascii' or absent) and therefore you would indeed get such errors if trying to print a string containi...
[ 4, 1, 0 ]
[]
[]
[ "beautifulsoup", "loops", "python", "web_scraping" ]
stackoverflow_0003158433_beautifulsoup_loops_python_web_scraping.txt
Q: Parsing JSON with Python I'm getting an error while parsing a JSON response in Python. Ex: { "oneliners": [ "she\'s the one", "who opened the gates" ] } The JSON decoder coughs up on the invalid escape on the single quote. Typically do people apply a REGEX to remove the escape slash character prior to decoding a response that can potentially contain an invalid escape? A: Pyparsing ships with a JSON parsing example (or you can get it online here): >>> text = r"""{ ... "oneliners": [ ... "she\'s the one", ... "who opened the gates" ... ] ... } """ >>> text '{ \n "oneliners": [ \n "she\\\'s the one", \n "who opened the gates" \n ] \n} ' >>> obj = jsonObject.parseString(text) >>> obj.asList() [['oneliners', ["she\\'s the one", 'who opened the gates']]] >>> obj.asDict() {'oneliners': (["she\\'s the one", 'who opened the gates'], {})} >>> obj.oneliners (["she\\'s the one", 'who opened the gates'], {}) >>> obj.oneliners.asList() ["she\\'s the one", 'who opened the gates'] Don't be put off by the seeming inclusion of a dict (the '{}') in obj.oneliners, that is just the repr output for a pyparsing ParseResults object. You can just treat obj.oneliners like an ordinary list - or if you like, extract its contents as a list using asList as shown. A: if you have \' character sequence in your JSON string representation, and you KNOW it should be ', it means it was improperly escaped before, you should fix the problem there. if you can't, you should do the replacement before you provide such a string to the JSON parser. simplejson will fail parsing it, cjson or anyjson would not fail, but will handle it literally, so you will have the backslash-apostrophe sequence in the resulting data.
Parsing JSON with Python
I'm getting an error while parsing a JSON response in Python. Ex: { "oneliners": [ "she\'s the one", "who opened the gates" ] } The JSON decoder coughs up on the invalid escape on the single quote. Typically do people apply a REGEX to remove the escape slash character prior to decoding a response that can potentially contain an invalid escape?
[ "Pyparsing ships with a JSON parsing example (or you can get it online here):\n>>> text = r\"\"\"{\n... \"oneliners\": [\n... \"she\\'s the one\",\n... \"who opened the gates\"\n... ]\n... } \"\"\"\n>>> text\n'{ \\n \"oneliners\": [ \\n \"she\\\\\\'s the one\", \\...
[ 1, 1 ]
[ "import json\ns = \"\"\"{\n \"oneliners\": [\n \"she\\'s the one\",\n \"who opened the gates\"\n ]\n}\"\"\"\n\nprint \"%r\" % json.loads(s)\n\nThis appears to work just fine, in Python 2.6 and upwards anyway.\n" ]
[ -1 ]
[ "json", "python" ]
stackoverflow_0003155758_json_python.txt
Q: python open() how to change set files name/title If I open a file (image) in python with f = open('/path/to/file.jpg', 'r+') I have a function f.title() and I get the full path of the file back. How can I change the opened files name/repr/title to something else? A: You don't change filenames using open, that's for sure. You'll want to use os.rename. But if you're trying to change the name the file has within your program but NOT the actual filename, why are you trying to do that/what would be the point in that? I guess you could detach the buffer from the file object and assign it to a new object with the title you want, if you're working with Python 3 (thought you could do it in Python 2(.6) as well, but don't see any mention of the detach method in the documentation of the Python 2.6 file object or its io module), but really, I don't quite see the point... Oh wait, if you just want the filename for use elsewhere and don't necessarily need to change the name itself: import os.path f = open('/path/to/file.jpg', 'r+') print(os.path.basename(f.name)) #don't include the parentheses if you're working in Python 2.6 and not using the right __future__ imports or working in something prior to 2.6 This will output 'file.jpg'. Not sure if it helps you if blob.filename is an automatic assignment, though, unless you're willing to subclass whatever class blob is... A: It doesn't work for me (Python 2.6, on Windows); I have to use the "name" attribute: >>> f = open(r'C:\test.txt', 'r+') >>> f.title() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'file' object has no attribute 'title' >>> f.name 'C:\\test.txt' According to the documentation, "name" is read-only. And unfortunately, you can't set arbitrary attributes on file objects: >>> f.title = f.name Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'file' object has no attribute 'title'
python open() how to change set files name/title
If I open a file (image) in python with f = open('/path/to/file.jpg', 'r+') I have a function f.title() and I get the full path of the file back. How can I change the opened files name/repr/title to something else?
[ "You don't change filenames using open, that's for sure. You'll want to use os.rename.\nBut if you're trying to change the name the file has within your program but NOT the actual filename, why are you trying to do that/what would be the point in that? I guess you could detach the buffer from the file object and as...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003159652_python.txt
Q: How to determine if we are in the first week of the current month I am writing a little utility function in Python which returns a boolean, indicating whether today is in the first week of the month. This is what I have so far: import calendar import time y, m = time.localtime(time.time())[:2] data = calendar.month(y, m) In [24]: type(temp) Out[24]: <type 'str'> In [25]: print temp -------> print(temp) July 2010 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 I want to pack this string into a list of lists. Actually, it's only the first row that I want, since it is the first week, but I could generalize the function so that it allows me to check whether we are in the nth week, where 1 < n < 5 (depending on the month of course). Once I have a list of lists I then intend to check if the current day is an element in the list. Can anyone show how I can get the output from the calendar.month() method into a list of lists? Last but not the least, I may be reinventing the wheel here. If there is an inbuilt way of doing this (or maybe a more Pythonic way of doing this) someone please let me know. A: Here's a simple function which will tell you whether today is in the first week of the month: from datetime import date def first_week(): today = date.today() return today.weekday() - today.day >= -1 This is simpler than processing the output of a call into the calendar library; simply take the day of the week in numeric form (which starts at 0) and then subtract the day of the month (which starts at 1). If the result is at least -1, you're in the first week. A: Here is a total solution using the standard library. import calendar import datetime def in_first_week(today): """Expects a datetime object""" weeks = calendar.monthcalendar(today.year, today.month) firstweek = weeks[0] return today.day in firstweek today = datetime.date.today() # => datetime.date(2010, 7, 1) print in_first_week(today) # => True then = datetime.date(2010,7,10) print in_first_week(then) # => False A: calendar.monthcalendar(2010,7) This returns a list of lists as such: [[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24, 25], [26, 27, 28, 29, 30, 31, 0]]
How to determine if we are in the first week of the current month
I am writing a little utility function in Python which returns a boolean, indicating whether today is in the first week of the month. This is what I have so far: import calendar import time y, m = time.localtime(time.time())[:2] data = calendar.month(y, m) In [24]: type(temp) Out[24]: <type 'str'> In [25]: print temp -------> print(temp) July 2010 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 I want to pack this string into a list of lists. Actually, it's only the first row that I want, since it is the first week, but I could generalize the function so that it allows me to check whether we are in the nth week, where 1 < n < 5 (depending on the month of course). Once I have a list of lists I then intend to check if the current day is an element in the list. Can anyone show how I can get the output from the calendar.month() method into a list of lists? Last but not the least, I may be reinventing the wheel here. If there is an inbuilt way of doing this (or maybe a more Pythonic way of doing this) someone please let me know.
[ "Here's a simple function which will tell you whether today is in the first week of the month:\nfrom datetime import date\n\ndef first_week():\n today = date.today()\n return today.weekday() - today.day >= -1\n\nThis is simpler than processing the output of a call into the calendar library; simply take the da...
[ 5, 3, 2 ]
[]
[]
[ "calendar", "python" ]
stackoverflow_0003159908_calendar_python.txt
Q: What kind of regex would I use to match this? I have several strings which look like the following: <some_text> TAG[<some_text>@11.22.33.44] <some_text> I want to get the ip_address and only the ip_address from this line. (For the sake of this example, assume that the ip address will always be in this format xx.xx.xx.xx) Edit: I'm afraid I wasn't clear. The strings will look something like this: <some_text> TAG1[<some_text>@xx.xx.xx.xx] <some_text> TAG2[<some_text>@yy.yy.yy.yy] <some_text> Note that the 'some_text' can be a variable length. I need to associate different regex's to different tags so that when r.group() is called, the ip address will be returned. In the above case the regex's would not be different but it is a bad example. The regexes I have tried so far have been inadequate. Ideally, I would like something like this: r = re.search('(?<=TAG.*@)(\d\d.\d\d.\d\d.\d\d)', line) where line is in the format specified above. However, this does not work because you need to have a fixed width look-behind assertion. Additionally, I have tried non-capturing groups as such: r = re.search('(?<=TAG\[)(?:.*@)(\d\d.\d\d.\d\d.\d\d)', line) However, I cannot use this because r.group() will return some_text@xx.xx.xx.xx I understand that r.group(1) will return just the ip address. Unfortunately, the script I am writing requires that all my regex will return the correct result after calling r.group(). What kind of regex could I use for this situation? The code is in python. Note: All of the some_text can be variable length A: Try re.search('(?<=@)\d\d\.\d\d\.\d\d\.\d\d(?=\])', line). In fact, re.search('\d\d\.\d\d\.\d\d\.\d\d', line) may get you what you need if the only occurrence of the xx.xx.xx.xx format in the strings being checked is in those IP address sections. EDIT: As stated in my comment, to find all occurrences of the wanted pattern in a string, you just do re.findall(pattern_to_match, line). So in this case, re.findall('\d\d\.\d\d\.\d\d\.\d\d', line) (or more generally, re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', line)). EDIT 2: From your comment, this should work (with tagname being the tag of the IP address you currently want). r = re.search(tagname + '\[.+?@(?P<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', line) And then you'd just refer to it with r.group("ip") like psmears said. ...In fact, there's an easy way to make the regex a bit more concise. r = re.search(tagname + r'\[.+?@(?P<ip>(?:\d{1,3}\.?){4})', line) In fact, you could even do this: r = re.findall('(?P<tag>\S+)\[.+?@(?P<ip>(?:\d{1,3}\.?){4})', line) Which would return you a list containing the tags and their associated IP addresses, and so you wouldn't have to recheck any one string once you found the matches if you wanted to refer to the IP address of a different tag from the same string. ...In fact, going two steps further (farther?), you could do the following: r = dict((m.group("tag"), m.group("ip")) for m in re.finditer('(?P<tag>\S+)\[.+?@(?P<ip>(?:\d{1,3}\.?){4})', line)) Or in Python 3: r = {(m.group("tag"), m.group("ip")) for m in re.finditer('(?P<tag>\S+)\[.+?@(?P<ip>(?:\d{1,3}\.?){4})', line)} And then r would be a dict with the tags as keys and the IP addresses as the respective values. A: Why do you want to use groups or look behinds at all? What is wrong with re.search('TAG\[.*@(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]')? A: I don't think it's possible to do that - r.group() will always return the whole string that matched, so you're forced to use lookbehind, which as you say must be fixed width. Instead, I'd suggest modifying the script that you're writing. I'm guessing that you have a whole load of regexps that it matches, and you don't want to have to specify for each one "this one uses r.group(0)", "this one uses r.group(3)" etc. In that case, you could use Python's named groups facility: you can name a group in a regular expression like this: (?P<name>CONTENTS) then retrieve what matched with r.group("name"). What I suggest doing in your script is: match the regular expression, then test if r.group("usethis") is set. If so - use that; if not - then use r.group() as before. That way you can cope with awkward situations like this by specifying the group name usethis in the regexp - but your other regexps don't have to know or care. A: Almost but I think that you need to change the .* at the start to .*? since you may have multiple TAGs on a single line (I believe - as there is in the example) re.search('TAG(\d+)\[.*?@(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})]') The Tag ID will be in the first backreference and the IP address will be in the second back reference
What kind of regex would I use to match this?
I have several strings which look like the following: <some_text> TAG[<some_text>@11.22.33.44] <some_text> I want to get the ip_address and only the ip_address from this line. (For the sake of this example, assume that the ip address will always be in this format xx.xx.xx.xx) Edit: I'm afraid I wasn't clear. The strings will look something like this: <some_text> TAG1[<some_text>@xx.xx.xx.xx] <some_text> TAG2[<some_text>@yy.yy.yy.yy] <some_text> Note that the 'some_text' can be a variable length. I need to associate different regex's to different tags so that when r.group() is called, the ip address will be returned. In the above case the regex's would not be different but it is a bad example. The regexes I have tried so far have been inadequate. Ideally, I would like something like this: r = re.search('(?<=TAG.*@)(\d\d.\d\d.\d\d.\d\d)', line) where line is in the format specified above. However, this does not work because you need to have a fixed width look-behind assertion. Additionally, I have tried non-capturing groups as such: r = re.search('(?<=TAG\[)(?:.*@)(\d\d.\d\d.\d\d.\d\d)', line) However, I cannot use this because r.group() will return some_text@xx.xx.xx.xx I understand that r.group(1) will return just the ip address. Unfortunately, the script I am writing requires that all my regex will return the correct result after calling r.group(). What kind of regex could I use for this situation? The code is in python. Note: All of the some_text can be variable length
[ "Try re.search('(?<=@)\\d\\d\\.\\d\\d\\.\\d\\d\\.\\d\\d(?=\\])', line).\nIn fact, re.search('\\d\\d\\.\\d\\d\\.\\d\\d\\.\\d\\d', line) may get you what you need if the only occurrence of the xx.xx.xx.xx format in the strings being checked is in those IP address sections.\nEDIT: As stated in my comment, to find all ...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003152151_python_regex.txt
Q: python random.shuffle's randomness Following is from python website, about random.shuffle(x[, random]) Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random(). Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated. If I want to repeat getting a random permutation of ['a'..'k'], it seems shuffle will NOT give me the randomness. Is my understanding right? Thank you! A: You don't have anything to worry about. While under len(x) is under 2000, random.shuffle should work just fine. A: For a sequence of length 11, there are 11! or 39,916,800 (~ 225.3) possible permutations. For the Mersienne Twister (Python's random algorithm) the period is 219937 − 1. In other words, you'll be fine.
python random.shuffle's randomness
Following is from python website, about random.shuffle(x[, random]) Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random(). Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated. If I want to repeat getting a random permutation of ['a'..'k'], it seems shuffle will NOT give me the randomness. Is my understanding right? Thank you!
[ "You don't have anything to worry about. While under len(x) is under 2000, random.shuffle should work just fine.\n", "For a sequence of length 11, there are 11! or 39,916,800 (~ 225.3) possible permutations. For the Mersienne Twister (Python's random algorithm) the period is 219937 − 1. In other words, you'll b...
[ 6, 6 ]
[]
[]
[ "python", "random", "shuffle" ]
stackoverflow_0003160214_python_random_shuffle.txt
Q: Could you recommend a python library or source code for reading barcodes? I would like some help finding a python module that can identify a barcode within a scanned document. If anyone can help me at least come closer to finding an example of this I would be greatly appreciative. A: http://pypi.python.org/pypi/zbar
Could you recommend a python library or source code for reading barcodes?
I would like some help finding a python module that can identify a barcode within a scanned document. If anyone can help me at least come closer to finding an example of this I would be greatly appreciative.
[ "http://pypi.python.org/pypi/zbar\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003160320_python.txt
Q: header filtering using python i want to filter some headers in a wireshark capture (converted to text format) so i can analyse these set of headers.i need a python script to do this. any help would be appreciated A: You might want to look at dpkt. It's a Python library to simplify reading (or generating) network data. Just save your Wireshark data as a Pcap stream and it can easily be opened from within Python. I don't know exactly which headers you want or how you need them filtered and formatted, but here's an example of what you could write: (taken from a contributor's blog post) import dpkt pcap = dpkt.pcap.Reader(open('test.pcap')) for timestamp, buf in pcap: eth = dpkt.ethernet.Ethernet(buf) ip = eth.data tcp = ip.data print 'Got data from port ' + str(tcp.port)
header filtering using python
i want to filter some headers in a wireshark capture (converted to text format) so i can analyse these set of headers.i need a python script to do this. any help would be appreciated
[ "You might want to look at dpkt. It's a Python library to simplify reading (or generating) network data. Just save your Wireshark data as a Pcap stream and it can easily be opened from within Python.\nI don't know exactly which headers you want or how you need them filtered and formatted, but here's an example of...
[ 1 ]
[]
[]
[ "python", "python_2.5" ]
stackoverflow_0003160307_python_python_2.5.txt
Q: running BLAST (bl2seq) without creating sequence files I have a script that performs BLAST queries (bl2seq) The script works like this: Get sequence a, sequence b write sequence a to filea write sequence b to fileb run command 'bl2seq -i filea -j fileb -n blastn' get output from STDOUT, parse repeat 20 million times The program bl2seq does not support piping. Is there any way to do this and avoid writing/reading to the harddrive? I'm using Python BTW. A: Depending on what OS you're running on, you may be able to use something like bash's process substitution. I'm not sure how you'd set that up in Python, but you're basically using a named pipe (or named file descriptor). That won't work if bl2seq tries to seek within the files, but it should work if it just reads them sequentially. A: Is this the bl2seq program from BioPerl? If so, it doesn't look like you can do piping to it. You can, however, code your own hack using Bio::Tools::Run::AnalysisFactory::Pise, which is the recommended way of going about it. You'd have to do it in Perl, though. If this is a different bl2seq, then disregard the message. In any case, you should probably provide some more detail. A: How do you know bl2seq does not support piping.? By the way, pipes is an OS feature, not the program. If your bl2seq program outputs something, whether to STDOUT or to a file, you should be able to parse the output. Check the help file of bl2seq for options to output to file as well, eg -o option. Then you can parse the file. Also, since you are using Python, an alternative you can use is BioPython module. A: Wow. I have it figured out. The answer is to use python's subprocess module and pipes! EDIT: forgot to mention that I'm using blast2 which does support piping. (this is part of a class) def _query(self): from subprocess import Popen, PIPE, STDOUT pipe = Popen([BLAST, '-p', 'blastn', '-d', self.database, '-m', '8'], stdin=PIPE, stdout=PIPE) pipe.stdin.write('%s\n' % self.sequence) print pipe.communicate()[0] where self.database is a string containing the database filename, ie 'nt.fa' self.sequence is a string containing the query sequence This prints the output to the screen but you can easily just parse it. No slow disk I/O. No slow XML parsing. I'm going to write a module for this and put it on github. Also, I haven't gotten this far yet but I think you can do multiple queries so that the blast database does not need to be read and loaded into RAM for each query. A: I call blast2 using R script: .... system("mkfifo seq1") system("mkfifo seq2") system("echo sequence1 > seq1"), wait = FALSE) system("echo sequence2 > seq2"), wait = FALSE) system("blast2 -p blastp -i seq1 -j seq2 -m 8", intern = TRUE) .... This is 2 times slower(!) vs. writing and reading from hard drive!
running BLAST (bl2seq) without creating sequence files
I have a script that performs BLAST queries (bl2seq) The script works like this: Get sequence a, sequence b write sequence a to filea write sequence b to fileb run command 'bl2seq -i filea -j fileb -n blastn' get output from STDOUT, parse repeat 20 million times The program bl2seq does not support piping. Is there any way to do this and avoid writing/reading to the harddrive? I'm using Python BTW.
[ "Depending on what OS you're running on, you may be able to use something like bash's process substitution. I'm not sure how you'd set that up in Python, but you're basically using a named pipe (or named file descriptor). That won't work if bl2seq tries to seek within the files, but it should work if it just read...
[ 4, 1, 1, 1, 1 ]
[]
[]
[ "bioinformatics", "perl", "python", "shell", "unix" ]
stackoverflow_0002248016_bioinformatics_perl_python_shell_unix.txt
Q: Mutagen's OggFileType producing 'Type Error: NoneType' exception Ive just started using mutagen and have succefully used it with m4a, mp3, ape, afs, and flac. However Im having difficulty with the OggFileType class, when I try to create an instance of OggFileType Im presented with a "TypeError: 'NoneType' object is not callable" exception. Iv searched and searched for solutions but information and documentation on mutagen is scarce. Any help would be appreciated thanks. A snippet of the code I am using for testing path = "I:\Music\Various Artists\Studio One Classics" audiofile = "16 - Rub A Dub Style.ogg" os.chdir(path) OggTag = OggFileType(audiofile) print OggTag Traceback Traceback (most recent call last): File "I:\My Documents\Programming\python\music_organizer\mutagen_test.py", line 203, in <module> OggTag = OggFileType(audiofile) File "C:\Python26\lib\site-packages\mutagen\__init__.py", line 75, in __init__ self.load(filename, *args, **kwargs) File "C:\Python26\lib\site-packages\mutagen\ogg.py", line 441, in load self.info = self._Info(fileobj) TypeError: 'NoneType' object is not callable A: You're not supposed to use OggFileType directly. It's a base class for the other Ogg format classes -- OggVorbis, OggTheora, etc. Those all properly set _Info, _Tags, _Error appropriately. This is noted in the documentation for the ogg.py module: Read and write Ogg bitstreams and pages. This module reads and writes a subset of the Ogg bitstream format version 0. It does not read or write Ogg Vorbis files! For that, you should use mutagen.oggvorbis.
Mutagen's OggFileType producing 'Type Error: NoneType' exception
Ive just started using mutagen and have succefully used it with m4a, mp3, ape, afs, and flac. However Im having difficulty with the OggFileType class, when I try to create an instance of OggFileType Im presented with a "TypeError: 'NoneType' object is not callable" exception. Iv searched and searched for solutions but information and documentation on mutagen is scarce. Any help would be appreciated thanks. A snippet of the code I am using for testing path = "I:\Music\Various Artists\Studio One Classics" audiofile = "16 - Rub A Dub Style.ogg" os.chdir(path) OggTag = OggFileType(audiofile) print OggTag Traceback Traceback (most recent call last): File "I:\My Documents\Programming\python\music_organizer\mutagen_test.py", line 203, in <module> OggTag = OggFileType(audiofile) File "C:\Python26\lib\site-packages\mutagen\__init__.py", line 75, in __init__ self.load(filename, *args, **kwargs) File "C:\Python26\lib\site-packages\mutagen\ogg.py", line 441, in load self.info = self._Info(fileobj) TypeError: 'NoneType' object is not callable
[ "You're not supposed to use OggFileType directly. It's a base class for the other Ogg format classes -- OggVorbis, OggTheora, etc. Those all properly set _Info, _Tags, _Error appropriately. This is noted in the documentation for the ogg.py module:\n\nRead and write Ogg bitstreams and pages.\nThis module reads an...
[ 1 ]
[]
[]
[ "metadata", "mutagen", "ogg", "python" ]
stackoverflow_0003160471_metadata_mutagen_ogg_python.txt
Q: Python: Help with new line character I read in a text file that is tab delimited, i then have a list for each line, i then index out the first entry of each list, i then write this to a file. code below: import csv z = csv.reader(open('output.blast'), delimiter='\t') k = open('output.fasta', 'w') for row in z: print row[1:12] for i in row[1:12]: k.write(i+'\t') When writing to the file it writes it as one long line, i would like a new line to be started after the 11th (last) entry in each list. But i cannot figure out where to put the new line charater A: It sounds like you just want it after each row, so put it at the end of the for loop that iterates over the rows: for row in z: print row[1:12] for i in row[1:12]: k.write(i+'\t') k.write('\n') A: If you're writing it back out to a tab separated format why not use the csv package again? r = csv.reader(open('output.blast'),delimiter='\t') outfile = open('output.fasta','w') w = csv.writer(outfile,delimiter='\t') w.writerows(row[1:12] for row in r) outfile.flush() outfile.close() A: import csv z = csv.reader(open('output.blast'), delimiter='\t') k = open('output.fasta', 'w') for row in z: print row[1:12] for i in row[1:12]: k.write(i+'\t') k.write('\n ') # <- write out the newline here.
Python: Help with new line character
I read in a text file that is tab delimited, i then have a list for each line, i then index out the first entry of each list, i then write this to a file. code below: import csv z = csv.reader(open('output.blast'), delimiter='\t') k = open('output.fasta', 'w') for row in z: print row[1:12] for i in row[1:12]: k.write(i+'\t') When writing to the file it writes it as one long line, i would like a new line to be started after the 11th (last) entry in each list. But i cannot figure out where to put the new line charater
[ "It sounds like you just want it after each row, so put it at the end of the for loop that iterates over the rows:\nfor row in z:\n print row[1:12]\n for i in row[1:12]:\n k.write(i+'\\t')\n k.write('\\n')\n\n", "If you're writing it back out to a tab separated format why not use the csv package a...
[ 6, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003160508_python.txt
Q: How can I achieve layout similar to Google Image search in QT (PyQT)? I'm new to QT. I'm using PyQT for GUI development in my project. I want to achieve this layout in my application. This application searches images from an image database. Google image search layout is ideal for my purpose. I'm following the book "Rapid GUI Programming with Python and Qt" and I'm familiar with layouts. I guess I need to use a grid layout with each result image in each box of grid. & use vertical layout for (image,Qlabel,Qlabel) inside each grid box. These are some problems I'm facing. Importantly, I'm unable to display image. What control/widget do I need? I cannot find anything similar to PictureBox of .NET How do I seperate these image result by fixed gap like in the image? I'm using Horizontal & vertical spacers but that isn't working? How to set QLabel a clickable (like hyperlink). I don't want to a open a URL. Just the text should be clickable. So, that when user clicks on the link. I can show more information (like next set of results when he clicks on next page number or a new window with image in fullsize when user clicks on 'view') Do we have some new kind of control for this? This is another important issue. I'll display the page numbers of results (like shown in figure) & assuming they are clickable. How do I load a new page of results? I mean what is the equivalent of page in QT? As you can guess. This definitely wont be the first page of GUI. The first page will be exactly like http://google.com (a big logo & text box with button below it). when user clicks the search button. This page will be displayed. Again the same question comes up. How change the pages? Please give a list of controls I'm going to need for this. Tell me if I'm unaware of something. A: 1/2. For displaying the images and labels use a QListWidget with view mode set to QListView::IconMode. However, if you need to customize the display beyond what the QListWidget/QListWidgetItem api can provide you will need to create your own QAbstractListModel and use a standard QListView with it. Make sure and read Qt's primer on model/view. As for spacing the images, checkout the spacing property on the list view. Here is an example from KDE's Dolphin file manager: 3. Use a regular QLabel, but set the contents to be an href. Example: edit: Oops I see from your tags you are using PyQt, the following is C++, but should be similar to what you would do in python. QLabel *linkLabel = new QLabel; linkLabel->setTextFormat( Qt::RichText ) linkLabel->setText( "<a href=\"someurl\"> Click me! </a>" ); connect( linkLabel, SIGNAL( linkActivated ( const QString & link ) ), .... ) 4. Well, since you are using a Model/View, why bother having page numbers at all? The user will just be able to scroll the view and more pictures will be shown. This is by far the easiest solution as you don't have to do anything once you've got your M/V setup! However, if you really want to show page numbers it will require more work in your model. For example, have a track the "current page" in the model and only allow access to images on the "current page". Then in your slot connected to the linkActivated() signal tell the model to change pages. I won't go into much more detail as this seriously violates the whole idea behind model/view. The "right way" of doing this would be to subclass QListView and add pagination support, but like I said why not use scroll bars? There isn't any performance hits to doing so. 5. Use a QStackedWidget, addWidget() all your "pages" to it, then call setCurrentIndex/Widget() as needed to switch the pages. Thoughts: It seems you are very committed to cloning the look, feel, and behavior of Google Image search, which is fine, but Google Image Search is a web application that uses interaction paradigms that are very different than a normal desktop application (links, pages, etc). You are presumably developing a desktop application, and by trying to emulate the behavior of a web app you will find it difficult as the API just isn't designed to support those sorts of interactions. By all means, it is doable, but you'll have your work cut out for you. If you are extremely intent on sticking to the web based interaction style, why not code your app in javascript and HTML and toss it in a QWebView? A: Try using QListWidget with viewMode set to IconMode. It should do all for you. BUT if you need to customize your data display use QListView with your own/standard model and own delegate for painting
How can I achieve layout similar to Google Image search in QT (PyQT)?
I'm new to QT. I'm using PyQT for GUI development in my project. I want to achieve this layout in my application. This application searches images from an image database. Google image search layout is ideal for my purpose. I'm following the book "Rapid GUI Programming with Python and Qt" and I'm familiar with layouts. I guess I need to use a grid layout with each result image in each box of grid. & use vertical layout for (image,Qlabel,Qlabel) inside each grid box. These are some problems I'm facing. Importantly, I'm unable to display image. What control/widget do I need? I cannot find anything similar to PictureBox of .NET How do I seperate these image result by fixed gap like in the image? I'm using Horizontal & vertical spacers but that isn't working? How to set QLabel a clickable (like hyperlink). I don't want to a open a URL. Just the text should be clickable. So, that when user clicks on the link. I can show more information (like next set of results when he clicks on next page number or a new window with image in fullsize when user clicks on 'view') Do we have some new kind of control for this? This is another important issue. I'll display the page numbers of results (like shown in figure) & assuming they are clickable. How do I load a new page of results? I mean what is the equivalent of page in QT? As you can guess. This definitely wont be the first page of GUI. The first page will be exactly like http://google.com (a big logo & text box with button below it). when user clicks the search button. This page will be displayed. Again the same question comes up. How change the pages? Please give a list of controls I'm going to need for this. Tell me if I'm unaware of something.
[ "1/2.\nFor displaying the images and labels use a QListWidget with view mode set to QListView::IconMode. However, if you need to customize the display beyond what the QListWidget/QListWidgetItem api can provide you will need to create your own QAbstractListModel and use a standard QListView with it.\nMake sure and ...
[ 14, 3 ]
[]
[]
[ "pyqt", "python", "qt", "qt4" ]
stackoverflow_0003157766_pyqt_python_qt_qt4.txt
Q: None value returned The code below is used in a function: def print_query(x): h = open('/home/rv/data.txt', 'r') read = h.readlines() for line in read: return line When the value "line" is retunred it should print but instead i get the value "None" A: Try this: with open('/home/rv/data.txt','r') as fh: for line in fh: print line If you're on Python 2.5 you might need a from __future__ import with_statement on top. Also: why do you return the line when you want to print it? A: You are not checking if the "read" variable actually contains any lines - if it does not, then the function will fall through the for loop and return None. Using the for loop is also silly - why would you read all lines, and only return the first one, especially in a for loop? What happens when the file can't be opened? A: I'm not sure why you're bothering with a loop in your function, since it's just going to return after the first iteration anyway. What exactly are you trying to accomplish? It seems like there is a deeper conceptual issue here, beyond the simple implementation issues. A: When you are writing: def f: return 1 return 2 the function returns 1. if you want to return few values you can return it in a list: def f: ans = [] ans.append(1) ans.append(2) return ans another option is to use "yield". google it when you will ready for it A: Another problem with the function is that you're iterating over the wrong object being more verbose than you need to be. To iterate over lines in a file, just do this: for line in open(file, "r"): print line
None value returned
The code below is used in a function: def print_query(x): h = open('/home/rv/data.txt', 'r') read = h.readlines() for line in read: return line When the value "line" is retunred it should print but instead i get the value "None"
[ "Try this:\nwith open('/home/rv/data.txt','r') as fh:\n for line in fh:\n print line\n\nIf you're on Python 2.5 you might need a from __future__ import with_statement on top.\nAlso: why do you return the line when you want to print it?\n", "You are not checking if the \"read\" variable actually contains...
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003160863_python.txt
Q: Accessing outer class methods from an inner class I want a python class that has a nested class where the inner class can access the members of the outer class. I understand that normal nesting doesn't even require that the outer class has an instance. I have some code that seems to generate the results I desire and I want feedback on style and unforeseen complications Code: class A(): def __init__(self,x): self.x = x self.B = self.classBdef() def classBdef(self): parent = self class B(): def out(self): print parent.x return B Output: >>> a = A(5) >>> b = a.B() >>> b.out() 5 >>> a.x = 7 >>> b.out() 7 So, A has an inner class B, which can only be created from an instance of A. Then B has access to all the members of A through the parent variable. A: This doesn't look very good to me. classBdef is a class factory method. Usually (and seldomly) you would use these to create custom classes e.g. a class with a custom super class: def class_factory(superclass): class CustomClass(superclass): def custom_method(self): pass return CustomClass But your construct doesn't make use of a customization. In fact it puts stuff of A into B and couples them tightly. If B needs to know about some A variable then make a method call with parameters or instantiate a B object with a reference to the A object. Unless there is a specific reason or problem you need to solve, it would be much easier and clearer to just make a normal factory method giving a B object in A instead of stuff like b = a.B(). class B(object): def __init__(self, a): self.a = a def out(self): print self.a.x class A(object): def __init__(self,x): self.x = x def create_b(self): return B(self) a = A() b = a.create_b() b.out() A: I don't think what you're trying to do is a very good idea. "Inner" classes in python have absolutely no special relationship with their "outer" class, if you bother to define one inside of another. It is exactly the same to say: class A(object): class B(object): pass as it is to say: class B(object): pass class A(object): pass A.B = B del B That said, it is possible to accomplish something like what you're describing, by making your "inner" class into a descriptor, by defining __get__() on its metaclass. I recommend against doing this -- it's too complicated and yields little benefit. class ParentBindingType(type): def __get__(cls, inst, instcls): return type(cls.__name__, (cls,), {'parent': inst}) def __repr__(cls): return "<class '%s.%s' parent=%r>" % (cls.__module__, cls.__name__, getattr(cls, 'parent', None)) class B(object): __metaclass__ = ParentBindingType def out(self): print self.parent.x class A(object): _B = B def __init__(self,x): self.x = x self.B = self._B a = A(5) print a.B b = a.B() b.out() a.x = 7 b.out() printing: <class '__main__.B' parent=<__main__.A object at 0x85c90>> 5 7
Accessing outer class methods from an inner class
I want a python class that has a nested class where the inner class can access the members of the outer class. I understand that normal nesting doesn't even require that the outer class has an instance. I have some code that seems to generate the results I desire and I want feedback on style and unforeseen complications Code: class A(): def __init__(self,x): self.x = x self.B = self.classBdef() def classBdef(self): parent = self class B(): def out(self): print parent.x return B Output: >>> a = A(5) >>> b = a.B() >>> b.out() 5 >>> a.x = 7 >>> b.out() 7 So, A has an inner class B, which can only be created from an instance of A. Then B has access to all the members of A through the parent variable.
[ "This doesn't look very good to me. classBdef is a class factory method. Usually (and seldomly) you would use these to create custom classes e.g. a class with a custom super class:\ndef class_factory(superclass):\n class CustomClass(superclass):\n def custom_method(self):\n pass\n return Cus...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003160809_python.txt
Q: Running Python scripts on a server? How would I run a python script on my site? I wrote a script that takes values (the values should come from a form that the end user fills out) and then returns a string. What would I need to add to the submit form to make the script run with the values? Is this possible or should I be using PHP? (The script involved web scraping, so I'm not sure if Python or PHP is better or what would allow for more flexibility) Thanks! A: Your site needs to allow python cgi scripting. See this for more info, especially this.
Running Python scripts on a server?
How would I run a python script on my site? I wrote a script that takes values (the values should come from a form that the end user fills out) and then returns a string. What would I need to add to the submit form to make the script run with the values? Is this possible or should I be using PHP? (The script involved web scraping, so I'm not sure if Python or PHP is better or what would allow for more flexibility) Thanks!
[ "Your site needs to allow python cgi scripting. \nSee this for more info, especially this.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003160906_python.txt
Q: String or list substitution in Python How would I go about taking a string: ("h1", "h2", "h3, "h4") And substituting these values with numbers 1, 2, 3, 4? Correspondingly, how I would I preform the same operation but on a list instead? A: to_replace = ["h1","h2","h3","h4"] replaced = [ int(s.replace("h","")) for s in to_replace ] If this is what you want. It's not exactly clear; I'm assuming that your input is not literally a string "(\"h1\", \"h2\", \"h3\", \"h4\")", but a list of strings. And I'm not sure what you meant by your second question, as it appears to be the same as the first. I will update my answer accordingly =) A: This would strip out every non-numeric character (not only h): >>> s = ["h1", "h2" , "h3" , "h4"] >>> [int(filter(lambda c: c.isdigit(), x)) for x in s] [1, 2, 3, 4] or >>> s = ["x1", "b2" , "c3" , "h4"] >>> [int(filter(lambda c: c.isdigit(), x)) for x in s] [1, 2, 3, 4]
String or list substitution in Python
How would I go about taking a string: ("h1", "h2", "h3, "h4") And substituting these values with numbers 1, 2, 3, 4? Correspondingly, how I would I preform the same operation but on a list instead?
[ " to_replace = [\"h1\",\"h2\",\"h3\",\"h4\"]\n replaced = [ int(s.replace(\"h\",\"\")) for s in to_replace ]\n\nIf this is what you want.\nIt's not exactly clear; I'm assuming that your input is not literally a string \"(\\\"h1\\\", \\\"h2\\\", \\\"h3\\\", \\\"h4\\\")\", but a list of strings.\nAnd I'm not sure wha...
[ 5, 3 ]
[]
[]
[ "list", "python", "string", "substitution" ]
stackoverflow_0003160791_list_python_string_substitution.txt
Q: Python threads in embedded Python: How? While experimenting with Python's (python.org) C API, I found myself wondering how to properly spawn threads via Python's threading package when Python itself is embedded in a C program. Functions PyEval_EvalCode and kin appear to terminate threads it "owns" as soon as the C function finishes evaluating a block of Python code. Roughly, running the following Python from C ... import threading, time class MyThread(threading.Thread): def __init__(self, num): self.num = num threading.Thread.__init__(self) def run(self): print "magic num = %d" % self.num for x in xrange(1000): MyThread(x).start() ... will stop entirely as soon as the for loop finishes and control is returned back out of the PyEval_EvalCode (or such) C function. We can observe this produces truncated output. I hypothesized this behavior after using the following tactic: We can dictate when control is returned, and therefore to a degree the output, by sleeping after spawning the slew of threads: for x in xrange(100): MyThread(x).start() # Don't leave just yet; let threads run for a bit time.sleep(5) # Adjust to taste I suspect a possible approach lies in creating a new system thread dedicated to embedding and running Python. After spawning Python threads, the Python code would sleep on a semaphore or something until it is told to shut down. The question would then be how can the thread be signaled for a tidy shutdown? Similarly, the "main" block can simply join() on all threads; the threads would then need to be signaled from C. Solutions greatly appreciated .. A: Have you included the pthread library? Python will fall back to dummy threads if it detects that real threads are not available
Python threads in embedded Python: How?
While experimenting with Python's (python.org) C API, I found myself wondering how to properly spawn threads via Python's threading package when Python itself is embedded in a C program. Functions PyEval_EvalCode and kin appear to terminate threads it "owns" as soon as the C function finishes evaluating a block of Python code. Roughly, running the following Python from C ... import threading, time class MyThread(threading.Thread): def __init__(self, num): self.num = num threading.Thread.__init__(self) def run(self): print "magic num = %d" % self.num for x in xrange(1000): MyThread(x).start() ... will stop entirely as soon as the for loop finishes and control is returned back out of the PyEval_EvalCode (or such) C function. We can observe this produces truncated output. I hypothesized this behavior after using the following tactic: We can dictate when control is returned, and therefore to a degree the output, by sleeping after spawning the slew of threads: for x in xrange(100): MyThread(x).start() # Don't leave just yet; let threads run for a bit time.sleep(5) # Adjust to taste I suspect a possible approach lies in creating a new system thread dedicated to embedding and running Python. After spawning Python threads, the Python code would sleep on a semaphore or something until it is told to shut down. The question would then be how can the thread be signaled for a tidy shutdown? Similarly, the "main" block can simply join() on all threads; the threads would then need to be signaled from C. Solutions greatly appreciated ..
[ "Have you included the pthread library? Python will fall back to dummy threads if it detects that real threads are not available\n" ]
[ 2 ]
[]
[]
[ "c", "embed", "multithreading", "python" ]
stackoverflow_0003159256_c_embed_multithreading_python.txt
Q: adding a trailing comma to a print command makes threads executions "serialized" without dumping tones of code here is the symptom having a threads which all run various methods of the same type of object. within the methods i have a print line which reads: print self.args, self.foo everything works just fine. However, if i turn that line into: # remain in the same line print self.args, self.foo, execution is done in a serialize way and it seems like that print statement blocks other threads from being executed until it finishes. import threading, time class Graph2(object): def __init__(self, instanceName): self.instanceName = instanceName def __getattr__(self, name): def foo(): for i in xrange(10): #### the tricky line #### # print i, self.instanceName print i, self.instanceName, time.sleep(1) return foo class GraphThread(threading.Thread): def __init__(self, graph, method, *args): threading.Thread.__init__(self) self.g, self.m, self.args = graph, method, args self.results = None def run(self): print 'm=%s, args=%s' % (self.m, self.args) self.results = getattr(self.g, self.m)(*self.args) print "...done running method %s, with args %s:"%(self.m,self.args) methods = ["degree","betweenness","closeness","cocitation","shell_index","evcent","eccentricity","constraint"] threads=[] # spawn a new thread for every requesting url for method in methods: print "starting thread for method %s..."%method t=GraphThread(Graph2(method),method) t.start() print "..appending thread..." threads.append(t) print "...thread appendd." A: Try flushing stdout after the print sys.stdout.flush()
adding a trailing comma to a print command makes threads executions "serialized"
without dumping tones of code here is the symptom having a threads which all run various methods of the same type of object. within the methods i have a print line which reads: print self.args, self.foo everything works just fine. However, if i turn that line into: # remain in the same line print self.args, self.foo, execution is done in a serialize way and it seems like that print statement blocks other threads from being executed until it finishes. import threading, time class Graph2(object): def __init__(self, instanceName): self.instanceName = instanceName def __getattr__(self, name): def foo(): for i in xrange(10): #### the tricky line #### # print i, self.instanceName print i, self.instanceName, time.sleep(1) return foo class GraphThread(threading.Thread): def __init__(self, graph, method, *args): threading.Thread.__init__(self) self.g, self.m, self.args = graph, method, args self.results = None def run(self): print 'm=%s, args=%s' % (self.m, self.args) self.results = getattr(self.g, self.m)(*self.args) print "...done running method %s, with args %s:"%(self.m,self.args) methods = ["degree","betweenness","closeness","cocitation","shell_index","evcent","eccentricity","constraint"] threads=[] # spawn a new thread for every requesting url for method in methods: print "starting thread for method %s..."%method t=GraphThread(Graph2(method),method) t.start() print "..appending thread..." threads.append(t) print "...thread appendd."
[ "Try flushing stdout after the print\nsys.stdout.flush()\n\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003161412_multithreading_python.txt
Q: Beginner needing experienced advice for important choices I've never written a program, (although I've dabbled in Access and am familiar with OOP concepts), and have decided to undertake the challenge of writing myself a database program for home use. (It'll keep track of our finances and be customized to our way of doing things.) I've pretty much decided to use Python and SQLite, but that still leaves other decisions to be made. I think I should get experienced advice and help choosing because I know nothing about the pros and cons (for my situation) of what's out there. I know I'll need reports of some kind (something similar to Access reports would be ideal). Also I'll need (the easiest way) to build a UI. What are some softwares that I (total beginner) should look at for those purposes? And are there other tools will I need besides those? Thanks a lot for your help. Update. Are there any drag and drop form and report development tools for Python/Sqlite (similar to Access)? What about opinions on Netbeans IDE and Swing UI for me? A: Tkinter is a *great** UI framework for beginners. I highly recommend using that, if it seems powerful enough to fill your needs. Since it sounds like you're pretty inexperienced as far as programming goes, here's what I recommend: 1) Learn how to do basic IO, and especially learn Python's string formatting. It's super useful, and probably invaluable in your situation. 2) Learn how to do SQL queries with SQLite - attach your Python IO skills to SQLite. 3) Learn Python's object model - how it fits within the concept of OOP, and especially how you can make an object to fit your data model. Learn how this can work in between Python's IO and SQLite IO. 4) Now that you're comfortable putting data into and getting data out of a SQLite database and a user, and can handle objects comfortably, it's time to start learning about event driven programming, mainloops, and GUI layouts. Tkinter is pretty simple and Effbot has some rather good information about Tkinter. 5) Tie all of these skills and knowledge together and make yourself a program. You'll probably have to go back and brush up, relearn, or learn some new things about 1-4 all along the way. Don't be afraid to re-factor code - if it seems like something is a pain to work with/around, you're probably doing something wrong, or just not seeing a solution right in front of your face. In some cases it's ignorance, in others you've just been looking at your program too long and may be married to the idea of doing it the "wrong" way. If your solution isn't simple, then you may be complicating the problem. 6) Ask for help. If you get stuck, you can always ask here, or at the python tutor mailing list . Just tell/show what you've done, what you expect to happen, and what it does instead. Most pythonistas tend to be a rather helpful bunch, and even more so when you show you've been trying to work at it yourself. Anyhow, HTH, and good programming! *by great I mean it has good features, but it's not very pretty or overly complicated. Plus it comes standard with your Python install. For instance, a simple tkinter program with a label and a button could look like this: import Tkinter as tk # Initialize a new root window root = tk.Tk() # Create a label that belongs to the root window hello = tk.Label(root, text='Hello') # Create a button that belongs to root, and will make the program # quit when pressed goodbye = tk.Button(root, text='Goodbye', command=root.quit) # Use the pack manager to add the button and label to the root # Window - do NOT mix pack and grid managers - they don't play well hello.pack() goodbye.pack() # Enter the mainloop root.mainloop() A: One advice if you've never done any programming before is: small steps. Write a small program that extracts things from a SQLite database and just prints them. Learn how that works and throw it away. Do the same with reading files, make a simple GUI and so on with all the aspects you need to know for your program. Once you know the pieces, try putting them together.
Beginner needing experienced advice for important choices
I've never written a program, (although I've dabbled in Access and am familiar with OOP concepts), and have decided to undertake the challenge of writing myself a database program for home use. (It'll keep track of our finances and be customized to our way of doing things.) I've pretty much decided to use Python and SQLite, but that still leaves other decisions to be made. I think I should get experienced advice and help choosing because I know nothing about the pros and cons (for my situation) of what's out there. I know I'll need reports of some kind (something similar to Access reports would be ideal). Also I'll need (the easiest way) to build a UI. What are some softwares that I (total beginner) should look at for those purposes? And are there other tools will I need besides those? Thanks a lot for your help. Update. Are there any drag and drop form and report development tools for Python/Sqlite (similar to Access)? What about opinions on Netbeans IDE and Swing UI for me?
[ "Tkinter is a *great** UI framework for beginners. I highly recommend using that, if it seems powerful enough to fill your needs.\nSince it sounds like you're pretty inexperienced as far as programming goes, here's what I recommend:\n1) Learn how to do basic IO, and especially learn Python's string formatting. It's...
[ 6, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003159878_python.txt
Q: How to model this in django (inherited model, where each inherited model has a unique method) How to model this in django: 1) have a base network of manufacturers 2) under each network their might be several distributors 3) a user of the system can access items through the distributor 4) if a user access the item through the distributor we want that item to be translated where each manufacturer will have their own translation class Manufacturer(models.Model): networkname = models.CharField(max_length=128) class Meta: proxy = True class Distributor(models.Model): man = models.ForeignKey(Manufacturer) class ManuType1(Manufacturer): def translate(self, str): return 'translate' class ManuType2(Manufacturer): def translate(self, str): return 'translate' In this scenario we will get a request for a certain Distributor. We identify that distributor and we want to call that distributors manufacturers translate method. Does this look like a way to model this in django (I'm sure there are many ways to do this) so any input/feedback is useful. Where I run into problems (not knowing python well enough perhaps) is given a Distributor with ManuType1 How do I call the translate function at runtime? This is probably a well explored pattern using other terms, just not sure how to express it exactly. A: If dist is an instance of Distributor, then you can do dist.man to get the Manufacturer instance. Due to the way multi-table inheritance works in Django, you'll need to access the OneToOneField that exists on the Manufacturer to the subclass instance. The problem lies in figuring out which subclass instance exists. This can be made easier by storing the ContentType of the subclass in the Manufacturer instance.
How to model this in django (inherited model, where each inherited model has a unique method)
How to model this in django: 1) have a base network of manufacturers 2) under each network their might be several distributors 3) a user of the system can access items through the distributor 4) if a user access the item through the distributor we want that item to be translated where each manufacturer will have their own translation class Manufacturer(models.Model): networkname = models.CharField(max_length=128) class Meta: proxy = True class Distributor(models.Model): man = models.ForeignKey(Manufacturer) class ManuType1(Manufacturer): def translate(self, str): return 'translate' class ManuType2(Manufacturer): def translate(self, str): return 'translate' In this scenario we will get a request for a certain Distributor. We identify that distributor and we want to call that distributors manufacturers translate method. Does this look like a way to model this in django (I'm sure there are many ways to do this) so any input/feedback is useful. Where I run into problems (not knowing python well enough perhaps) is given a Distributor with ManuType1 How do I call the translate function at runtime? This is probably a well explored pattern using other terms, just not sure how to express it exactly.
[ "If dist is an instance of Distributor, then you can do dist.man to get the Manufacturer instance. Due to the way multi-table inheritance works in Django, you'll need to access the OneToOneField that exists on the Manufacturer to the subclass instance. The problem lies in figuring out which subclass instance exists...
[ 0 ]
[]
[]
[ "django", "inheritance", "model", "proxy", "python" ]
stackoverflow_0003160762_django_inheritance_model_proxy_python.txt
Q: Retain formatting Im using a function to return a text file that is tab delimited and read in, the format of the text file is: 1_0 NP_250397 100.00 140 0 0 1 140 1 140 6e-54 198 1_0 NP_250378 60.00 140 0 0 1 140 1 140 6e-54 198 1_0 NP_257777 70.00 140 0 0 1 140 1 140 6e-54 198 My code used to return is: def print_file(x): h = open('/home/me/data/db/test.blast', 'r') return h.readlines() But when its printed it looks like: ['1_0\tNP_250397\t100.00\t140\t0\t0\t1\t140\t1\t140\t6e-54\t 198\n', '1_0\tNP_250397\t100.00\t140\t0\t0\t1\t140\t1\t140\t6e-54\t 198\n', '1_0\tNP_250397\t100.00\t140\t0\t0\t1\t140\t1\t140\t6e-54\t 198\n'] Is there a way of returning the file, while aslo retaining formatting? A: If you want print_file to actually print the file as the function name suggests def print_file(x): with open('/home/me/data/db/test.blast', 'r') as h: for line in h: print line If you want to return the contents of the file as a single string def print_file(x): with open('/home/me/data/db/test.blast', 'r') as h: return h.read() If your Python is too old to use the with statement def print_file(x): return open('/home/me/data/db/test.blast', 'r').read() Aside: You may be interested to know that the csv module can work with tab delimited files too A: return h.read() would return the file's contents as a single string, and therefore "retain formatting" if that's printed, as you put it. What other constraints do you have on the return value of the peculiarly-named print_file (peculiarly indeed because it doesn't print anything!)...? A: When you print out a list, Python prints the list in a kind of raw format that represents how it's stored internally. If you want to eliminate the brackets and commas and quotes and want the tabs expanded, you must print out each string individually. for line in print_file(x): print line And could you please pick a more appropriate name for print_file, since it isn't really printing anything? It's adding a bit of cognitive dissonance that isn't helping your problem.
Retain formatting
Im using a function to return a text file that is tab delimited and read in, the format of the text file is: 1_0 NP_250397 100.00 140 0 0 1 140 1 140 6e-54 198 1_0 NP_250378 60.00 140 0 0 1 140 1 140 6e-54 198 1_0 NP_257777 70.00 140 0 0 1 140 1 140 6e-54 198 My code used to return is: def print_file(x): h = open('/home/me/data/db/test.blast', 'r') return h.readlines() But when its printed it looks like: ['1_0\tNP_250397\t100.00\t140\t0\t0\t1\t140\t1\t140\t6e-54\t 198\n', '1_0\tNP_250397\t100.00\t140\t0\t0\t1\t140\t1\t140\t6e-54\t 198\n', '1_0\tNP_250397\t100.00\t140\t0\t0\t1\t140\t1\t140\t6e-54\t 198\n'] Is there a way of returning the file, while aslo retaining formatting?
[ "If you want print_file to actually print the file as the function name suggests\ndef print_file(x):\n with open('/home/me/data/db/test.blast', 'r') as h:\n for line in h:\n print line\n\nIf you want to return the contents of the file as a single string\ndef print_file(x):\n with open('/home...
[ 2, 0, 0 ]
[]
[]
[ "formatting", "python" ]
stackoverflow_0003161413_formatting_python.txt
Q: How do i print the script line number in IronPython? I am running an IronPython script inside a c# application, i am catching exceptions within the script and i wish to find out the script line at which the exception is thrown. This has to be done while the script is running ie. i do not wish the script to terminate in order to print the exception. Is this even possible? A: If inspect is working as expected under IronPython (not really sure) this could do the trick: import inspect filename, linenum, funcname = inspect.getframeinfo(inspect.currentframe())[:3] print linenum Edit: alternate solution: import sys frame = sys._getframe() print frame.f_lineno A: Haven't tried this on ironpython but: import traceback try: # something that raises exception except YourException, _: traceback.print_exc() This should show you the stack trace of the place where the exception was raised. You can also do other stuff than just print, like print to string, or get the stack frames. The traceback module documentation will tell you more.
How do i print the script line number in IronPython?
I am running an IronPython script inside a c# application, i am catching exceptions within the script and i wish to find out the script line at which the exception is thrown. This has to be done while the script is running ie. i do not wish the script to terminate in order to print the exception. Is this even possible?
[ "If inspect is working as expected under IronPython (not really sure) this could do the trick:\nimport inspect\n\nfilename, linenum, funcname = inspect.getframeinfo(inspect.currentframe())[:3]\nprint linenum\n\nEdit: alternate solution:\nimport sys\n\nframe = sys._getframe()\nprint frame.f_lineno\n\n", "Haven't t...
[ 1, 0 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0003161177_ironpython_python.txt
Q: What am I doing wrong? Python object instantiation keeping data from previous instantiation? Can someone point out to me what I'm doing wrong or where my understanding is wrong? To me, it seems like the code below which instantiates two objects should have separate data for each instantiation. class Node: def __init__(self, data = []): self.data = data def main(): a = Node() a.data.append('a-data') #only append data to the a instance b = Node() #shouldn't this be empty? #a data is as expected print('number of items in a:', len(a.data)) for item in a.data: print(item) #b data includes the data from a print('number of items in b:', len(b.data)) for item in b.data: print(item) if __name__ == '__main__': main() However, the second object is created with the data from the first: >>> number of items in a: 1 a-data number of items in b: 1 a-data A: You can't use an mutable object as a default value. All objects will share the same mutable object. Do this. class Node: def __init__(self, data = None): self.data = data if data is not None else [] When you create the class definition, it creates the [] list object. Every time you create an instance of the class it uses the same list object as a default value. A: The problem is in this line: def __init__(self, data = []): When you write data = [] to set an empty list as the default value for that argument, Python only creates a list once and uses the same list for every time the method is called without an explicit data argument. In your case, that happens in the creation of both a and b, since you don't give an explicit list to either constructor, so both a and b are using the same object as their data list. Any changes you make to one will be reflected in the other. To fix this, I'd suggest replacing the first line of the constructor with def __init__(self, data=None): if data is None: data = [] A: When providing default values for a function or method, you generally want to provide immutable objects. If you provide an empty list or an empty dictionary, you'll end up with all calls to that function or method sharing the object. A good workaround is: def __init__(self, data = None): if data == None: self.data = [] else: self.data = data
What am I doing wrong? Python object instantiation keeping data from previous instantiation?
Can someone point out to me what I'm doing wrong or where my understanding is wrong? To me, it seems like the code below which instantiates two objects should have separate data for each instantiation. class Node: def __init__(self, data = []): self.data = data def main(): a = Node() a.data.append('a-data') #only append data to the a instance b = Node() #shouldn't this be empty? #a data is as expected print('number of items in a:', len(a.data)) for item in a.data: print(item) #b data includes the data from a print('number of items in b:', len(b.data)) for item in b.data: print(item) if __name__ == '__main__': main() However, the second object is created with the data from the first: >>> number of items in a: 1 a-data number of items in b: 1 a-data
[ "You can't use an mutable object as a default value. All objects will share the same mutable object.\nDo this.\nclass Node:\n def __init__(self, data = None):\n self.data = data if data is not None else []\n\nWhen you create the class definition, it creates the [] list object. Every time you create an i...
[ 16, 6, 3 ]
[]
[]
[ "instantiation", "python" ]
stackoverflow_0003161827_instantiation_python.txt
Q: How can I access another server with Python? I have two servers, and one updates with a DNSBL of 100k domains every 15 minutes. I want to process these domains through a Python script with information from Safebrowsing, Siteadvisor, and other services. Unfortunately, the server with the DNSBL is rather slow. Is there a way I can transfer the files over from the other server with SSH in Python? A: If it's just files (and directories) you are transferring, why not just use rsync over ssh (in a bash script perhaps). A proven, mature method. Or you could mount the remote filesystem (over ssh) into your own filesystem using sshfs (fuse) and then use something like pyrobocopy (implementing a basic version of rsync functionality in Python) to transfer the files. If you don't need incremental copying, you could go the simple route: mount the remote filesystem using sshfs (link above) and then use shutil.copytree to copy the correct directory. Or yet another option: implement it using the paramiko Python ssh module. A: There is a module called pexpect which is pretty nice. This allows you to ssh, telnet, etc. It also supports ftp which might be handy in transferring files.
How can I access another server with Python?
I have two servers, and one updates with a DNSBL of 100k domains every 15 minutes. I want to process these domains through a Python script with information from Safebrowsing, Siteadvisor, and other services. Unfortunately, the server with the DNSBL is rather slow. Is there a way I can transfer the files over from the other server with SSH in Python?
[ "If it's just files (and directories) you are transferring, why not just use rsync over ssh (in a bash script perhaps). A proven, mature method.\nOr you could mount the remote filesystem (over ssh) into your own filesystem using sshfs (fuse) and then use something like pyrobocopy (implementing a basic version of rs...
[ 0, 0 ]
[]
[]
[ "python", "ssh" ]
stackoverflow_0003161884_python_ssh.txt
Q: How can I fix this bug? BadKeyError: Name must be string type Hey everyone. I am using Appengine/Python and I haven't been able to fix a BadKeyError bug for the last 5 hours. I'm wondering if someone can help me figure it out. The part of the app that is causing the bug is a controller that processes votes done by users. Actor_id is the key of the user and object_id is the key of the object that is being voted on. I've been testing the app by hiding and restoring some code, and I know for sure that the keys being received are good (first block), and that the entities are being created (second block). What does not work is creating an activity instance - raises BadKeyError (third block) I've added the controller code, the model code, and the traceback of the error from the log page. # Controller Code class ActivityHandler(FacebookEnabled): def get(self): # i.e. fbid / headline id / upvote. This works actor_id = self.request.get('actor_id') object_id = self.request.get('object_id') # creating actor and object from keys (actor_id and object_id). # This works. actor = models.Person.get(actor_id) object = models.Headline.get(object_id) logging.info("Actor " + str(actor) +": " + str(actor.name) + " object " + str(object) + ": " + str(object.title)) # THIS IS WHAT SEEMS TO RAISE AN EXCEPTION activity = models.Activity(actor, object, action='upvote') activity.put() # Model Code class Activity(polymodel.PolyModel): # User causing the action i.e. a person actor = db.ReferenceProperty(Person, required=True, collection_name='actors') # The object being the subject of the action i.e. headline object = db.ReferenceProperty(Headline, required=True, collection_name='objects') # The action being made action = db.StringProperty(required=True, choices=['upvote','downvote'], default='upvote') Traceback Name must be string type, not Headline Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/webapp/__init__.py", line 511, in __call__ handler.get(*groups) File "/base/data/home/apps/libnentest/2.343063076026692316/main.py", line 125, in get activity = models.Activity(actor, object, action='upvote') File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 726, in __init__ key_name.__class__.__name__) BadKeyError: Name must be string type, not Headline A: object is always a poor choice of name and could well be causing the exception. A: The constructor for PolyModel is like so: class PolyModel(parent=None, key_name=None, **kwds): So you're passing in the headline object as the key_name, which looks like it must be a string from the stacktrace. From reading through the docs I think what you want to do is this: activity_kwargs = { 'actor' : actor, 'object' : object', 'action' : 'upvote', } activity = models.Activity(**activity_kwargs) activity.put() On a side note: Don't use object as a variable name, since it's a built-in keyword.
How can I fix this bug? BadKeyError: Name must be string type
Hey everyone. I am using Appengine/Python and I haven't been able to fix a BadKeyError bug for the last 5 hours. I'm wondering if someone can help me figure it out. The part of the app that is causing the bug is a controller that processes votes done by users. Actor_id is the key of the user and object_id is the key of the object that is being voted on. I've been testing the app by hiding and restoring some code, and I know for sure that the keys being received are good (first block), and that the entities are being created (second block). What does not work is creating an activity instance - raises BadKeyError (third block) I've added the controller code, the model code, and the traceback of the error from the log page. # Controller Code class ActivityHandler(FacebookEnabled): def get(self): # i.e. fbid / headline id / upvote. This works actor_id = self.request.get('actor_id') object_id = self.request.get('object_id') # creating actor and object from keys (actor_id and object_id). # This works. actor = models.Person.get(actor_id) object = models.Headline.get(object_id) logging.info("Actor " + str(actor) +": " + str(actor.name) + " object " + str(object) + ": " + str(object.title)) # THIS IS WHAT SEEMS TO RAISE AN EXCEPTION activity = models.Activity(actor, object, action='upvote') activity.put() # Model Code class Activity(polymodel.PolyModel): # User causing the action i.e. a person actor = db.ReferenceProperty(Person, required=True, collection_name='actors') # The object being the subject of the action i.e. headline object = db.ReferenceProperty(Headline, required=True, collection_name='objects') # The action being made action = db.StringProperty(required=True, choices=['upvote','downvote'], default='upvote') Traceback Name must be string type, not Headline Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/webapp/__init__.py", line 511, in __call__ handler.get(*groups) File "/base/data/home/apps/libnentest/2.343063076026692316/main.py", line 125, in get activity = models.Activity(actor, object, action='upvote') File "/base/python_runtime/python_lib/versions/1/google/appengine/ ext/db/__init__.py", line 726, in __init__ key_name.__class__.__name__) BadKeyError: Name must be string type, not Headline
[ "object is always a poor choice of name and could well be causing the exception.\n", "The constructor for PolyModel is like so: class PolyModel(parent=None, key_name=None, **kwds): So you're passing in the headline object as the key_name, which looks like it must be a string from the stacktrace.\nFrom reading th...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003161919_google_app_engine_python.txt
Q: PyQt4 dropdownlist with actions I want to create a drop down list in PyQt4, that executes an action when an element is selected. Also, some options may not be available at some time. They should still be in the list, but greyed out. I tried attaching a menu to a QToolButton, but I can not even see the menu. How is it done? Thanks! Nathan A: Use a popup. You can trigger a popup anywhere, using the QMenu.exec_ method and passing the point at which you want the menu to appear. I created a button that remembered where it was clicked, and connected that to the method to create and display the popup. class MemoryButton(QPushButton): def __init__(self, *args, **kw): QPushButton.__init__(self, *args, **kw) self.last_mouse_pos = None def mousePressEvent(self, event): self.last_mouse_pos = event.pos() QPushButton.mousePressEvent(self, event) def mouseReleaseEvent(self, event): self.last_mouse_pos = event.pos() QPushButton.mouseReleaseEvent(self, event) def get_last_pos(self): if self.last_mouse_pos: return self.mapToGlobal(self.last_mouse_pos) else: return None button = MemoryButton("Click Me!") def popup_menu(): popup = QMenu() menu = popup.addMenu("Do Action") def _action(check): print "Action Clicked!" menu.addAction("Action").triggered.connect(_action) popup.exec_(button.get_last_pos()) button.clicked.connect(popup_menu) A: QToolButton has ToolButtonPopupMode enum that controls how it handles menus and multiple actions. When set to QToolButton::MenuButtonPopup, it will display the arrow that is typical of buttons that have menu options. To use it set the appropriate popup mode and then you can either add a menu to the QToolButton using setMenu or you can add actions using addAction. QToolButton should then respond as expected to clicks on the menu, whether Action generated or an actual QMenu.
PyQt4 dropdownlist with actions
I want to create a drop down list in PyQt4, that executes an action when an element is selected. Also, some options may not be available at some time. They should still be in the list, but greyed out. I tried attaching a menu to a QToolButton, but I can not even see the menu. How is it done? Thanks! Nathan
[ "Use a popup. You can trigger a popup anywhere, using the QMenu.exec_ method and passing the point at which you want the menu to appear.\nI created a button that remembered where it was clicked, and connected that to the method to create and display the popup.\nclass MemoryButton(QPushButton):\n def __init__(se...
[ 2, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0003161519_pyqt4_python.txt
Q: Python encoding function can't be decoded I wrote this python code in an attempt to convert objects to a string of ones and zeros, but the decoding fails because the data can't be unpickled. This is the code: def encode(obj): 'convert an object to ones and zeros' def tobin(str): rstr = '' for f in str: if f == "0": rstr += "0000" elif f == "1": rstr += "0001" elif f == "2": rstr += "0010" elif f == "3": rstr += "0100" elif f == "4": rstr += "1000" elif f == "5": rstr += "1001" elif f == "6": rstr += "1010" elif f == "7": rstr += "1100" elif f == "8": rstr += "1101" elif f == "9": rstr += "1110" else: rstr += f return rstr import pickle, StringIO f = StringIO.StringIO() pickle.dump(obj, f) data = f.getvalue() import base64 return tobin(base64.b16encode(base64.b16encode(data))) def decode(data): def unbin(data): rstr = '' for f in data: if f == "0000": rstr += "0" elif f == "0001": rstr += "1" elif f == "0010": rstr += "2" elif f == "0100": rstr += "3" elif f == "1000": rstr += "4" elif f == "1001": rstr += "5" elif f == "1010": rstr += "6" elif f == "1100": rstr += "7" elif f == "1101": rstr += "8" elif f == "1110": rstr += "9" return rstr import base64 ndata = base64.b16decode(base64.b16decode(unbin(data))) import pickle, StringIO f = StringIO.StringIO(ndata) obj = pickle.load(f) return obj A: I think there are several problems, but one is that when you decode, you need to iterate through groups of 4 characters in you unbin() function, not single characters like you are currently doing. A: I think I have a better solution for you. This should be even more secure, since it "encrypts" everything, not just numbers: MAGIC = 0x15 # CHOOSE ANY TWO HEX DIGITS YOU LIKE # THANKS TO NAS BANOV FOR THE FOLLOWING: unbin = tobin = lambda s: ''.join(chr(ord(c) ^ MAGIC) for c in s) A: Your bin and unbin functions aren't inverses of each other, because bin has an else clause that just puts the characters verbatim into the output, but unbin has no else clause to pass them back. A: By the way... base64.b16encode(base64.b16encode(data)) is equivalent to data.encode('hex').encode('hex'). And there is simpler and faster way to do the mapping, def tobin(numStr): return ''.join(("0000","0001","0010","0100","1000","1001","1010","1100","1101","1110")[int(c)] for c in numStr) The whole idea of this encoding, while seeming complicated on the surface, is not very good. First, it does not do much of encryption, since each digit from the hex dump gets matched always to the same 8-length string of 0 and 1s: >>> hexd = '0123456789ABCDEF' >>> s = hexd.encode('hex') >>> s '30313233343536373839414243444546' >>> s=''.join(["0000","0001","0010","0100","1000","1001","1010","1100","1101","1110"][int(c)] for c in s) >>> s '01000000010000010100001001000100010010000100100101001010010011000100110101001110100000011000001010000100100010001000100110001010' >>> for i in range(0,len(s),8): ... print hexd[i/8], s[i:i+8], chr(int(s[i:i+8],2)) ... 0 01000000 @ 1 01000001 A 2 01000010 B 3 01000100 D 4 01001000 H 5 01001001 I 6 01001010 J 7 01001100 L 8 01001101 M 9 01001110 N A 10000001 B 10000010 ‚ C 10000100 „ D 10001000 ˆ E 10001001 ‰ F 10001010 Š Secondly, it blows up the size of the pickled object 16 times! Even if you pack this by converting every 8 bits of '0' and '1' to bytes (say chr(int(encoded[i:i+8],2))), that still is 2x the pickle.
Python encoding function can't be decoded
I wrote this python code in an attempt to convert objects to a string of ones and zeros, but the decoding fails because the data can't be unpickled. This is the code: def encode(obj): 'convert an object to ones and zeros' def tobin(str): rstr = '' for f in str: if f == "0": rstr += "0000" elif f == "1": rstr += "0001" elif f == "2": rstr += "0010" elif f == "3": rstr += "0100" elif f == "4": rstr += "1000" elif f == "5": rstr += "1001" elif f == "6": rstr += "1010" elif f == "7": rstr += "1100" elif f == "8": rstr += "1101" elif f == "9": rstr += "1110" else: rstr += f return rstr import pickle, StringIO f = StringIO.StringIO() pickle.dump(obj, f) data = f.getvalue() import base64 return tobin(base64.b16encode(base64.b16encode(data))) def decode(data): def unbin(data): rstr = '' for f in data: if f == "0000": rstr += "0" elif f == "0001": rstr += "1" elif f == "0010": rstr += "2" elif f == "0100": rstr += "3" elif f == "1000": rstr += "4" elif f == "1001": rstr += "5" elif f == "1010": rstr += "6" elif f == "1100": rstr += "7" elif f == "1101": rstr += "8" elif f == "1110": rstr += "9" return rstr import base64 ndata = base64.b16decode(base64.b16decode(unbin(data))) import pickle, StringIO f = StringIO.StringIO(ndata) obj = pickle.load(f) return obj
[ "I think there are several problems, but one is that when you decode, you need to iterate through groups of 4 characters in you unbin() function, not single characters like you are currently doing.\n", "I think I have a better solution for you. This should be even more secure, since it \"encrypts\" everything, no...
[ 2, 1, 0, 0 ]
[]
[]
[ "decoding", "encoding", "pickle", "python" ]
stackoverflow_0003160919_decoding_encoding_pickle_python.txt
Q: Python's subprocess module returning different results from Unix shell I'm trying to get a list of the CSV files in a directory with python. This is really easy within unix: ls -l *.csv And, predictably, I get a list of the files that end with .csv in my directory. However, when I attempt the Python equivalent using the Subprocess module: >>> import subprocess as sp >>> sp.Popen(["ls", "-l", "*.csv"], stdout = sp.PIPE) <subprocess.Popen object at 0xb780e90c> >>> ls: cannot access *.csv: No such file or directory Can somebody please explain what's going on? Edit: Adding shell = True removes the error, but instead of getting a list of just CSV files, I get a list of all the files in the directory. A: If you want it to behave as it does at the shell, you need to pass shell=True (your mileage may vary here, depending on your system and shell). In your case the problem is that when you do ls -l *.csv, the shell is evaluating what * means, not ls. (ls is merely formatting your results, but the shell has done the heavy lifting to determine what files match *.csv). Subprocess makes ls treat *.csv literally, and look for a file with that specific name, which of course there aren't any (since that's a pretty hard filename to create). What you really should be doing is using os.listdir and filtering the names yourself. A: Why not use glob instead? It's going to be faster than "shelling out"! import glob glob.glob('*.csv') This gives you just the names, not all the extra info ls -l supplies, though you can get extra info with os.stat calls on files of interest. If you really must use ls -l, I think you want to pass it as a string for the shell to do the needed star-expansion: proc = sp.Popen('ls -l *.csv', shell=True, stdout=sp.PIPE) A: When you enter ls -l *.csv at the shell, the shell itself expands *.csv into a list of all the filenames it matches. So the arguments to ls will actually be something more like ls -l spam.txt eggs.txt ham.py The ls command doesn't understand wildcards itself. So when you pass the argument *.csv to it it tries to treat it as a filename, and there is no file with that name. As Nick says, you can use the shell=True parameter to have Python invoke a shell to run the subprocess, and the shell will expand the wildcards for you. A: p=subprocess.Popen(["ls", "-l", "*.out"], stdout = subprocess.PIPE, shell=True) causes /bin/sh -c ls -l *.out to be executed. If you try this command in a directory, you'll see -- in typical mystifying-shell fashion -- all files are listed. And the -l flag is ignored as well. That's a clue. You see, the -c flag is picking up only the ls. The rest of the arguments are being eaten up by /bin/sh, not by ls. To get this command to work right at the terminal, you have to type /bin/sh -c "ls -l *.out" Now /bin/sh sees the full command "ls -l *.out" as the argument to the -c flag. So to get this to work out right using subprocess.Popen, you are best off just passing the command as a single string p=subprocess.Popen("ls -l *.out", stdout = subprocess.PIPE, shell=True) output,error=p.communicate() print(output)
Python's subprocess module returning different results from Unix shell
I'm trying to get a list of the CSV files in a directory with python. This is really easy within unix: ls -l *.csv And, predictably, I get a list of the files that end with .csv in my directory. However, when I attempt the Python equivalent using the Subprocess module: >>> import subprocess as sp >>> sp.Popen(["ls", "-l", "*.csv"], stdout = sp.PIPE) <subprocess.Popen object at 0xb780e90c> >>> ls: cannot access *.csv: No such file or directory Can somebody please explain what's going on? Edit: Adding shell = True removes the error, but instead of getting a list of just CSV files, I get a list of all the files in the directory.
[ "If you want it to behave as it does at the shell, you need to pass shell=True (your mileage may vary here, depending on your system and shell). In your case the problem is that when you do ls -l *.csv, the shell is evaluating what * means, not ls. (ls is merely formatting your results, but the shell has done the ...
[ 4, 4, 1, 1 ]
[]
[]
[ "python", "unix" ]
stackoverflow_0003162153_python_unix.txt
Q: Add headers to a file I have a file containing data like below: 88_NPDJ 565 789 3434 54454 98HGJDN 945 453 3453 23423 ... ... ... whats the best way to add headers to the file? After data has been entered into the file. The data is tab delimited. A: Best way to get the effect of altering a file in place is with fileinput: import fileinput headers = 'a b c d e'.split() for line in fileinput.input(['thefile.blah'], inplace=True): if fileinput.isfirstline(): print '\t'.join(headers) print line, A: Which kind of headers? Something like: type A Type B Type C Type D Type E 88_NPDJ 565 789 3434 54454 98HGJDN 945 453 3453 23423 ... ... ... Isn't it? You can open a temporary file, write the headers and then append the rest of the file to your temporary file. Delete the original file and rename the temp. like the original. import os headers = ['type 1', 'type 2', 'insert more types'] filename = 'your/file/here' tmp = open('TMP', 'w') orig = open(filename, 'r') tmp.write('\t'.join(headers) + '\n') for line in orig.readlines(): tmp.write(line) orig.close() tmp.close() os.remove(filename) os.rename('TMP', filename) A: I am assuming that you already know what the headers are and you just want a way to programmatically insert them at the top of the file. One way is to read the file into memory, truncate it, write the headers then write back the contents of the file. This might not work so well if the file is huge. If that could be the case, then you could write the header to a new file, then read each line from the original file and append it to the new file, then finally rename the new file so that it replaces the old file.
Add headers to a file
I have a file containing data like below: 88_NPDJ 565 789 3434 54454 98HGJDN 945 453 3453 23423 ... ... ... whats the best way to add headers to the file? After data has been entered into the file. The data is tab delimited.
[ "Best way to get the effect of altering a file in place is with fileinput:\nimport fileinput\n\nheaders = 'a b c d e'.split()\nfor line in fileinput.input(['thefile.blah'], inplace=True):\n if fileinput.isfirstline():\n print '\\t'.join(headers)\n print line,\n\n", "Which kind of headers? Something l...
[ 9, 1, 0 ]
[]
[]
[ "file_io", "header", "python" ]
stackoverflow_0003162314_file_io_header_python.txt
Q: Python binary file reading problem I'm trying to read a binary file (which represents a matrix in Matlab) in Python. But I am having trouble reading the file and converting the bytes to the correct values. The binary file consists of a sequence of 4-byte numbers. The first two numbers are the number of rows and columns respectively. My friend gave me a Matlab function he wrote that does this using fwrite. I would like to do something like this: f = open(filename, 'rb') rows = f.read(4) cols = f.read(4) m = [[0 for c in cols] for r in rows] r = c = 0 while True: if c == cols: r += 1 c = 0 num = f.read(4) if num: m[r][c] = num c += 1 else: break But whenever I use f.read(4), I get something like '\x00\x00\x00\x04' (this specific example should represent a 4), and I can't figure out convert it into the correct number (using int, hex or anything like that doesn't work). I stumbled upon struct.unpack, but that didn't seem to help very much. Here is an example matrix and the corresponding binary file (as it appears when I read the entire file using the python function f.read() without any size paramater) that the Matlab function created for it: 4 4 2 4 2 2 2 1 3 3 2 4 2 2 6 2 '\x00\x00\x00\x04\x00\x00\x00\x04@\x80\x00\x00@\x00\x00\x00@@\x00\x00@\x00\x00\x00@\x80\x00\x00@\x00\x00\x00@@\x00\x00@\x00\x00\x00@\x00\x00\x00@\x00\x00\x00@\x00\x00\x00@\xc0\x00\x00@\x80\x00\x00?\x80\x00\x00@\x80\x00\x00@\x00\x00\x00' So the first 4 bytes and the 5th-8th bytes should both be 4, as the matrix is 4x4. and then it should be 4,4,2,4,2,2,2,1,etc... Thanks guys! A: rows = f.read(4) cols = f.read(4) both names are now bound to 4-byte strings. To turn them into integers instead, import struct rowsandcols = f.read(8) rows, cols = struct.unpack('=ii', rowsandcols) See the docs for struct.unpack. A: I looked a bit more in your problem, since I had never used struct before so it was good learning activity. Turns out there are couple of twists there - first the numbers are not stored as 4-byte integers but as 4-byte float in big-endian form. Second, if your example is correct, then the matrix was not stored as one would expect - by rows, but by columns instead. E.g. it was output like so (pseudocode): for j in cols: for i in rows: write Aij to file So I had to transpose the result after reading. Here is the code that you need given the example: import struct def readMatrix(f): rows, cols = struct.unpack('>ii',f.read(8)) m = [ list(struct.unpack('>%df' % rows, f.read(4*rows))) for c in range(cols) ] # transpose result to return return zip(*m) And here we test it: >>> from StringIO import StringIO >>> f = StringIO('\x00\x00\x00\x04\x00\x00\x00\x04@\x80\x00\x00@\x00\x00\x00@@\x00\x00@\x00\x00\x00@\x80\x00\x00@\x00\x00\x00@@\x00\x00@\x00\x00\x00@\x00\x00\x00@\x00\x00\x00@\x00\x00\x00@\xc0\x00\x00@\x80\x00\x00?\x80\x00\x00@\x80\x00\x00@\x00\x00\x00') >>> mat = readMatrix(f) >>> for row in mat: ... print row ... (4.0, 4.0, 2.0, 4.0) (2.0, 2.0, 2.0, 1.0) (3.0, 3.0, 2.0, 4.0) (2.0, 2.0, 6.0, 2.0)
Python binary file reading problem
I'm trying to read a binary file (which represents a matrix in Matlab) in Python. But I am having trouble reading the file and converting the bytes to the correct values. The binary file consists of a sequence of 4-byte numbers. The first two numbers are the number of rows and columns respectively. My friend gave me a Matlab function he wrote that does this using fwrite. I would like to do something like this: f = open(filename, 'rb') rows = f.read(4) cols = f.read(4) m = [[0 for c in cols] for r in rows] r = c = 0 while True: if c == cols: r += 1 c = 0 num = f.read(4) if num: m[r][c] = num c += 1 else: break But whenever I use f.read(4), I get something like '\x00\x00\x00\x04' (this specific example should represent a 4), and I can't figure out convert it into the correct number (using int, hex or anything like that doesn't work). I stumbled upon struct.unpack, but that didn't seem to help very much. Here is an example matrix and the corresponding binary file (as it appears when I read the entire file using the python function f.read() without any size paramater) that the Matlab function created for it: 4 4 2 4 2 2 2 1 3 3 2 4 2 2 6 2 '\x00\x00\x00\x04\x00\x00\x00\x04@\x80\x00\x00@\x00\x00\x00@@\x00\x00@\x00\x00\x00@\x80\x00\x00@\x00\x00\x00@@\x00\x00@\x00\x00\x00@\x00\x00\x00@\x00\x00\x00@\x00\x00\x00@\xc0\x00\x00@\x80\x00\x00?\x80\x00\x00@\x80\x00\x00@\x00\x00\x00' So the first 4 bytes and the 5th-8th bytes should both be 4, as the matrix is 4x4. and then it should be 4,4,2,4,2,2,2,1,etc... Thanks guys!
[ "rows = f.read(4)\ncols = f.read(4)\n\nboth names are now bound to 4-byte strings. To turn them into integers instead,\nimport struct\n\nrowsandcols = f.read(8)\nrows, cols = struct.unpack('=ii', rowsandcols)\n\nSee the docs for struct.unpack.\n", "I looked a bit more in your problem, since I had never used stru...
[ 7, 2 ]
[]
[]
[ "binary", "file_io", "matlab", "python" ]
stackoverflow_0003162191_binary_file_io_matlab_python.txt
Q: Python: Looping over One Dictionary and Creating Key/Value Pairs in a New Dictionary if Conditions Are Met I want to compare the values of one dictionary to the values of a second dictionary. If the values meet certain criteria, I want to create a third dictionary with keys and value pairs that will vary depending on the matches. Here is a contrived example that shows my problem. edit: sorry about all the returns, but stack overflow is not recognizing single returns and is running 3-4 lines onto one line, making the code illegible. also, it's not greying out my code as code. don't know why. employee = {'skills': 'superintendent', 'teaches': 'social studies', 'grades': 'K-12'} school_districts = {0: {'needs': 'superintendent', 'grades': 'K-12'}, 1:{'needs': 'social_studies', 'grades': 'K-12'}} jobs_in_school_district = {} for key in school_districts: if (employee['skills'] == school_districts[key]['needs']): jobs_in_school_district[key] = {} jobs_in_school_district[key]['best_paying_job'] = 'superintendent' if (employee['teaches'] == school_districts[key]['needs']): jobs_in_school_district[key] = {} jobs_in_school_district[key]['other_job'] = 'social_studies_teacher' print(jobs_in_school_district) This is the value I want to see for 'jobs_in_school_district ': {0: {'best_paying_job': 'superintendent'}, 1: {'other_job': 'social_studies_teacher'}} This is what I'm getting: {1: {'other_job': 'social_studies_teacher'}} I understand what's wrong here. Python is setting jobs_in_school_district equal to {0: {'best_paying_job': 'superintendent'} after the first if block (lines 6-8). Then it executes the second if block (line 10). But then it overwrites the {0: {'best_paying_job': 'superintendent'} at line 11 and creates an empty dict again. Then it assigns 1: {'other_job': 'social_studies_teacher'}' to jobs_in_school_district at line 12. But if I eliminate the two jobs_in_school_district[key] = {} in each of the for blocks (lines 7 and 11) and just put one before the 'for' statement (new line 5) like this: jobs_in_school_district[key] = {} for key in school_districts: if (employee['skills'] == school_districts[key]['needs']): jobs_in_school_district[key]['best_paying_job'] = 'superintendent' if (employee['teaches'] == jobs[key]['needs']): jobs_in_school_district[key]['other_job'] = 'social_studies_teacher' print(jobs_in_school_district) It will only check the first key in the 'school_districts' dict and then stop (it stops looping I guess, I don't know), so I get this: jobs_in_school_district = {0: {'best_paying_job': 'superintendent'} (I've tried re-writing it a few times and sometimes I get a "key error" instead). First question: why doesn't that second block of code work? Second question: how do I write code so it does work? (I don't really understand 'next' (method or function) and what it does, so if I have to use it, could you please explain? Thanks). A: Simplest fix (and answer to your first question): key is not properly defined in your latest snippets, the assignment must be inside the for though outside the ifs: for key in school_districts: jobs_in_school_district[key] = {} if ... etc etc ... if ... other etc etc ... Simplest may actually be to use "default dicts" instead of plain ones: import collections jobs_in_school_district = collections.defaultdict(dict) Now you can remove the assignment to the [key] indexing and it will be done for you, automatically, if and when needed for the first time for any given key. A: Try placing jobs_in_school_district[key] = {} after the for loop but before the if statements. And yea the formatting is unreadable. A: If you change social_studies to social studies without the underscore the code works as you expected. See this line: school_districts = {0: {'needs': 'superintendent', 'grades': 'K-12'}, 1:{'needs': 'social_studies', 'grades': 'K-12'}}
Python: Looping over One Dictionary and Creating Key/Value Pairs in a New Dictionary if Conditions Are Met
I want to compare the values of one dictionary to the values of a second dictionary. If the values meet certain criteria, I want to create a third dictionary with keys and value pairs that will vary depending on the matches. Here is a contrived example that shows my problem. edit: sorry about all the returns, but stack overflow is not recognizing single returns and is running 3-4 lines onto one line, making the code illegible. also, it's not greying out my code as code. don't know why. employee = {'skills': 'superintendent', 'teaches': 'social studies', 'grades': 'K-12'} school_districts = {0: {'needs': 'superintendent', 'grades': 'K-12'}, 1:{'needs': 'social_studies', 'grades': 'K-12'}} jobs_in_school_district = {} for key in school_districts: if (employee['skills'] == school_districts[key]['needs']): jobs_in_school_district[key] = {} jobs_in_school_district[key]['best_paying_job'] = 'superintendent' if (employee['teaches'] == school_districts[key]['needs']): jobs_in_school_district[key] = {} jobs_in_school_district[key]['other_job'] = 'social_studies_teacher' print(jobs_in_school_district) This is the value I want to see for 'jobs_in_school_district ': {0: {'best_paying_job': 'superintendent'}, 1: {'other_job': 'social_studies_teacher'}} This is what I'm getting: {1: {'other_job': 'social_studies_teacher'}} I understand what's wrong here. Python is setting jobs_in_school_district equal to {0: {'best_paying_job': 'superintendent'} after the first if block (lines 6-8). Then it executes the second if block (line 10). But then it overwrites the {0: {'best_paying_job': 'superintendent'} at line 11 and creates an empty dict again. Then it assigns 1: {'other_job': 'social_studies_teacher'}' to jobs_in_school_district at line 12. But if I eliminate the two jobs_in_school_district[key] = {} in each of the for blocks (lines 7 and 11) and just put one before the 'for' statement (new line 5) like this: jobs_in_school_district[key] = {} for key in school_districts: if (employee['skills'] == school_districts[key]['needs']): jobs_in_school_district[key]['best_paying_job'] = 'superintendent' if (employee['teaches'] == jobs[key]['needs']): jobs_in_school_district[key]['other_job'] = 'social_studies_teacher' print(jobs_in_school_district) It will only check the first key in the 'school_districts' dict and then stop (it stops looping I guess, I don't know), so I get this: jobs_in_school_district = {0: {'best_paying_job': 'superintendent'} (I've tried re-writing it a few times and sometimes I get a "key error" instead). First question: why doesn't that second block of code work? Second question: how do I write code so it does work? (I don't really understand 'next' (method or function) and what it does, so if I have to use it, could you please explain? Thanks).
[ "Simplest fix (and answer to your first question): key is not properly defined in your latest snippets, the assignment must be inside the for though outside the ifs:\nfor key in school_districts:\n jobs_in_school_district[key] = {}\n if ... etc etc ...\n\n if ... other etc etc ...\n\nSimplest may actually ...
[ 3, 0, 0 ]
[]
[]
[ "conditional", "dictionary", "iteration", "key", "python" ]
stackoverflow_0003162166_conditional_dictionary_iteration_key_python.txt
Q: Flicker-free drawable ScrolledWindow I'm trying to build a ScrolledWindow that you can draw on using the mouse, and it's working too, but I'm getting a nasty flicker when the user is drawing on the window while the scrollbars aren't in the "home" position.. To reproduce, run the attached program, scroll a bit down (or to the right) and "doodle" a bit by keeping the left mouse button pressed. You should see a flickering now and then.. import wx class MainFrame(wx.Frame): """ Just a frame with a DrawPane """ def __init__(self, *args, **kw): wx.Frame.__init__(self, *args, **kw) s = wx.BoxSizer(wx.VERTICAL) s.Add(DrawPane(self), 1, wx.EXPAND) self.SetSizer(s) ######################################################################## class DrawPane(wx.PyScrolledWindow): """ A PyScrolledWindow with a 1000x1000 drawable area """ VSIZE = (1000, 1000) def __init__(self, *args, **kw): wx.PyScrolledWindow.__init__(self, *args, **kw) self.SetScrollbars(10, 10, 100, 100) self.prepare_buffer() self.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.Bind(wx.EVT_MOTION, self.on_motion) def prepare_buffer(self): self.buffer = wx.EmptyBitmap(*DrawPane.VSIZE) dc = wx.BufferedDC(None, self.buffer) dc.Clear() dc.DrawLine(0, 0, 999, 999) # Draw something to better show the flicker problem def on_paint(self, evt): dc = wx.BufferedPaintDC(self, self.buffer, wx.BUFFER_VIRTUAL_AREA) def on_mouse_down(self, evt): self.mouse_pos = self.CalcUnscrolledPosition(evt.GetPosition()).Get() def on_motion(self, evt): if evt.Dragging() and evt.LeftIsDown(): dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) newpos = self.CalcUnscrolledPosition(evt.GetPosition()).Get() coords = self.mouse_pos + newpos dc.DrawLine(*coords) self.mouse_pos = newpos self.Refresh() if __name__ == "__main__": app = wx.PySimpleApp() wx.InitAllImageHandlers() MainFrame(None).Show() app.MainLoop() I tried using SetBackgroundStyle(wx.BG_STYLE_CUSTOM), or binding EVT_ERASE_BACKGROUND, or using RefreshRect instead of Refresh, but the flicker is still there.. Any idea on what I might try next? My environment: Xubuntu 9.04, wxPython 2.8.9.1 (but tested on Ubuntu 10.04 too) Many thanks for your time! A: From Robin Dunn himself: First, a Refresh() by default will erase the background before sending the paint event (although setting the BG style or catching the erase event would have taken care of that.) The second and probably most visible problem in this case is that in your on_motion handler you are not offsetting the ClientDC by the scroll offsets, just the position in the buffer that you are drawing the line segment at. So when the buffer is flushed out to the client DC it is drawn at the physical (0,0), not the virtual (0,0). In other words, the flicker you are seeing is coming from drawing the buffer at the wrong position after every mouse drag event, and then it immediately being drawn again at the right position in the on_paint triggered by the Refresh(). You should be able to fix this by calling PrepareDC on the client DC before using it, like this: cdc = wx.CLientDC(self) self.PrepareDC(cdc) dc = wx.BufferedDC(cdc, self.buffer) However since you are doing a Refresh or RefreshRect anyway, there is no need to use a client DC here at all, just let the flushing of the buffer to the screen be done in on_paint instead: dc = wx.BufferedDC(None, self.buffer) A: Using Joril recomendations and removing Refresh(), there is no flicker anymore (even enlarging the frame). import wx class MainFrame(wx.Frame): """ Just a frame with a DrawPane """ def __init__(self, *args, **kw): wx.Frame.__init__(self, *args, **kw) s = wx.BoxSizer(wx.VERTICAL) s.Add(DrawPane(self), 1, wx.EXPAND) self.SetSizer(s) ######################################################################## class DrawPane(wx.PyScrolledWindow): """ A PyScrolledWindow with a 1000x1000 drawable area """ VSIZE = (1000, 1000) def __init__(self, *args, **kw): wx.PyScrolledWindow.__init__(self, *args, **kw) self.SetScrollbars(10, 10, 100, 100) self.prepare_buffer() cdc = wx.ClientDC(self) self.PrepareDC(cdc) dc = wx.BufferedDC(cdc, self.buffer) self.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.Bind(wx.EVT_MOTION, self.on_motion) def prepare_buffer(self): self.buffer = wx.EmptyBitmap(*DrawPane.VSIZE) cdc = wx.ClientDC(self) self.PrepareDC(cdc) dc = wx.BufferedDC(cdc, self.buffer) dc.Clear() dc.DrawLine(0, 0, 999, 999) # Draw something to better show the flicker problem def on_paint(self, evt): dc = wx.BufferedPaintDC(self, self.buffer, wx.BUFFER_VIRTUAL_AREA) def on_mouse_down(self, evt): self.mouse_pos = self.CalcUnscrolledPosition(evt.GetPosition()).Get() def on_motion(self, evt): if evt.Dragging() and evt.LeftIsDown(): newpos = self.CalcUnscrolledPosition(evt.GetPosition()).Get() coords = self.mouse_pos + newpos cdc = wx.ClientDC(self) self.PrepareDC(cdc) dc = wx.BufferedDC(cdc, self.buffer) dc.DrawLine(*coords) self.mouse_pos = newpos if __name__ == "__main__": app = wx.PySimpleApp() wx.InitAllImageHandlers() MainFrame(None).Show() app.MainLoop()
Flicker-free drawable ScrolledWindow
I'm trying to build a ScrolledWindow that you can draw on using the mouse, and it's working too, but I'm getting a nasty flicker when the user is drawing on the window while the scrollbars aren't in the "home" position.. To reproduce, run the attached program, scroll a bit down (or to the right) and "doodle" a bit by keeping the left mouse button pressed. You should see a flickering now and then.. import wx class MainFrame(wx.Frame): """ Just a frame with a DrawPane """ def __init__(self, *args, **kw): wx.Frame.__init__(self, *args, **kw) s = wx.BoxSizer(wx.VERTICAL) s.Add(DrawPane(self), 1, wx.EXPAND) self.SetSizer(s) ######################################################################## class DrawPane(wx.PyScrolledWindow): """ A PyScrolledWindow with a 1000x1000 drawable area """ VSIZE = (1000, 1000) def __init__(self, *args, **kw): wx.PyScrolledWindow.__init__(self, *args, **kw) self.SetScrollbars(10, 10, 100, 100) self.prepare_buffer() self.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.Bind(wx.EVT_MOTION, self.on_motion) def prepare_buffer(self): self.buffer = wx.EmptyBitmap(*DrawPane.VSIZE) dc = wx.BufferedDC(None, self.buffer) dc.Clear() dc.DrawLine(0, 0, 999, 999) # Draw something to better show the flicker problem def on_paint(self, evt): dc = wx.BufferedPaintDC(self, self.buffer, wx.BUFFER_VIRTUAL_AREA) def on_mouse_down(self, evt): self.mouse_pos = self.CalcUnscrolledPosition(evt.GetPosition()).Get() def on_motion(self, evt): if evt.Dragging() and evt.LeftIsDown(): dc = wx.BufferedDC(wx.ClientDC(self), self.buffer) newpos = self.CalcUnscrolledPosition(evt.GetPosition()).Get() coords = self.mouse_pos + newpos dc.DrawLine(*coords) self.mouse_pos = newpos self.Refresh() if __name__ == "__main__": app = wx.PySimpleApp() wx.InitAllImageHandlers() MainFrame(None).Show() app.MainLoop() I tried using SetBackgroundStyle(wx.BG_STYLE_CUSTOM), or binding EVT_ERASE_BACKGROUND, or using RefreshRect instead of Refresh, but the flicker is still there.. Any idea on what I might try next? My environment: Xubuntu 9.04, wxPython 2.8.9.1 (but tested on Ubuntu 10.04 too) Many thanks for your time!
[ "From Robin Dunn himself:\n\nFirst, a Refresh() by default will\n erase the background before sending\n the paint event (although setting the\n BG style or catching the erase event\n would have taken care of that.) The\n second and probably most visible\n problem in this case is that in your\n on_motion han...
[ 5, 2 ]
[]
[]
[ "flicker", "python", "scrolledwindow", "wxpython" ]
stackoverflow_0003147613_flicker_python_scrolledwindow_wxpython.txt
Q: Displaying and refreshing my picture every 5 seconds Ok, I've got the GUI in tkinter working, and I'm trying to grab and image every 5 seconds and display it in a Label named Picturelabel. from Tkinter import * from PIL import ImageGrab import cStringIO, base64, time, threading class PictureThread(threading.Thread): def run(self): print "test" box = (0,0,500,500) #x,x,width,height MyImage = ImageGrab.grab(box) fp = cStringIO.StringIO() MyImage.save(fp, 'GIF') MyPhotoImage = PhotoImage(data=base64.encodestring(fp.getvalue())) time.sleep(5) PictureThread().run() #If I get rid of this then it just display one image return MyPhotoImage MyVeryNewImage = PictureThread().run() Picturelabel = Label(BalanceFrame, image=MyVeryNewImage) Picturelabel.grid(row=3, column=2, columnspan=3) Picturelabel.image = MyVeryNewImage window.mainloop() Firstly how can I clean up this code, as starting a thread inside another thread can't be good practice. Also when I run this it prints "test" in the console, but it does not bring up the GUI. If I comment out the commented text (PictureThread().run() where I'm creating yet another thread inside it.) then it displays the first image, but not any more. A: The problem is that you return the new image from the PictureThread().run() in the method, but you never save it. How about: from Tkinter import * from PIL import ImageGrab import cStringIO, base64, time, threading box = (0,0,500,500) #x,x,width,height MyImage = ImageGrab.grab(box) fp = cStringIO.StringIO() MyImage.save(fp, 'GIF') MyPhotoImage = PhotoImage(data=base64.encodestring(fp.getvalue())) Picturelabel = Label(BalanceFrame, image=MyPhotoImage) Picturelabel.grid(row=3, column=2, columnspan=3) class PictureThread(threading.Thread): def run(self): while True: box = (0,0,500,500) #x,x,width,height MyImage = ImageGrab.grab(box) fp = cStringIO.StringIO() MyImage.save(fp, 'GIF') MyPhotoImage = PhotoImage(data=base64.encodestring(fp.getvalue())) time.sleep(5) Picturelabel.image = MyPhotoImage PictureThread().start() window.mainloop() A: You should call start() instead of run(). From the Documentation: Once a thread object is created, its activity must be started by calling the thread’s start() method. This invokes the run() method in a separate thread of control. I see you're invoking a new thread inside your run() method. This will cause you to spawn infinite threads! EDIT: I'm not sure if this works: from Tkinter import * from PIL import ImageGrab import cStringIO, base64, time, threading Picturelabel = Label(BalanceFrame) Picturelabel.grid(row=3, column=2, columnspan=3) class PictureThread(threading.Thread): def run(self): print "test" box = (0,0,500,500) #x,x,width,height fp = cStringIO.StringIO() while(1): MyImage = ImageGrab.grab(box) MyImage.save(fp, 'GIF') self.image = PhotoImage(data=base64.encodestring(fp.getvalue())) Picturelabel.image = self.image fp.reset() # reset the fp position to the start fp.truncate() # and truncate the file so we don't get garbage time.sleep(5) PictureThread().start() window.mainloop()
Displaying and refreshing my picture every 5 seconds
Ok, I've got the GUI in tkinter working, and I'm trying to grab and image every 5 seconds and display it in a Label named Picturelabel. from Tkinter import * from PIL import ImageGrab import cStringIO, base64, time, threading class PictureThread(threading.Thread): def run(self): print "test" box = (0,0,500,500) #x,x,width,height MyImage = ImageGrab.grab(box) fp = cStringIO.StringIO() MyImage.save(fp, 'GIF') MyPhotoImage = PhotoImage(data=base64.encodestring(fp.getvalue())) time.sleep(5) PictureThread().run() #If I get rid of this then it just display one image return MyPhotoImage MyVeryNewImage = PictureThread().run() Picturelabel = Label(BalanceFrame, image=MyVeryNewImage) Picturelabel.grid(row=3, column=2, columnspan=3) Picturelabel.image = MyVeryNewImage window.mainloop() Firstly how can I clean up this code, as starting a thread inside another thread can't be good practice. Also when I run this it prints "test" in the console, but it does not bring up the GUI. If I comment out the commented text (PictureThread().run() where I'm creating yet another thread inside it.) then it displays the first image, but not any more.
[ "The problem is that you return the new image from the PictureThread().run() in the method, but you never save it.\nHow about:\nfrom Tkinter import *\nfrom PIL import ImageGrab\nimport cStringIO, base64, time, threading\n\nbox = (0,0,500,500) #x,x,width,height\nMyImage = ImageGrab.grab(box)\n\nfp = cStringIO.String...
[ 0, 0 ]
[]
[]
[ "multithreading", "python", "tkinter" ]
stackoverflow_0003162564_multithreading_python_tkinter.txt
Q: Python "List" object is not callable I'm writing a program that looks through CSVs in a directory and appends the contents of each CSV to a list. Here's a snippet of the offending code: import glob import re c = glob.glob("*.csv") print c archive = [] for element in c: look = open(element, "r").read() open = re.split("\n+", look) for n in open: n = re.split(",", n)[0] archive.append(n) However, when I run this script, I get a TypeError: 'list' object is not callable. Can somebody please explain what's going on? A: I think it's because you redefine open as a list and call it in the next loop iteration. Just give the list another name. Note that strings have a split() method for when you don't need a regex. A: The fact that open is a builtin function is irrelevant. It could have been a function defined in the same module. The basic problem is that the same name was used to refer to two different objects (a function and a list), both of which were needed again. When the first object was needed again, the name referred to the second object. Result: splat. The golden rule is: don't re-use names unthinkingly. A: The gold rule is: never use the name of a builtin thing for your variables! It's a matter of aliasing, just don't call the list open.. A: Agree with previous answers: never call a variable open or any other builtin. You may be interested int the Python csv module, which will correctly parse csv files that re.split(',', line) won't. Also, you can use the file object as a line-by-line iterator like so: for line in open('data.csv'): do_something(line)
Python "List" object is not callable
I'm writing a program that looks through CSVs in a directory and appends the contents of each CSV to a list. Here's a snippet of the offending code: import glob import re c = glob.glob("*.csv") print c archive = [] for element in c: look = open(element, "r").read() open = re.split("\n+", look) for n in open: n = re.split(",", n)[0] archive.append(n) However, when I run this script, I get a TypeError: 'list' object is not callable. Can somebody please explain what's going on?
[ "I think it's because you redefine open as a list and call it in the next loop iteration.\nJust give the list another name.\nNote that strings have a split() method for when you don't need a regex.\n", "The fact that open is a builtin function is irrelevant. It could have been a function defined in the same modul...
[ 10, 5, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003162588_python.txt
Q: What does [[]]*2 do in python? A = [[]]*2 A[0].append("a") A[1].append("b") B = [[], []] B[0].append("a") B[1].append("b") print "A: "+ str(A) print "B: "+ str(B) Yields: A: [['a', 'b'], ['a', 'b']] B: [['a'], ['b']] One would expect that the A list would be the same as the B list, this is not the case, both append statements were applied to A[0] and A[1]. Why? A: A = [[]]*2 creates a list with 2 identical elements: [[],[]]. The elements are the same exact list. So A[0].append("a") A[1].append("b") appends both "a" and "b" to the same list. B = [[], []] creates a list with 2 distinct elements. In [220]: A=[[]]*2 In [221]: A Out[221]: [[], []] This shows that the two elements of A are identical: In [223]: id(A[0])==id(A[1]) Out[223]: True In [224]: B=[[],[]] This shows that the two elements of B are different objects. In [225]: id(B[0])==id(B[1]) Out[225]: False
What does [[]]*2 do in python?
A = [[]]*2 A[0].append("a") A[1].append("b") B = [[], []] B[0].append("a") B[1].append("b") print "A: "+ str(A) print "B: "+ str(B) Yields: A: [['a', 'b'], ['a', 'b']] B: [['a'], ['b']] One would expect that the A list would be the same as the B list, this is not the case, both append statements were applied to A[0] and A[1]. Why?
[ "A = [[]]*2 creates a list with 2 identical elements: [[],[]].\nThe elements are the same exact list.\nSo\nA[0].append(\"a\")\nA[1].append(\"b\")\n\nappends both \"a\" and \"b\" to the same list.\nB = [[], []] creates a list with 2 distinct elements. \nIn [220]: A=[[]]*2\n\nIn [221]: A\nOut[221]: [[], []]\n\nThis s...
[ 17 ]
[]
[]
[ "python" ]
stackoverflow_0003162698_python.txt
Q: Scraping Ajax - Using python I'm trying to scrap a page in youtube with python which has lot of ajax in it I've to call the java script each time to get the info. But i'm not really sure how to go about it. I'm using the urllib2 module to open URLs. Any help would be appreciated. A: Youtube (and everything else Google makes) have EXTENSIVE APIs already in place for giving you access to just about any and all data you could possibly want. Take a look at The Youtube Data API for more information. I use urllib to make the API requests and ElementTree to parse the returned XML. A: Main problem is, you're violating the TOS (terms of service) for the youtube site. Youtube engineers and lawyers will do their professional best to track you down and make an example of you if you persist. If you're happy with that prospect, then, on you head be it -- technically, your best bet are python-spidermonkey and selenium. I wanted to put the technical hints on record in case anybody in the future has needs like the ones your question's title indicates, without the legal issues you clearly have if you continue in this particular endeavor. A: Here is how I would do it: Install Firebug on Firefox, then turn the NET on in firebug and click on the desired link on YouTube. Now see what happens and what pages are requested. Find the one that are responsible for the AJAX part of page. Now you can use urllib or Mechanize to fetch the link. If you CAN pull the same content this way, then you have what you are looking for, then just parse the content. If you CAN'T pull the content this way, then that would suggest that the requested page might be looking at user login credentials, sessions info or other header fields such as HTTP_REFERER ... etc. Then you might want to look at something more extensive like the scrapy ... etc. I would suggest that you always follow the simple path first. Good luck and happy "responsibly" scraping! :) A: As suggested, you should use the YouTube API to access the data made available legitimately. Regarding the general question of scraping AJAX, you might want to consider the scrapy framework. It provides extensive support for crawling and scraping web sites and uses python-spidermonkey under the hood to access javascript links. A: You could sniff the network traffic with something like Wireshark then replay the HTTP calls via a scraping framework that is robust enough to deal with AJAX, such as scraPY.
Scraping Ajax - Using python
I'm trying to scrap a page in youtube with python which has lot of ajax in it I've to call the java script each time to get the info. But i'm not really sure how to go about it. I'm using the urllib2 module to open URLs. Any help would be appreciated.
[ "Youtube (and everything else Google makes) have EXTENSIVE APIs already in place for giving you access to just about any and all data you could possibly want.\nTake a look at The Youtube Data API for more information.\nI use urllib to make the API requests and ElementTree to parse the returned XML.\n", "Main prob...
[ 6, 6, 2, 0, 0 ]
[]
[]
[ "ajax", "python", "screen_scraping" ]
stackoverflow_0001281075_ajax_python_screen_scraping.txt
Q: Python regex confused by brackets ([])? Is python confused, or is the programmer? I've got a lot of lines of this: some_dict[0x2a] = blah some_dict[0xab] = blah, blah What I'd like to do is to convert the hex codes into all uppercase to look like this: some_dict[0x2A] = blah some_dict[0xAB] = blah, blah So I decided to call in the regular expressions. Normally, I'd just do this using my editor's regexps (xemacs), but the need to convert to uppercase pushes one into Lisp. ....ok... how about Python? So I whip together a short script which doesn't work. I've condensed the code into this example, which doesn't work either. It looks to me like Python's regexps are getting confused by the brackets in the code. Is it me or Python? import fileinput import sys import re this = "0x2a" that = "[0x2b]" for line in [this, that]: found = re.match("0x([0-9,a-f]{2})", line) if found: print("Found: %s" % found.group(0)) (I'm using the () grouping constructs so I don't capitalize the 'x' in '0x'.) This example only prints the 0x2a value, not the 0x2b. Is this correct behavior? I can easily work around this by changing the match expression to: found = re.match("\[0x([0-9,a-f]{2}\])", line) but I'm just wondering if someone can give me some insight into what's going on here. Running Python 2.6.2 on Linux. A: re.match matches from the start of the string. Use re.search instead to "match the first occurrence anywhere in the string". The key bit about this in the docs is here. A: I don't think you need the comma within the brackets. i.e.: found = re.match("0x([0-9,a-f]{2})", line) tells python to look for commas which it might be mistakenly matching. I think you want found = re.match("0x([0-9a-f]{2})", line) A: You're using a partial pattern, so you can't use re.match, which expects to match the entire input string. You need to use re.search, which can perform partial matches. >>> that = "[0x2b]" >>> m = re.search("0x([0-9,a-f]{2})", that) >>> m.group() '0x2b' A: You'll want to change found = re.match("0x([0-9,a-f]{2})", line) to found = re.search("0x([0-9,a-f]{2})", line) re.match will match only from the beginning of the string, which fails in the "[0x2b]" case. re.search will match anywhere in the string, and thus ignore the leading "[" in the "[0x2b]" case. See search() vs. match() for details. A: You want to use re.search. This explains why. A: If you use re.sub, and pass a callable as the replacement string, it will also do the uppercasing for you: >>> that = 'some_dict[0x2a] = blah' >>> m = re.sub("0x([0-9,a-f]{2})", lambda x: "0x"+x.group(1).upper(), that) >>> m 'some_dict[0x2A] = blah'
Python regex confused by brackets ([])?
Is python confused, or is the programmer? I've got a lot of lines of this: some_dict[0x2a] = blah some_dict[0xab] = blah, blah What I'd like to do is to convert the hex codes into all uppercase to look like this: some_dict[0x2A] = blah some_dict[0xAB] = blah, blah So I decided to call in the regular expressions. Normally, I'd just do this using my editor's regexps (xemacs), but the need to convert to uppercase pushes one into Lisp. ....ok... how about Python? So I whip together a short script which doesn't work. I've condensed the code into this example, which doesn't work either. It looks to me like Python's regexps are getting confused by the brackets in the code. Is it me or Python? import fileinput import sys import re this = "0x2a" that = "[0x2b]" for line in [this, that]: found = re.match("0x([0-9,a-f]{2})", line) if found: print("Found: %s" % found.group(0)) (I'm using the () grouping constructs so I don't capitalize the 'x' in '0x'.) This example only prints the 0x2a value, not the 0x2b. Is this correct behavior? I can easily work around this by changing the match expression to: found = re.match("\[0x([0-9,a-f]{2}\])", line) but I'm just wondering if someone can give me some insight into what's going on here. Running Python 2.6.2 on Linux.
[ "re.match matches from the start of the string. Use re.search instead to \"match the first occurrence anywhere in the string\". The key bit about this in the docs is here.\n", "I don't think you need the comma within the brackets. i.e.:\nfound = re.match(\"0x([0-9,a-f]{2})\", line)\n\ntells python to look for c...
[ 7, 4, 4, 2, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003160590_python_regex.txt
Q: Can someone show me the "hello world" of Paypal IPN? I'd like to set up a PayPal donation box, and use their IPN protocol to monitor when donations come in. The documentation is enormously complex and full of features I'm not interested in. Is there a short snippet -- ideally in Python -- that shows how to, say, connect to Paypal, loop forever, and print "Just got $5" every time a donation comes in? A: Actually, with IPNs it's the other way around. PayPal posts a notification to your server via HTTP POST when a payment is made. You therefore need to make a CGI script or server that receives these posts, checks their validity, and processes them. Probably the easiest sample code to look at for setting up an IPN processor is the PHP sample code at: https://cms.paypal.com/cms_content/US/en_US/files/developer/IPN_PHP_41.txt but there's a whole set of code snippets at: https://github.com/paypal/ipn-code-samples You shouldn't skip the official documentation because it covers how to administratively set up, and test, IPNs. It's at: https://www.paypalobjects.com/webstatic/en_US/developer/docs/pdf/ipnguide.pdf In particular, see chapters 2-4.
Can someone show me the "hello world" of Paypal IPN?
I'd like to set up a PayPal donation box, and use their IPN protocol to monitor when donations come in. The documentation is enormously complex and full of features I'm not interested in. Is there a short snippet -- ideally in Python -- that shows how to, say, connect to Paypal, loop forever, and print "Just got $5" every time a donation comes in?
[ "Actually, with IPNs it's the other way around. PayPal posts a notification to your server via HTTP POST when a payment is made. You therefore need to make a CGI script or server that receives these posts, checks their validity, and processes them.\nProbably the easiest sample code to look at for setting up an IPN ...
[ 4 ]
[]
[]
[ "paypal", "paypal_ipn", "python" ]
stackoverflow_0003162758_paypal_paypal_ipn_python.txt
Q: Python search and replace in binary file I am trying to search and replace some of the text (eg 'Smith, John') in this pdf form file (header.fdf, I presumed this is treated as binary file): '%FDF-1.2\n%\xe2\xe3\xcf\xd3\n1 0 obj\n<</FDF<</Fields[<</V(M)/T(PatientSexLabel)>><</V(24-09-1956 53)/T(PatientDateOfBirth)>><</V(Fisher)/T(PatientLastNameLabel)>><</V(CNSL)/T(PatientConsultant)>><</V(28-01-2010 18:13)/T(PatientAdmission)>><</V(134 Field Street\\rBlackburn BB1 1BB)/T(PatientAddressLabel)>><</V(Smith, John)/T(PatientName)>><</V(24-09-1956)/T(PatientDobLabel)>><</V(0123456)/T(PatientRxr)>><</V(01234567891011)/T(PatientNhsLabel)>><</V(John)/T(PatientFirstNameLabel)>><</V(0123456)/T(PatientRxrLabel)>>]>>>>\nendobj\ntrailer\n<</Root 1 0 R>>\n%%EOF\n' After f=open("header.fdf","rb") s=f.read() f.close() s=s.replace(b'PatientName',name) the following error occurs: Traceback (most recent call last): File "/home/aj/Inkscape/Med/GAD/gad.py", line 56, in <module> s=s.replace(b'PatientName',name) TypeError: expected an object with the buffer interface How best to do this? A: f=open("header.fdf","rb") s=str(f.read()) f.close() s=s.replace(b'PatientName',name) or f=open("header.fdf","rb") s=f.read() f.close() s=s.replace(b'PatientName',bytes(name)) probably the latter, as I don't think you are going to be able to use unicode names with this type of substitution anyway A: You must be using Python 3.X. You didn't define 'name' in your example, but it is the problem. Likely you defined it as a Unicode string: name = 'blah' It needs to be a bytes object too: name = b'blah' This works: Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('file.txt','rb') >>> s = f.read() >>> f.close() >>> s b'Test File\r\n' >>> name = b'Replacement' >>> s=s.replace(b'File',name) >>> s b'Test Replacement\r\n' In a bytes object, the arguments to replace must both be bytes objects.
Python search and replace in binary file
I am trying to search and replace some of the text (eg 'Smith, John') in this pdf form file (header.fdf, I presumed this is treated as binary file): '%FDF-1.2\n%\xe2\xe3\xcf\xd3\n1 0 obj\n<</FDF<</Fields[<</V(M)/T(PatientSexLabel)>><</V(24-09-1956 53)/T(PatientDateOfBirth)>><</V(Fisher)/T(PatientLastNameLabel)>><</V(CNSL)/T(PatientConsultant)>><</V(28-01-2010 18:13)/T(PatientAdmission)>><</V(134 Field Street\\rBlackburn BB1 1BB)/T(PatientAddressLabel)>><</V(Smith, John)/T(PatientName)>><</V(24-09-1956)/T(PatientDobLabel)>><</V(0123456)/T(PatientRxr)>><</V(01234567891011)/T(PatientNhsLabel)>><</V(John)/T(PatientFirstNameLabel)>><</V(0123456)/T(PatientRxrLabel)>>]>>>>\nendobj\ntrailer\n<</Root 1 0 R>>\n%%EOF\n' After f=open("header.fdf","rb") s=f.read() f.close() s=s.replace(b'PatientName',name) the following error occurs: Traceback (most recent call last): File "/home/aj/Inkscape/Med/GAD/gad.py", line 56, in <module> s=s.replace(b'PatientName',name) TypeError: expected an object with the buffer interface How best to do this?
[ "f=open(\"header.fdf\",\"rb\")\ns=str(f.read())\nf.close()\ns=s.replace(b'PatientName',name)\n\nor\nf=open(\"header.fdf\",\"rb\")\ns=f.read()\nf.close()\ns=s.replace(b'PatientName',bytes(name))\n\nprobably the latter, as I don't think you are going to be able to use unicode names with this type of substitution anyw...
[ 32, 11 ]
[]
[]
[ "binary_data", "python", "replace" ]
stackoverflow_0003162614_binary_data_python_replace.txt
Q: Python2.6 XML reading I want to migrate my system from Active Python 2.4 to Python 2.6.5. However I face some problem in parsing XML files. The I/O is very slow. My sample xml file <config><dicts><dictName>EnvDict</dictName><dictElems><key>AppServerIP</key> <value>localhost</value><key>DBServerIP</key> <value>localhost</value><key>DBServerName</key> <value>DB1</value></dictElems></dicts></config> My log shows this xml parsing took 25s. My system is structure as below Publisher-Subr is used to redirect request to different modules ClntMgrFact is attached to PubSubr and listen to pre-defined ports. It will spawn a new process for login from client. ClntMgr(process) is spawned by ClntMgrFact and also attached to PubSubr. ClntMgr will generate a ClntWorker(thread) to process workflow. ClntWorker need to read some static XML file from local. But the parsing is extremely slow. My XML file is around 500 - 700k. Any one can help on this without changing the system structure? Thanks in advance. A: I'm very perplexed...: $ py26 -mtimeit -s'import rex' 'rex.t()' 10000 loops, best of 3: 103 usec per loop 100 microseconds seems more reasonable than 25 seconds to read in, and parse, such a small XML file as you're giving (even on the old laptop I'm using for the timing!) -- but how to explain the fact that my parsing is being 250,000 times faster than yours?! This is rex.py, btw...: import xml.etree.cElementTree as et def t(fn='static.xml'): return et.parse(fn) and static.xml is the file where I wrote your XML example (223 characters). So what's your platform, OS, Python version, chosen XML parser, etc...? I'm on a macbook pro laptop, OSX 10.5.8, 2.4 GHz Intel Core Duo, 667 MHz DDR2 RAM -- as I said, a pretty old machine indeed! -- with Python 2.6.4 straight from python.org.
Python2.6 XML reading
I want to migrate my system from Active Python 2.4 to Python 2.6.5. However I face some problem in parsing XML files. The I/O is very slow. My sample xml file <config><dicts><dictName>EnvDict</dictName><dictElems><key>AppServerIP</key> <value>localhost</value><key>DBServerIP</key> <value>localhost</value><key>DBServerName</key> <value>DB1</value></dictElems></dicts></config> My log shows this xml parsing took 25s. My system is structure as below Publisher-Subr is used to redirect request to different modules ClntMgrFact is attached to PubSubr and listen to pre-defined ports. It will spawn a new process for login from client. ClntMgr(process) is spawned by ClntMgrFact and also attached to PubSubr. ClntMgr will generate a ClntWorker(thread) to process workflow. ClntWorker need to read some static XML file from local. But the parsing is extremely slow. My XML file is around 500 - 700k. Any one can help on this without changing the system structure? Thanks in advance.
[ "I'm very perplexed...:\n$ py26 -mtimeit -s'import rex' 'rex.t()'\n10000 loops, best of 3: 103 usec per loop\n\n100 microseconds seems more reasonable than 25 seconds to read in, and parse, such a small XML file as you're giving (even on the old laptop I'm using for the timing!) -- but how to explain the fact that ...
[ 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003163133_python_xml.txt
Q: Better Way to Write This List Comprehension? I'm parsing a string that doesn't have a delimiter but does have specific indexes where fields start and stop. Here's my list comprehension to generate a list from the string: field_breaks = [(0,2), (2,10), (10,13), (13, 21), (21, 32), (32, 43), (43, 51), (51, 54), (54, 55), (55, 57), (57, 61), (61, 63), (63, 113), (113, 163), (163, 213), (213, 238), (238, 240), (240, 250), (250, 300)] s = '4100100297LICACTIVE 09-JUN-198131-DEC-2010P0 Y12490227WYVERN RESTAURANTS INC 1351 HEALDSBURG AVE HEALDSBURG CA95448 ROUND TABLE PIZZA 575 W COLLEGE AVE STE 201 SANTA ROSA CA95401 ' data = [s[x[0]:x[1]].strip() for x in field_breaks] Any recommendation on how to improve this? A: You can cut your field_breaks list in half by doing: field_breaks = [0, 2, 10, 13, 21, 32, 43, ..., 250, 300] s = ... data = [s[x[0]:x[1]].strip() for x in zip(field_breaks[:-1], field_breaks[1:])] A: You can use tuple unpacking for cleaner code: data = [s[a:b].strip() for a,b in field_breaks] A: To be honest, I don't find the parse-by-column-number approach very readable, and I question its maintainability (off by one errors and the like). Though I'm sure the list comprehensions are very virtuous and efficient in this case, and the suggested zip-based solution has a nice functional tweak to it. Instead, I'm going to throw softballs from out here in left field, since list comprehensions are supposed to be in part about making your code more declarative. For something completely different, consider the following approach based on the pyparsing module: def Fixed(chars, width): return Word(chars, exact=width) myDate = Combine(Fixed(nums,2) + Literal('-') + Fixed(alphas,3) + Literal('-') + Fixed(nums,4)) fullRow = Fixed(nums,2) + Fixed(nums,8) + Fixed(alphas,3) + Fixed(alphas,8) + myDate + myDate + ... data = fullRow.parseString(s) # should be ['41', '00100297', 'LIC', 'ACTIVE ', # '09-JUN-1981', '31-DEC-2010', ...] To make this even more declarative, you could name each of the fields as you come across them. I have no idea what the fields actually are, but something like: someId = Fixed(nums,2) someOtherId = Fixed(nums,8) recordType = Fixed(alphas,3) recordStatus = Fixed(alphas,8) birthDate = myDate issueDate = myDate fullRow = someId + someOtherId + recordType + recordStatus + birthDate + issueDate + ... Now an approach like this probably isn't going to break any land speed records. But, holy cow, wouldn't you find this easier to read and maintain? A: Here is a way using map data = map(s.__getslice__, *zip(*field_breaks))
Better Way to Write This List Comprehension?
I'm parsing a string that doesn't have a delimiter but does have specific indexes where fields start and stop. Here's my list comprehension to generate a list from the string: field_breaks = [(0,2), (2,10), (10,13), (13, 21), (21, 32), (32, 43), (43, 51), (51, 54), (54, 55), (55, 57), (57, 61), (61, 63), (63, 113), (113, 163), (163, 213), (213, 238), (238, 240), (240, 250), (250, 300)] s = '4100100297LICACTIVE 09-JUN-198131-DEC-2010P0 Y12490227WYVERN RESTAURANTS INC 1351 HEALDSBURG AVE HEALDSBURG CA95448 ROUND TABLE PIZZA 575 W COLLEGE AVE STE 201 SANTA ROSA CA95401 ' data = [s[x[0]:x[1]].strip() for x in field_breaks] Any recommendation on how to improve this?
[ "You can cut your field_breaks list in half by doing:\nfield_breaks = [0, 2, 10, 13, 21, 32, 43, ..., 250, 300]\ns = ...\ndata = [s[x[0]:x[1]].strip() for x in zip(field_breaks[:-1], field_breaks[1:])]\n\n", "You can use tuple unpacking for cleaner code:\ndata = [s[a:b].strip() for a,b in field_breaks]\n\n", "T...
[ 7, 7, 3, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0003163391_list_comprehension_python.txt
Q: Can't build readline when trying to install Python 2.6.5 in Debian 4.3.2 I am trying to install Python 2.6.5 on my web server running Debian 4.3.2.1-1. I unpacked the tarball, ran "./configure --prefix /usr/", then ran "make". I saw this message. Failed to find the necessary bits to build these modules: _bsddb _hashlib _ssl _tkinter bsddb185 bz2 dl imageop readline sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the module's name. I thought it was not a big deal, so I went ahead with the rest of the installation, which I think was just running "make install" as root. I tried running the new version of Python, and it worked, but some things acted funny. The usual keyboard shortcuts at the interactive prompt didn't work. I tried importing readline and the interpreter couldn't find it. Is there any way to make it work? I tried looking in setup.py like "make" told me, but I couldn't find any clues that were useful to me. I would really like to get readline to work. I don't really care about the other modules. EDIT: This is on a DreamHost private server. They have some older versions of Python with readline, and they seem to work fine. I am trying to make it work with this new version. I would like to add that I am kind of a Linux newbie, and I don't know much about installing packages, and using RPM or apt-get. A: You'll probably need to install the libreadline-dev virtual package for Debian 4 (etch) to be able to build python with libreadline support. Check the package dependencies for the Debian python2.6 source package here. It's for a newer version of Debian so not all of the same versions will be available in etch but you should be able to hunt down the closest versions available there to be able to build most of the other missing modules. Or you could try a dry run of installing the current testing (squeeze) version of python2.6 and see how many dependencies it brings along and if you're OK with upgrading those on your system.
Can't build readline when trying to install Python 2.6.5 in Debian 4.3.2
I am trying to install Python 2.6.5 on my web server running Debian 4.3.2.1-1. I unpacked the tarball, ran "./configure --prefix /usr/", then ran "make". I saw this message. Failed to find the necessary bits to build these modules: _bsddb _hashlib _ssl _tkinter bsddb185 bz2 dl imageop readline sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the module's name. I thought it was not a big deal, so I went ahead with the rest of the installation, which I think was just running "make install" as root. I tried running the new version of Python, and it worked, but some things acted funny. The usual keyboard shortcuts at the interactive prompt didn't work. I tried importing readline and the interpreter couldn't find it. Is there any way to make it work? I tried looking in setup.py like "make" told me, but I couldn't find any clues that were useful to me. I would really like to get readline to work. I don't really care about the other modules. EDIT: This is on a DreamHost private server. They have some older versions of Python with readline, and they seem to work fine. I am trying to make it work with this new version. I would like to add that I am kind of a Linux newbie, and I don't know much about installing packages, and using RPM or apt-get.
[ "You'll probably need to install the libreadline-dev virtual package for Debian 4 (etch) to be able to build python with libreadline support. Check the package dependencies for the Debian python2.6 source package here. It's for a newer version of Debian so not all of the same versions will be available in etch bu...
[ 7 ]
[]
[]
[ "debian", "linux", "python", "readline" ]
stackoverflow_0003163573_debian_linux_python_readline.txt
Q: Storing Application Sensitive Data I am implementing a python application that will connect to our different servers and computers. They all have different logins and passwords. I want to store all these information in the app directly and ask for one master login/password only. How can I store all these sensitive data in the application so that someone who hasn't the master password will not be able to access our servers and computers? EDIT: would it be possible to store an encrypted file to store these data? EDIT2: My app runs under windows for the moment. I will port it to linux and MAC OSX if possible. EDIT3: for those interested, I used M2secret + M2Crypto to encrypt a text file. When launching the application, the user has to enter a password which is used to decrypt the file and load the needed credentials into the app. Seems to work like that... Best regards. A: This sounds like a very bad idea. You could encrypt the logins and passwords, but anyone who has access to the master password will then have access to all of the individual logins. That means you can guarantee the individual logins won't remain a secret for long and if they do leak out you'll have to change them all. A better solution would be to give each user of your application their own login on each of your servers. Then you application can use the same login/password for every server it accesses and the password doesn't need to be stored in the application at all. If one user's password is leaked you just change their password on all their logins and the other users aren't affected. Alternatively route all the logins through a single server proxy: the proxy can be on a secured system so none of the users every get near any of the underlying accounts and you can protect access to the proxy by individual user accounts. I dug through some of my old code and came up with the following from a module I called 'passwordcache.py'. See if this helps: """Password Cache This module provides a portable interface for caching passwords. Operations: Store a password. Retrieve a password (which may prompt for a password if it needs it). Test whether or not we have a password stored. Clear a stored password. Passwords are identified by a combination key app/service/user. """ import sys, os, random, hashlib random.seed() # Init random number generator from other random source or system time class PasswordCacheBase(object): """Base class for common functionality between different platform implementations""" def __init__(self, application=None): """PasswordCache(application) Creates a new store for passwords (or opens an existing one). The application name may be any string, but defaults to the script name. """ if application is None: self.application = os.path.basename(sys.argv[0]) else: self.application = application def get(self, service, user, getpass=None, cache=False): """Retrieve a password from the store""" raise NotImplementedError() def set(self, service, user, password): """Save a password in the store""" raise NotImplementedError() def exists(self, service, user): """Check whether a password exists""" try: pwd = self.get(service, user) except KeyError: return False return True def clear(self, service, user): raise NotImplementedError() def salt(self, service, user): """Get a salt value to help prevent encryption collisions. The salt string is 16 bytes long.""" salt = hashlib.md5("%r|%s|%s|%s" % (random.random(), self.application, service, user)).digest() return salt if sys.platform=="win32": """Interface to Windows data protection api. Based on code from: http://osdir.com/ml/python.ctypes/2003-07/msg00091.html """ from ctypes import * from ctypes.wintypes import DWORD import _winreg import cPickle as pickle LocalFree = windll.kernel32.LocalFree # Note that CopyMemory is defined in term of memcpy: memcpy = cdll.msvcrt.memcpy CryptProtectData = windll.crypt32.CryptProtectData CryptUnprotectData = windll.crypt32.CryptUnprotectData # See http://msdn.microsoft.com/architecture/application/default.aspx?pull=/library/en-us/dnnetsec/html/SecNetHT07.asp CRYPTPROTECT_UI_FORBIDDEN = 0x01 class DATA_BLOB(Structure): # See d:\vc98\Include\WINCRYPT.H # This will not work # _fields_ = [("cbData", DWORD), ("pbData", c_char_p)] # because accessing pbData will create a new Python string which is # null terminated. _fields_ = [("cbData", DWORD), ("pbData", POINTER(c_char))] class PasswordCache(PasswordCacheBase): def set(self, service, user, password): """Save a password in the store""" salt = self.salt(service, user) encrypted = self.Win32CryptProtectData( '%s' % password, salt) key = self._get_regkey() try: data = self._get_registrydata(key) data[service, user] = (salt, encrypted) self._put_registrydata(key, data) finally: key.Close() def get(self, service, user, getpass=None, cache=False): data = self._get_registrydata() try: salt, encrypted = data[service, user] decrypted = self.Win32CryptUnprotectData(encrypted, salt) except KeyError: if getpass is not None: password = getpass() if cache: self.set(service, user, password) return password raise return decrypted def clear(self, service=None, user=None): key = self._get_regkey() try: data = self._get_registrydata(key) if service is None: if user is None: data = {} else: for (s,u) in data.keys(): if u==user: del data[s,u] else: if user is None: for (s,u) in data.keys(): if s==service: del data[s,u] else: if (service,user) in data: del data[service,user] self._put_registrydata(key, data) finally: key.Close() def _get_regkey(self): return _winreg.CreateKey( _winreg.HKEY_CURRENT_USER, r'Software\Python\Passwords') def _get_registrydata(self, regkey=None): if regkey is None: key = self._get_regkey() try: return self._get_registrydata(key) finally: key.Close() try: current = _winreg.QueryValueEx(regkey, self.application)[0] data = pickle.loads(current.decode('base64')) except WindowsError: data = {} return data def _put_registrydata(self, regkey, data): pickled = pickle.dumps(data) _winreg.SetValueEx(regkey, self.application, None, _winreg.REG_SZ, pickled.encode('base64')) def getData(self, blobOut): cbData = int(blobOut.cbData) pbData = blobOut.pbData buffer = c_buffer(cbData) memcpy(buffer, pbData, cbData) LocalFree(pbData); return buffer.raw def Win32CryptProtectData(self, plainText, entropy): bufferIn = c_buffer(plainText, len(plainText)) blobIn = DATA_BLOB(len(plainText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() # The CryptProtectData function performs encryption on the data # in a DATA_BLOB structure. # BOOL WINAPI CryptProtectData( # DATA_BLOB* pDataIn, # LPCWSTR szDataDescr, # DATA_BLOB* pOptionalEntropy, # PVOID pvReserved, # CRYPTPROTECT_PROMPTSTRUCT* pPromptStruct, # DWORD dwFlags, # DATA_BLOB* pDataOut if CryptProtectData(byref(blobIn), u"win32crypto.py", byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return self.getData(blobOut) else: return None def Win32CryptUnprotectData(self, cipherText, entropy): bufferIn = c_buffer(cipherText, len(cipherText)) blobIn = DATA_BLOB(len(cipherText), bufferIn) bufferEntropy = c_buffer(entropy, len(entropy)) blobEntropy = DATA_BLOB(len(entropy), bufferEntropy) blobOut = DATA_BLOB() if CryptUnprotectData(byref(blobIn), None, byref(blobEntropy), None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)): return self.getData(blobOut) else: return None else: # Not Windows, try for gnome-keyring import gtk # ensure that the application name is correctly set import gnomekeyring as gkey class Keyring(object): def __init__(self, name, server, protocol): self._name = name self._server = server self._protocol = protocol self._keyring = k = gkey.get_default_keyring_sync() import pdb; pdb.set_trace() print dir(k) class PasswordCache(PasswordCacheBase): def __init__(self, application=None): PasswordCacheBase.__init__(self, application) self._keyring = gkey.get_default_keyring_sync() def set(self, service, user, password): """Save a password in the store""" attrs = { "application": self.application, "user": user, "server": service, } gkey.item_create_sync(self._keyring, gkey.ITEM_NETWORK_PASSWORD, self.application, attrs, password, True) def get(self, service, user, getpass=None, cache=False): attrs = { "application": self.application, "user": user, "server": service} try: items = gkey.find_items_sync(gkey.ITEM_NETWORK_PASSWORD, attrs) except gkey.NoMatchError: if getpass is not None: password = getpass() if cache: self.set(service, user, password) return password raise KeyError((service,user)) return items[0].secret def clear(self, service=None, user=None): attrs = {'application':self.application} if user is not None: attrs["user"] = user if service is not None: attrs["server"] = service try: items = gkey.find_items_sync(gkey.ITEM_NETWORK_PASSWORD, attrs) except gkey.NoMatchError: return for item in items: gkey.item_delete_sync(self._keyring, item.item_id)
Storing Application Sensitive Data
I am implementing a python application that will connect to our different servers and computers. They all have different logins and passwords. I want to store all these information in the app directly and ask for one master login/password only. How can I store all these sensitive data in the application so that someone who hasn't the master password will not be able to access our servers and computers? EDIT: would it be possible to store an encrypted file to store these data? EDIT2: My app runs under windows for the moment. I will port it to linux and MAC OSX if possible. EDIT3: for those interested, I used M2secret + M2Crypto to encrypt a text file. When launching the application, the user has to enter a password which is used to decrypt the file and load the needed credentials into the app. Seems to work like that... Best regards.
[ "This sounds like a very bad idea. You could encrypt the logins and passwords, but anyone who has access to the master password will then have access to all of the individual logins. That means you can guarantee the individual logins won't remain a secret for long and if they do leak out you'll have to change them ...
[ 1 ]
[]
[]
[ "encryption", "python" ]
stackoverflow_0003163903_encryption_python.txt
Q: python application development resources (as in books/online guides) can anyone recommend a resource (book,tutorial,etc.) that focuses on application development in python? something similar to Practical Django Projects, but for stand alone applications instead of web apps (for now). A: Assuming you want a GUI on your standalone application, you could try Rapid GUI Programming with Python and Qt. There are other Python reference books of course, but I don't know of any that focus solely on application development without focusing on a particular toolkit (web or otherwise).
python application development resources (as in books/online guides)
can anyone recommend a resource (book,tutorial,etc.) that focuses on application development in python? something similar to Practical Django Projects, but for stand alone applications instead of web apps (for now).
[ "Assuming you want a GUI on your standalone application, you could try Rapid GUI Programming with Python and Qt. There are other Python reference books of course, but I don't know of any that focus solely on application development without focusing on a particular toolkit (web or otherwise).\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003163814_python.txt
Q: How can I manage these subprocesses efficiently? I've got a script that downloads and then converts videos. I'm trying to do all of the downloads at once(a lot of wgets) and then when they're done, convert them. Right now I have to wait while each file downloads individually and then convert when done. I want all the download requests to run concurrently. Here's the part in my 'download' script that is holding everything up. for id in ids: subprocess.Popen(cmd, shell=True).wait() I have my 'convert' script waiting on the download script to finish. (which is necessary, because i'm using sets of downloads to organize everything.) I could use a queue but this I've already made this a big enough mess and I'm hoping there is a simpler solution. Thanks A: you could use process_list = [] for id in ids: process_list.append(subprocess.Popen(cmd, shell=True)) for process in process_list: process.wait() as such you will wait just at the end of simultaneous jobs. A: You could use xargs as a simple solution, if that is availabe for your platform. From the man page: -P max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option with -P; otherwise chances are that only one exec will be done. There are certainly better solutions, but if you need a quick one this is probably the easiest to implement.
How can I manage these subprocesses efficiently?
I've got a script that downloads and then converts videos. I'm trying to do all of the downloads at once(a lot of wgets) and then when they're done, convert them. Right now I have to wait while each file downloads individually and then convert when done. I want all the download requests to run concurrently. Here's the part in my 'download' script that is holding everything up. for id in ids: subprocess.Popen(cmd, shell=True).wait() I have my 'convert' script waiting on the download script to finish. (which is necessary, because i'm using sets of downloads to organize everything.) I could use a queue but this I've already made this a big enough mess and I'm hoping there is a simpler solution. Thanks
[ "you could use\nprocess_list = [] \nfor id in ids:\n process_list.append(subprocess.Popen(cmd, shell=True))\nfor process in process_list:\n process.wait()\n\nas such you will wait just at the end of simultaneous jobs.\n", "You could use xargs as a simple solution, if that is availabe for your platform. ...
[ 1, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0003164086_python_subprocess.txt
Q: Thread safety in Python (Question how it works) I've read through the documentation on threading for python and as I've pereceived it the following should hold true: You can access (read) any PoD or python specific object (such as an array) without causing failure in a multi-threaded program trying the same thing at the same time, but you can not change them and accept thread integrity. My question is about classes. I have a server that is delegating database access to different threads, however I want them to be able to all access an instance of a class that handles response generation. However, I'm wondering if this class is thread-safe (I wish to avoid creating multiple instances), the thread does not change any instance variables (i.e. self.something = (something)) every function uses its own local variables (they do access class instance variables but does not change them), so to sum it up: my question is if many threads can use the same instance and call functions at the same time. A: Locals are thread-safe as they are not shared between threads. All constants (variables you never write to from any thread) are thread-safe. If that's all you have, then yes, that's fine. Ensure the class members you are talking about are really not written from any other thread. Check there are no underlying shared resources that might not be thread-safe, eg. if each thread is using the database connection object that may cause trouble, unless that object is specifically documented as being thread-safe.
Thread safety in Python (Question how it works)
I've read through the documentation on threading for python and as I've pereceived it the following should hold true: You can access (read) any PoD or python specific object (such as an array) without causing failure in a multi-threaded program trying the same thing at the same time, but you can not change them and accept thread integrity. My question is about classes. I have a server that is delegating database access to different threads, however I want them to be able to all access an instance of a class that handles response generation. However, I'm wondering if this class is thread-safe (I wish to avoid creating multiple instances), the thread does not change any instance variables (i.e. self.something = (something)) every function uses its own local variables (they do access class instance variables but does not change them), so to sum it up: my question is if many threads can use the same instance and call functions at the same time.
[ "Locals are thread-safe as they are not shared between threads. All constants (variables you never write to from any thread) are thread-safe. If that's all you have, then yes, that's fine. Ensure the class members you are talking about are really not written from any other thread.\nCheck there are no underlying sha...
[ 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003164241_multithreading_python.txt
Q: How to handle post request in python how can I handle post request in python script? Somewhere I want to send it from ajax to the python script with given params. What's correct way to handle that data in python? A: you probably use a cgi and you can handle it with form = cgi.FieldStorage() as described into http://docs.python.org/library/cgi.html
How to handle post request in python
how can I handle post request in python script? Somewhere I want to send it from ajax to the python script with given params. What's correct way to handle that data in python?
[ "you probably use a cgi and you can handle it with form = cgi.FieldStorage() as described into http://docs.python.org/library/cgi.html\n" ]
[ 1 ]
[]
[]
[ "post", "python", "request" ]
stackoverflow_0003164503_post_python_request.txt
Q: How to bypass url mapping in django & make url directly point to file I'm new to web development using python. I've good amount of experience in building dynamic websites using PHP. Also, I've never used MVC on PHP. For the first time I'm using MVC (or MTV to be more correct). I'm following One thing different from PHP world is that. URLs doesn't point to files but to functions. This single point has made my experience in web development to zero. Its good for HTML content which can be generated from template. But what about things that shouldn't be rendered like movies, images, pdfs, *.exes, stylesheets & javascript files. I mean for code like this: <img src="image.jpg" /> or <link rel="stylesheet" href="stylesheets/style.css" /> or <a href="/downloads/huge_executable.exe" /> Do I need to write views for these too? If you say just one view like 'getNonRenderingContent' which reads the file and writes to http response with appropriate mime-type. I feel its stupid & unnecessary load on the server. why should it run code for every such download. Is there any way to directly point urls to files instead of views? A: You can configure your HTTP server to serve your files directly. You can read about static files in Django here: http://docs.djangoproject.com/en/dev/howto/static-files/
How to bypass url mapping in django & make url directly point to file
I'm new to web development using python. I've good amount of experience in building dynamic websites using PHP. Also, I've never used MVC on PHP. For the first time I'm using MVC (or MTV to be more correct). I'm following One thing different from PHP world is that. URLs doesn't point to files but to functions. This single point has made my experience in web development to zero. Its good for HTML content which can be generated from template. But what about things that shouldn't be rendered like movies, images, pdfs, *.exes, stylesheets & javascript files. I mean for code like this: <img src="image.jpg" /> or <link rel="stylesheet" href="stylesheets/style.css" /> or <a href="/downloads/huge_executable.exe" /> Do I need to write views for these too? If you say just one view like 'getNonRenderingContent' which reads the file and writes to http response with appropriate mime-type. I feel its stupid & unnecessary load on the server. why should it run code for every such download. Is there any way to directly point urls to files instead of views?
[ "You can configure your HTTP server to serve your files directly.\nYou can read about static files in Django here:\nhttp://docs.djangoproject.com/en/dev/howto/static-files/\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003164699_django_python.txt
Q: How to properly use PyDev with two different Python versions with scripts that are recalling other python scripts? The story began with a very strange error while I was running my script from PyDev. Running the same script from outside will not encounter the same problem. Fatal Python error: Py_Initialize: can't initialize sys standard streams File "C:\Python26\lib\encodings\__init__.py", line 123 raise CodecRegistryError,\ ^ SyntaxError: invalid syntax This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. I was able to find why this is happening: In PyDev I use two different Python versions: 3.1 that is the default installation and 2.6 as the alternative one. My Windows Environment does not contains PYTHONHOME, CLASSPATH, PYTHONPATH but PyDev does add them. Now the problem is at one stage my python script does execute another python script using os.system(python second.py) and the second script will fail with the above error. Now I'm looking to find a way to prevent this issue, issue that is happening because it will run the execute the default python using the settings for the non-default one (added by PyDev). I do not want to change the standard call (python file.py) but I want to be able to run my script from pydev without problem and being able to use default or alternative python environment. Any ideas? A: I found a solution that seams acceptable specially because it will not interfere with running the scripts on other systems, just to run python -E second.py - this will force Python to ignore PYTHON* environment variables. A: I may not be understanding this quite right, but I think you're invoking a script from pydev that works okay, but this script executes another script which requires a different version. While this would unfortunately be installation-specific, you could use os.system("c:\absolute\path\to\proper\version\of\python.exe second.py"). If PyDev is setting up conflicting environmental variables, you may want to look into subprocess over os.system. http://docs.python.org/library/subprocess.html#using-the-subprocess-module This will allow you to invoke a process with a handle, so you can optionally wait for it to terminate. It will also allow you to pass environment variables upon execution. A: I believe your call should be: import sys os.system(sys.executable+ ' second.py') So that you guarantee you're using the same interpreter you're currently running and not launching the other one (or did you really mean to use the other interpreter?)
How to properly use PyDev with two different Python versions with scripts that are recalling other python scripts?
The story began with a very strange error while I was running my script from PyDev. Running the same script from outside will not encounter the same problem. Fatal Python error: Py_Initialize: can't initialize sys standard streams File "C:\Python26\lib\encodings\__init__.py", line 123 raise CodecRegistryError,\ ^ SyntaxError: invalid syntax This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. I was able to find why this is happening: In PyDev I use two different Python versions: 3.1 that is the default installation and 2.6 as the alternative one. My Windows Environment does not contains PYTHONHOME, CLASSPATH, PYTHONPATH but PyDev does add them. Now the problem is at one stage my python script does execute another python script using os.system(python second.py) and the second script will fail with the above error. Now I'm looking to find a way to prevent this issue, issue that is happening because it will run the execute the default python using the settings for the non-default one (added by PyDev). I do not want to change the standard call (python file.py) but I want to be able to run my script from pydev without problem and being able to use default or alternative python environment. Any ideas?
[ "I found a solution that seams acceptable specially because it will not interfere with running the scripts on other systems, just to run python -E second.py - this will force Python to ignore PYTHON* environment variables.\n", "I may not be understanding this quite right, but I think you're invoking a script from...
[ 2, 0, 0 ]
[]
[]
[ "environment_variables", "python", "windows" ]
stackoverflow_0003133690_environment_variables_python_windows.txt
Q: Why the id(string) does not return the address of string import ctypes a = 'abc' b = ctypes.string_at(id(a), 3) c = ctypes.string_at(id(a) + 20, 3) I expect the result of b to be 'abc', but it is not; and the result of c is 'abc'. I don't know why. Anyone can explain me? A: In Python, a str is an object, so there is no guarantee about what it looks like in memory. Probably, it contains some more information, like the length of the string. In your case, the size of this "metadata" is apparently 20 bytes. Possibly, the object itself does not even contain the actual string, but rather a pointer to it. If that is the case, in your situation the actual string happens to be located 20 bytes after the object. Either way, this is an implementation detail. None of this behaviour should be relied upon in any serious code.
Why the id(string) does not return the address of string
import ctypes a = 'abc' b = ctypes.string_at(id(a), 3) c = ctypes.string_at(id(a) + 20, 3) I expect the result of b to be 'abc', but it is not; and the result of c is 'abc'. I don't know why. Anyone can explain me?
[ "In Python, a str is an object, so there is no guarantee about what it looks like in memory. Probably, it contains some more information, like the length of the string. In your case, the size of this \"metadata\" is apparently 20 bytes.\nPossibly, the object itself does not even contain the actual string, but rathe...
[ 6 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0003165213_ctypes_python.txt
Q: Storing 'struct' data to binary file I need to store a binary file with a 12 byte header composed of 4 fields. They are namely: sSamples (4-bytes integer), sSampPeriod (4-bytes integer), sSampSize (2-bytes integer), and finally sParmKind (2-bytes integer). I'm using 'struct' to my variables to the desired fields. Now that I have them defined separately, how could I merge them all to store the '12 bytes header'? sSamples = struct.pack('i', nSamples) # 4-bytes integer sSampPeriod = struct.pack('i', nSampPeriod) # 4-bytes integer sSampSize = struct.pack('H', nSampSize) # 2-bytes integer / unsigned short sParmKind = struct.pack('H', 9) # 2-bytes integer / unsigned short In addition, I've a npVect float array of dimensionality D (numpy.ndarray - float32). How could I store this vector in the same binary file, but after the header? A: As Cody Brocious wrote, you can pack your entire header at once: header = struct.pack('<iiHH', nSamples, nSampPeriod, nSampSize, nParmKind) He also mentioned endianness, which is important if you want to pack your data so as to reliably unpack it on machines with different architectures. The < at the beginning of my format string specifies "pack this data using a little-endian convention". As for the array, you'll have to pack its length in order to determine how many values to unpack when you read it again. Doing it all in one call: flattened = npVect.ravel() # get a 1-D array of numbers arrSize = len(flattened) # pack header, count of numbers, and numbers, all in one call packed = struct.pack('<iiHHi%df' % arrSize, nSamples, nSampPeriod, nSampSize, nParmKind, arrSize, *flattened) Depending on how big your array is likely to be, you could end up with a huge string representing the entire contents of your binary file, and you might want to look into alternatives to struct which don't require you to have the entire file in memory. Unpacking: fmt = '<iiHHi' nSamples, nSampPeriod, nSampSize, nParmKind, arrSize = struct.unpack(fmt, packed) # Use unpack_from to start reading after the packed header and count flattened = struct.unpack_from('<%df' % arrSize, packed, struct.calcsize(fmt)) npVect = np.ndarray(flattened, dtype='float32').reshape(# your dimensions go here ) EDIT: Oops, the array format isn't quite as simple as that :) The general idea holds, though: flatten your array into a list of numbers using any method you like, pack the number of values, then pack each value. On the other side, read the array as a flat list, then impose whatever structure you need on it. EDIT: Changed format strings to use repeat specifiers, rather than string multiplication. Thanks to John Machin for pointing it out. EDIT: Added numpy code to flatten the array before packing and reconstruct it after unpacking. A: struct.pack returns a string, so you can combine the fields simply by string concatenation: header = sSamples + sSampPeriod + sSampSize + sParmKind assert len( header ) == 12
Storing 'struct' data to binary file
I need to store a binary file with a 12 byte header composed of 4 fields. They are namely: sSamples (4-bytes integer), sSampPeriod (4-bytes integer), sSampSize (2-bytes integer), and finally sParmKind (2-bytes integer). I'm using 'struct' to my variables to the desired fields. Now that I have them defined separately, how could I merge them all to store the '12 bytes header'? sSamples = struct.pack('i', nSamples) # 4-bytes integer sSampPeriod = struct.pack('i', nSampPeriod) # 4-bytes integer sSampSize = struct.pack('H', nSampSize) # 2-bytes integer / unsigned short sParmKind = struct.pack('H', 9) # 2-bytes integer / unsigned short In addition, I've a npVect float array of dimensionality D (numpy.ndarray - float32). How could I store this vector in the same binary file, but after the header?
[ "As Cody Brocious wrote, you can pack your entire header at once:\nheader = struct.pack('<iiHH', nSamples, nSampPeriod, nSampSize, nParmKind)\n\nHe also mentioned endianness, which is important if you want to pack your data so as to reliably unpack it on machines with different architectures. The < at the beginning...
[ 2, 1 ]
[]
[]
[ "binaryfiles", "header_files", "python" ]
stackoverflow_0003164957_binaryfiles_header_files_python.txt
Q: Optimizing a Partition Function Here is the code, in python: # function for pentagonal numbers def pent (n): return int((0.5*n)*((3*n)-1)) # function for generalized pentagonal numbers def gen_pent (n): return pent(int(((-1)**(n+1))*(round((n+1)/2)))) # array for storing partitions - first ten already stored partitions = [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42] # function to generate partitions def partition (k): if (k < len(partitions)): return partitions[k] total, sign, i = 0, 1, 1 while (k - gen_pent(i)) >= 0: sign = (-1)**(int((i-1)/2)) total += sign*(partition(k - gen_pent(i))) i += 1 partitions.insert(k,total) return total It uses this method to calculate partitions: p(k) = p(k − 1) + p(k − 2) − p(k − 5) − p(k − 7) + p(k − 12) + p(k − 15) ... (source: Wikipedia) However, the code is taking quite some time when it comes to large numbers (over p(10^3)). I want to ask you if I can optimize my code, or hint me to a different but faster algorithm or approach. Any optimization suggestions are welcome. And no, before you ask, this is not for homework or Project Euler, its for the experience value. A: Here are some comments. Note that I am no expert on this stuff, by I too like messing about with maths (and Project Euler). I have redefined the pentagonal number functions as follows: def pent_new(n): return (n*(3*n - 1))/2 def gen_pent_new(n): if n%2: i = (n + 1)/2 else: i = -n/2 return pent_new(i) I have written them in such a way that I don't introduce floating point calculations - for large n using floats will introduce errors (compare the results for n = 100000001). You can use the timeit module to test small snippets of code. When I tested all pentagonal functions (yours and mine), the results for mine were quicker. The following is an example which tests your gen_pent function. # Add this code to your script t = Timer("for i in xrange(1, 100): gen_pent(i)", "from __main__ import gen_pent") print t.timeit() Here is a slight modification of your partition function. Again, testing with timeit shows that it is faster than your partition function. However, this may be due to the improvements made to the pentagonal number functions. def partition_new(n): try: return partitions_new[n] except IndexError: total, sign, i = 0, 1, 1 k = gen_pent_new(i) while n - k >= 0: total += sign*partition_new(n - k) i += 1 if i%2: sign *= -1 k = gen_pent_new(i) partitions_new.insert(n, total) return total In your partition function, you calculate the general pentagonal number twice for each loop. Once to test in the while condition, and the other to update total. I store the result in a variable, so only make the calculation once per loop. Using the cProfile module (for python >= 2.5, otherwise the profile module) you can see where your code spends most of its time. Here is an example based on your partition function. import cProfile import pstats cProfile.run('partition(70)', 'partition.test') p = pstats.Stats('partition.test') p.sort_stats('name') p.print_stats() This produced the following output in the console window: C:\Documents and Settings\ags97128\Desktop>test.py Fri Jul 02 12:42:15 2010 partition.test 4652 function calls (4101 primitive calls) in 0.015 CPU seconds Ordered by: function name ncalls tottime percall cumtime percall filename:lineno(function) 552 0.001 0.000 0.001 0.000 {len} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 60 0.000 0.000 0.000 0.000 {method 'insert' of 'list' objects} 1 0.000 0.000 0.015 0.015 <string>:1(<module>) 1162 0.002 0.000 0.002 0.000 {round} 1162 0.006 0.000 0.009 0.000 C:\Documents and Settings\ags97128\Desktop\test.py:11(gen_pent) 552/1 0.005 0.000 0.015 0.015 C:\Documents and Settings\ags97128\Desktop\test.py:26(partition) 1162 0.002 0.000 0.002 0.000 C:\Documents and Settings\ags97128\Desktop\test.py:5(pent) Now profiling my partition function: Fri Jul 02 12:50:10 2010 partition.test 1836 function calls (1285 primitive calls) in 0.006 CPU seconds Ordered by: function name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 60 0.000 0.000 0.000 0.000 {method 'insert' of 'list' objects} 1 0.000 0.000 0.006 0.006 <string>:1(<module>) 611 0.002 0.000 0.003 0.000 C:\Documents and Settings\ags97128\Desktop\test.py:14(gen_pent_new) 552/1 0.003 0.000 0.006 0.006 C:\Documents and Settings\ags97128\Desktop\test.py:40(partition_new) 611 0.001 0.000 0.001 0.000 C:\Documents and Settings\ags97128\Desktop\test.py:8(pent_new) You can see in my results there are no calls to the len and round builtin functions. And I have nearly halved the number of calls to the pentagonal functions (gen_pent_new and pent_new) There are probably other tricks to improving the speed of python code. I would search here for 'python optimization' to see what you can find. Finally, one of the links at the bottom of the wikipedia page you mentioned is an academic paper on fast algorithms for calculating partition numbers. A quick glance shows it contains pseudocode for the algorithms. These algorithms will probably be faster than anything you or I could produce.
Optimizing a Partition Function
Here is the code, in python: # function for pentagonal numbers def pent (n): return int((0.5*n)*((3*n)-1)) # function for generalized pentagonal numbers def gen_pent (n): return pent(int(((-1)**(n+1))*(round((n+1)/2)))) # array for storing partitions - first ten already stored partitions = [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42] # function to generate partitions def partition (k): if (k < len(partitions)): return partitions[k] total, sign, i = 0, 1, 1 while (k - gen_pent(i)) >= 0: sign = (-1)**(int((i-1)/2)) total += sign*(partition(k - gen_pent(i))) i += 1 partitions.insert(k,total) return total It uses this method to calculate partitions: p(k) = p(k − 1) + p(k − 2) − p(k − 5) − p(k − 7) + p(k − 12) + p(k − 15) ... (source: Wikipedia) However, the code is taking quite some time when it comes to large numbers (over p(10^3)). I want to ask you if I can optimize my code, or hint me to a different but faster algorithm or approach. Any optimization suggestions are welcome. And no, before you ask, this is not for homework or Project Euler, its for the experience value.
[ "Here are some comments. Note that I am no expert on this stuff, by I too like messing about with maths (and Project Euler).\nI have redefined the pentagonal number functions as follows:\ndef pent_new(n):\n return (n*(3*n - 1))/2\n\ndef gen_pent_new(n):\n if n%2:\n i = (n + 1)/2\n else:\n i =...
[ 6 ]
[]
[]
[ "optimization", "partitioning", "python" ]
stackoverflow_0003164305_optimization_partitioning_python.txt
Q: python/matplotlib - parasite twin axis scaling Trying to plot a spectrum, ie, velocity versus intensity, with lower x axis = velocity, on the upper twin axis = frequency The relationship between them (doppler formula) is f = (1-v/c)*f_0 where f is the resulting frequency, v the velocity, c the speed of light, and f_0 the frequency at v=0, ie. the v_lsr. I have tried to solve it by looking at http://matplotlib.sourceforge.net/examples/axes_grid/parasite_simple2.html , where it is solved by pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5 aux_trans = matplotlib.transforms.Affine2D().scale(pm_to_kms, 1.) ax_pm = ax_kms.twin(aux_trans) ax_pm.set_viewlim_mode("transform") my problem is, how do I replace the pm_to_kms with my function for frequency? Anyone know how to solve this? A: The solution I ended up using was: ax_hz = ax_kms.twiny() x_1, x_2 = ax_kms.get_xlim() # i want the frequency in GHz so, divide by 1e9 ax_hz.set_xlim(calc_frequency(x_1,data.restfreq/1e9),calc_frequency(x_2,data.restfreq/1e9)) This works perfect, and much less complicated solution. EDIT : Found a very fancy answer. EDIT2 : Changed the transform call according to the comment by @u55 This basically involves defining our own conversion/transform. Because of the excellent AstroPy Units equivalencies, it becomes even easier to understand and more illustrative. from matplotlib import transforms as mtransforms import astropy.constants as co import astropy.units as un import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') from mpl_toolkits.axes_grid.parasite_axes import SubplotHost class Freq2WavelengthTransform(mtransforms.Transform): input_dims = 1 output_dims = 1 is_separable = False has_inverse = True def __init__(self): mtransforms.Transform.__init__(self) def transform_non_affine(self, fr): return (fr*un.GHz).to(un.mm, equivalencies=un.spectral()).value def inverted(self): return Wavelength2FreqTransform() class Wavelength2FreqTransform(Freq2WavelengthTransform): input_dims = 1 output_dims = 1 is_separable = False has_inverse = True def __init__(self): mtransforms.Transform.__init__(self) def transform_non_affine(self, wl): return (wl*un.mm).to(un.GHz, equivalencies=un.spectral()).value def inverted(self): return Freq2WavelengthTransform() aux_trans = mtransforms.BlendedGenericTransform(Wavelength2FreqTransform(), mtransforms.IdentityTransform()) fig = plt.figure(2) ax_GHz = SubplotHost(fig, 1,1,1) fig.add_subplot(ax_GHz) ax_GHz.set_xlabel("Frequency (GHz)") xvals = np.arange(199.9, 999.9, 0.1) # data, noise + Gaussian (spectral) lines data = np.random.randn(len(xvals))*0.01 + np.exp(-(xvals-300.)**2/100.)*0.5 + np.exp(-(xvals-600.)**2/400.)*0.5 ax_mm = ax_GHz.twin(aux_trans) ax_mm.set_xlabel('Wavelength (mm)') ax_mm.set_viewlim_mode("transform") ax_mm.axis["right"].toggle(ticklabels=False) ax_GHz.plot(xvals, data) ax_GHz.set_xlim(200, 1000) plt.draw() plt.show() This now produces the desired results: A: Your "linear function" is a "simple scaling law" (with an offset). Just replace the pm_to_kms definition with your function.
python/matplotlib - parasite twin axis scaling
Trying to plot a spectrum, ie, velocity versus intensity, with lower x axis = velocity, on the upper twin axis = frequency The relationship between them (doppler formula) is f = (1-v/c)*f_0 where f is the resulting frequency, v the velocity, c the speed of light, and f_0 the frequency at v=0, ie. the v_lsr. I have tried to solve it by looking at http://matplotlib.sourceforge.net/examples/axes_grid/parasite_simple2.html , where it is solved by pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5 aux_trans = matplotlib.transforms.Affine2D().scale(pm_to_kms, 1.) ax_pm = ax_kms.twin(aux_trans) ax_pm.set_viewlim_mode("transform") my problem is, how do I replace the pm_to_kms with my function for frequency? Anyone know how to solve this?
[ "The solution I ended up using was:\nax_hz = ax_kms.twiny()\nx_1, x_2 = ax_kms.get_xlim()\n# i want the frequency in GHz so, divide by 1e9\nax_hz.set_xlim(calc_frequency(x_1,data.restfreq/1e9),calc_frequency(x_2,data.restfreq/1e9))\n\nThis works perfect, and much less complicated solution.\nEDIT : Found a very fanc...
[ 5, 0 ]
[]
[]
[ "axes", "matplotlib", "python" ]
stackoverflow_0003148808_axes_matplotlib_python.txt
Q: Is there any way to make Tkinter look less windows 95ish? I was wondering if there was a way to make tkinter more aesthetically pleasing. A: The ttk module is in the upcoming Python 2.7 release. A: You can try PyGtk or PyQt, both have very nice python bindings from what i have heard. There's also the possibility of Tile, which is getting integrated into tkinter in the (near?) future. So, choose another GUI toolkit, or wait :). A: If you don't want to use an alpha version of Python to get ttk, you can download and use the pyttk library from the package index (or use easy_install to get it of course).
Is there any way to make Tkinter look less windows 95ish?
I was wondering if there was a way to make tkinter more aesthetically pleasing.
[ "The ttk module is in the upcoming Python 2.7 release.\n", "You can try PyGtk or PyQt, both have very nice python bindings from what i have heard. There's also the possibility of Tile, which is getting integrated into tkinter in the (near?) future.\nSo, choose another GUI toolkit, or wait :). \n", "If you don't...
[ 3, 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003162662_python_tkinter.txt
Q: import statement mess in python I want to have a number of files imported in a general python file and then include that file when I need the imported modules in the current module. This of course will lead to errors and re-imports if using the from x import y, however when using the "normal" import statement I end up with long instruction statements, for example: x = importModule.directoryName1.directoryName2.moduleName.ClassName() whereas I'd like to do the following: x = importModule.ClassName() but as I said before, doing this: from importModule.directoryName1.directoryName2.moduleNam import ClassName in a general file doesn't work since I include importModule in ClassName. So, I'm basically wondering if there's anyway around this (something like an using statement, such as the one in C++, perhaps?) A: It sounds like you've got recursive imports (importModule refers to moduleName, and moduleName refers to importModule. If you refactor, you should be able to use from importModule.directoryName1.directoryName2.moduleName import ClassName To refactor, you can change the order in which things are imported in moduleName so that the class definition of ClassName occurs before the importModule import; as long as each file defines the references needed by the other module before they try and import the other module, things will work out. Another way to refactor: you could always import ClassName within the function where it's used; as long as the function isn't called before moduleName is imported, you'll be fine. The best way to refactor, though, is to move some classes or references into their own module, so you don't have any situation where A imports B and B imports A. That will fix your problem, as well as make it easier to maintain things going forward. A: Well, you could do from importModule.directoryName1.directoryName2 import moduleName as importModule but that's kind of ugly and very confusing, and won't score you a lot of points with the Python programmers who read your code later.
import statement mess in python
I want to have a number of files imported in a general python file and then include that file when I need the imported modules in the current module. This of course will lead to errors and re-imports if using the from x import y, however when using the "normal" import statement I end up with long instruction statements, for example: x = importModule.directoryName1.directoryName2.moduleName.ClassName() whereas I'd like to do the following: x = importModule.ClassName() but as I said before, doing this: from importModule.directoryName1.directoryName2.moduleNam import ClassName in a general file doesn't work since I include importModule in ClassName. So, I'm basically wondering if there's anyway around this (something like an using statement, such as the one in C++, perhaps?)
[ "It sounds like you've got recursive imports (importModule refers to moduleName, and moduleName refers to importModule. If you refactor, you should be able to use \nfrom importModule.directoryName1.directoryName2.moduleName import ClassName\n\nTo refactor, you can change the order in which things are imported in m...
[ 3, 2 ]
[]
[]
[ "import", "python", "using_statement" ]
stackoverflow_0003165881_import_python_using_statement.txt
Q: Having PyQt app controlling all. How use reactor? I've a django application, served via Twisted, which also serves ohter services (three sockets, mainly). I need to have it working under windows, and I decide to write a PyQt4 application which acts quite like Apache Service Monitor for windows. I was not able to connect twisted reactor to pyqt application reactor, so any hint on this will be welcome too. Now I've this kind of architecture: QMainWindow which, in __ init __() has the log.addObserver(callBack) function, and the widget. Twisted initializer class which extends QtCore.QThread and works in a different thread. the django app which runs over Twisted. I need to understand how to run the reactor, becouse calling reactor.start() from QtCore.QThread works not at all, giving me: exceptions.ValueError: signal only works in main thread Also I'm asking your opinion on the design of applications, does it makes sense for you? A: I'm not sure I totally understand your design but what I can say is that you need to use only one reactor in an application. The reactor is the main (event) loop of the application. And, I think, this reactor should be the QTReactor in your case.
Having PyQt app controlling all. How use reactor?
I've a django application, served via Twisted, which also serves ohter services (three sockets, mainly). I need to have it working under windows, and I decide to write a PyQt4 application which acts quite like Apache Service Monitor for windows. I was not able to connect twisted reactor to pyqt application reactor, so any hint on this will be welcome too. Now I've this kind of architecture: QMainWindow which, in __ init __() has the log.addObserver(callBack) function, and the widget. Twisted initializer class which extends QtCore.QThread and works in a different thread. the django app which runs over Twisted. I need to understand how to run the reactor, becouse calling reactor.start() from QtCore.QThread works not at all, giving me: exceptions.ValueError: signal only works in main thread Also I'm asking your opinion on the design of applications, does it makes sense for you?
[ "I'm not sure I totally understand your design but what I can say is that you need to use only one reactor in an application. The reactor is the main (event) loop of the application. And, I think, this reactor should be the QTReactor in your case.\n" ]
[ 1 ]
[]
[]
[ "django", "pyqt4", "python", "reactor", "twisted" ]
stackoverflow_0003165742_django_pyqt4_python_reactor_twisted.txt
Q: how to display a numpy array with pyglet? I have a label matrix with dimension (100*100), stored as a numpy array, and I would like to display the matrix with pyglet. My original idea is to use this matrix to form a new pyglet image using function pyglet.image.ImageData(). It requres a buffer of the imagedata as an input, however I have no idea how to get a right formated buffer from the numpy array. Any one have any idea? ps. my current solution: 3d_label = numpy.empty([100,100,3]) 3d_label[:,:,0] = label * 255 # value range of label is [0,1] 3d_label[:,:,1] = label * 255 3d_label[:,:,2] = label * 255 image_data = ctypes.string_at(id(3d_label.tostring())+20, 100*100*3) image = pyglet.image.ImageData(100, 100, 'RGB', image_data, -100*3) Any better way to construct a [100*100*3] matrix from 3 [100*100] matrix with numpy? A: I think what you are looking for is np.dstack (or more generally, np.concatenate): label255=label*255 label3=numpy.dstack((label255,label255,label255)) This shows dstack produces the same array (label3) as your construction for label_3d: import numpy as np label=np.random.random((100,100)) label255=label*255 label3=np.dstack((label255,label255,label255)) label_3d = np.empty([100,100,3]) label_3d[:,:,0] = label * 255 # value range of label is [0,1] label_3d[:,:,1] = label * 255 label_3d[:,:,2] = label * 255 print(np.all(label3==label_3d)) # True PS. I'm not sure, but have you tried using label3.data instead of ctypes.string_at(id(label3.tostring())+20, 100*100*3) ? A: You can get the memory representation of your array with 3d_label.tostring(). The tostring() method allows you to change the memory ordering of the elements: Parameters ---------- order : {'C', 'F', None}, optional Order of the data for multidimensional arrays: C, Fortran, or the same as for the original array. PS: The 3d_label.data of ~unutbu requires less memory, since no string is constructed. However, it does not allow you to change the order in which the elements are output.
how to display a numpy array with pyglet?
I have a label matrix with dimension (100*100), stored as a numpy array, and I would like to display the matrix with pyglet. My original idea is to use this matrix to form a new pyglet image using function pyglet.image.ImageData(). It requres a buffer of the imagedata as an input, however I have no idea how to get a right formated buffer from the numpy array. Any one have any idea? ps. my current solution: 3d_label = numpy.empty([100,100,3]) 3d_label[:,:,0] = label * 255 # value range of label is [0,1] 3d_label[:,:,1] = label * 255 3d_label[:,:,2] = label * 255 image_data = ctypes.string_at(id(3d_label.tostring())+20, 100*100*3) image = pyglet.image.ImageData(100, 100, 'RGB', image_data, -100*3) Any better way to construct a [100*100*3] matrix from 3 [100*100] matrix with numpy?
[ "I think what you are looking for is np.dstack (or more generally, np.concatenate):\nlabel255=label*255\nlabel3=numpy.dstack((label255,label255,label255))\n\nThis shows dstack produces the same array (label3) as your construction for label_3d:\nimport numpy as np\n\nlabel=np.random.random((100,100))\nlabel255=label...
[ 5, 1 ]
[]
[]
[ "numpy", "pyglet", "python" ]
stackoverflow_0003165379_numpy_pyglet_python.txt
Q: Can ( s is "" ) and ( s == "" ) ever give different results in Python 2.6.2? As any Python programmer knows, you should use == instead of is to compare two strings for equality. However, are there actually any cases where ( s is "" ) and ( s == "" ) will give different results in Python 2.6.2? I recently came across code that used ( s is "" ) in code review, and while pointing out that this was incorrect I wanted to give an example of how this could fail. But try as I might, I can't construct two empty strings with different identities. It seems that the Python implementation must special-case the empty string in lots of common operations. For example: >>> a = "" >>> b = "abc"[ 2:2 ] >>> c = ''.join( [] ) >>> d = re.match( '()', 'abc' ).group( 1 ) >>> e = a + b + c + d >>> a is b is c is d is e True However, this question suggests that there are cases where ( s is "" ) and ( s == "" ) can be different. Can anyone give me an example? A: Python is tests the objects identity and not equality. Here is an example where using is and == gives a different result: >>> s=u"" >>> print s is "" False >>> print s=="" True A: As everyone else has said, don't rely on undefined behaviour. However, since you asked for a specific counterexample for Python 2.6, here it is: >>> s = u"\xff".encode('ascii', 'ignore') >>> s '' >>> id(s) 10667744 >>> id("") 10666064 >>> s == "" True >>> s is "" False >>> type(s) is type("") True The only time that Python 2.6 can end up with an empty string which is not the normal empty string is when it does a string operation and it isn't sure about in advance how long the string will be. So when you encode a string the error handler can end up stripping characters and fixes up the buffer size after it has completed. Of course that's an oversight and could easily change in Python 2.7. A: You shouldn't care. Unlike None which is defined to be a singleton, there is no rule that says there is only one empty string object. So the result of s is "" is implementation-dependent and using is is a NO-NO whether you can find an example or not. A: It seems to work for anything which actually is a string, but something which just looks like a string (e.g. a unicode or subclass of str or something similar) will fail. >>> class mysub(str): def __init__(self, *args, **kwargs): super(mysub, self).__init__(*args, **kwargs) >>> >>> q = mysub("") >>> q is "" False >>> q == "" True edit: For the purposes of code review & feedback I would suggest that it was bad practice because it implements an unexpected test (even if we ignore the uncertainty of whether it will always behave the same when the types match). if x is "" Implies that x is of the correct value and type, but without an explicit test of type which would warn future maintainers or api users, etc. if x == "" Implies that x is just of the correct value A: You can't find a example because some things are unique and not muteable - so Python keeps them around exactly once and therefore is works. These include (), '',u'', True, False, None CPython even keeps a few frequently used numbers, ie 0, 0.0, 1, 1.0, A: Probably no, CPython seems to optimize spurious instances of "" away in all cases. But as the others say, don't rely on that. A: Undefined behavior is a murky issue. There are things the Python specification defines and adhering implementations must conform to, and there are things left to choice. You may get convinced, by looking into the source code of Python, that this behavior can never happen for actual string objects (unlike unicode vs. non-unicode and other close-but-irrelevant examples shown). Happy, you will leave such a test in a code. But the Python implementation doesn't guarantee it will always work. Some future implementation may cause it to change and you'll have a painful incompatibility. So the rule of thumb with this is simple: don't do it. Use operators only for their intended and well documented use. Don't rely on artifacts of implementation that may very well change in the future.
Can ( s is "" ) and ( s == "" ) ever give different results in Python 2.6.2?
As any Python programmer knows, you should use == instead of is to compare two strings for equality. However, are there actually any cases where ( s is "" ) and ( s == "" ) will give different results in Python 2.6.2? I recently came across code that used ( s is "" ) in code review, and while pointing out that this was incorrect I wanted to give an example of how this could fail. But try as I might, I can't construct two empty strings with different identities. It seems that the Python implementation must special-case the empty string in lots of common operations. For example: >>> a = "" >>> b = "abc"[ 2:2 ] >>> c = ''.join( [] ) >>> d = re.match( '()', 'abc' ).group( 1 ) >>> e = a + b + c + d >>> a is b is c is d is e True However, this question suggests that there are cases where ( s is "" ) and ( s == "" ) can be different. Can anyone give me an example?
[ "Python is tests the objects identity and not equality. Here is an example where using is and == gives a different result:\n>>> s=u\"\"\n>>> print s is \"\"\nFalse\n>>> print s==\"\"\nTrue\n\n", "As everyone else has said, don't rely on undefined behaviour. However, since you asked for a specific counterexample f...
[ 12, 11, 7, 3, 1, 0, 0 ]
[]
[]
[ "equality", "identity", "python", "string" ]
stackoverflow_0003165300_equality_identity_python_string.txt
Q: How to use OR using Django's model filter system? It seems that Django's object model filter method automatically uses the AND SQL keyword. For example: >>> Publisher.objects.filter(name__contains="press", country__contains="U.S.A") will automatically translate into something like: SELECT ... FROM publisher WHERE name LIKE '%press%' AND country LIKE '%U.S.A.%' However, I was wondering whether there was a way to make that 'AND' an 'OR'? I can't seem to find it in the documentation (oddly enough, searching for 'or' isn't really useful). A: You can use Q objects to do what you want, by bitwise OR-ing them together: from django.db.models import Q Publisher.objects.filter(Q(name__contains="press") | Q(country__contains="U.S.A"))
How to use OR using Django's model filter system?
It seems that Django's object model filter method automatically uses the AND SQL keyword. For example: >>> Publisher.objects.filter(name__contains="press", country__contains="U.S.A") will automatically translate into something like: SELECT ... FROM publisher WHERE name LIKE '%press%' AND country LIKE '%U.S.A.%' However, I was wondering whether there was a way to make that 'AND' an 'OR'? I can't seem to find it in the documentation (oddly enough, searching for 'or' isn't really useful).
[ "You can use Q objects to do what you want, by bitwise OR-ing them together:\nfrom django.db.models import Q\nPublisher.objects.filter(Q(name__contains=\"press\") | Q(country__contains=\"U.S.A\"))\n\n" ]
[ 82 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0003166361_django_python_sql.txt
Q: Python project architecture I'm a java developer new to python. In java, you can access all classes in the same directory without having to import them. I am trying to achieve the same behavior in python. Is this possible? I've tried various solutions, for example by importing everything in a file which I import everywhere. That works, but I have to type myClass = rootFolder.folder2.folder3.MyClass() each time I want to access a foreign class. Could you show me an example for how a python architecture over several directories works? Do you really have to import all the classes you need in each file? Imagine that I'm writing a web framework. Will the users of the framework have to import everything they need in their files? A: Put everything into a folder (doesn't matter the name), and make sure that that folder has a file named __init__.py (the file can be empty). Then you can add the following line to the top of your code: from myfolder import * That should give you access to everything defined in that folder without needing to give the prefix each time. You can also have multiple depths of folders like this: from folder1.folder2 import * Let me know if this is what you were looking for.
Python project architecture
I'm a java developer new to python. In java, you can access all classes in the same directory without having to import them. I am trying to achieve the same behavior in python. Is this possible? I've tried various solutions, for example by importing everything in a file which I import everywhere. That works, but I have to type myClass = rootFolder.folder2.folder3.MyClass() each time I want to access a foreign class. Could you show me an example for how a python architecture over several directories works? Do you really have to import all the classes you need in each file? Imagine that I'm writing a web framework. Will the users of the framework have to import everything they need in their files?
[ "Put everything into a folder (doesn't matter the name), and make sure that that folder has a file named __init__.py (the file can be empty).\nThen you can add the following line to the top of your code:\nfrom myfolder import *\n\nThat should give you access to everything defined in that folder without needing to g...
[ 2 ]
[]
[]
[ "architecture", "python" ]
stackoverflow_0003166347_architecture_python.txt
Q: Overriding Django Admin's main page? - Django I'm trying to add features to Django 1.2 admin's main page. I've been playing with index.html, but features added to this page affect all app pages. Any ideas on what template I'm supposed to use? Thanks loads!! A: You can use template hierarchy like: index.html ... {% block content %} ... {% block mycontent %}My custom text{% endblock %} ... {% endblock %} app_index.html ... {% block mycontent %}{% endblock %} .. A: I have done this by modifying the admin/index.html template. You may also need to modify admin/base_site.html (depending on what you want to do, exactly). These templates are found in the django/contrib/admin/templates/admin folder in a Django installation. Update: That's exactly what I've done, see the screenshot fragment below. The section marked in red is the section I added, via HTML in admin/index.html. However, you don't say which version of Django you're using - my example is from a 1.0 installation. A: According to http://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-vs-replacing-an-admin-template you will want to override admin/app_index.html
Overriding Django Admin's main page? - Django
I'm trying to add features to Django 1.2 admin's main page. I've been playing with index.html, but features added to this page affect all app pages. Any ideas on what template I'm supposed to use? Thanks loads!!
[ "You can use template hierarchy like:\nindex.html\n\n...\n{% block content %}\n...\n{% block mycontent %}My custom text{% endblock %}\n...\n{% endblock %}\n\napp_index.html\n\n...\n {% block mycontent %}{% endblock %}\n..\n\n", "I have done this by modifying the admin/index.html template. You may also need to ...
[ 4, 3, 3 ]
[]
[]
[ "admin", "django", "overriding", "python" ]
stackoverflow_0002896490_admin_django_overriding_python.txt
Q: Is safe to use the shove module to store data in a non blocking program? I'm writing a simple crawler with eventlet and I want to store all the url I retrieve in a simple datastore like shove. Is safe to use it in a non blocking enviroment? A: Since most modules are written in the traditional synchronous/blocking module, unless your module explicitly touts that it is asynchronous, you need to handle it with a callback in your eventlet program. The shove home page doesn't mention anything about the issue, which means its probably going to block on file I/O. You might want to ask the shove development community if there's an async variant. A: It depends whether you are OK with blocking disk I/O. A lot of people accept the blocking aspect of disk I/O even in asynchronous programs, as they regard it as 'fast enough'. If not, you'll have to move the data store handling to another thread or worker threads. Or figure out if your O/S can do non-blocking disk I/O from a single thread and port your database library to that. But that's likely a lot of extra work.
Is safe to use the shove module to store data in a non blocking program?
I'm writing a simple crawler with eventlet and I want to store all the url I retrieve in a simple datastore like shove. Is safe to use it in a non blocking enviroment?
[ "Since most modules are written in the traditional synchronous/blocking module, unless your module explicitly touts that it is asynchronous, you need to handle it with a callback in your eventlet program. The shove home page doesn't mention anything about the issue, which means its probably going to block on file...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003156175_python.txt
Q: python regex: match a string with only one instance of a character Suppose there are two strings: $1 off delicious ham. $1 off delicious $5 ham. In Python, can I have a regex that matches when there is only one $ in the string? I.e., I want the RE to match on the first phrase, but not on the second. I tried something like: re.search(r"\$[0-9]+.*!(\$)","$1 off delicious $5 ham.") ..saying "Match where you see a $ followed by anything EXCEPT for another $." There was no match on the $$ example, but there was also no match on the $ example. Thanks in advance! Simple test method for checking: def test(r): s = ("$1 off $5 delicious ham","$1 off any delicious ham") for x in s: print x print re.search(r,x,re.I) print "" A: >>> import re >>> onedollar = re.compile(r'^[^\$]*\$[^\$]*$') >>> onedollar.match('$1 off delicious ham.') <_sre.SRE_Match object at 0x7fe253c9c4a8> >>> onedollar.match('$1 off delicious $5 ham.') >>> Breakdown of regexp: ^ Anchor at start of string [^\$]* Zero or more characters that are not $ \$ Match a dollar sign [^\$]* Zero or more characters that are not $ $ Anchor at end of string A: >>> '$1 off delicious $5 ham.'.count('$') 2 >>> '$1 off delicious ham.'.count('$') 1 A: You want to use the complement of a character class [^] to match any character other than $: re.match(r"\$[0-9]+[^\$]*$","$1 off delicious $5 ham.") The changes from your original are as follows: .* replaced with [^\$]*. The new term [^\$] means any character other than $ $ appended to string. Forces the match to extend to the end of the string. re.search replaced with re.match. Matches the whole string, rather than any subset of it. A: re.search("^[^$]*\$[^$]*$",test_string) A: ^.*?\$[^$]*$ this should make the trick
python regex: match a string with only one instance of a character
Suppose there are two strings: $1 off delicious ham. $1 off delicious $5 ham. In Python, can I have a regex that matches when there is only one $ in the string? I.e., I want the RE to match on the first phrase, but not on the second. I tried something like: re.search(r"\$[0-9]+.*!(\$)","$1 off delicious $5 ham.") ..saying "Match where you see a $ followed by anything EXCEPT for another $." There was no match on the $$ example, but there was also no match on the $ example. Thanks in advance! Simple test method for checking: def test(r): s = ("$1 off $5 delicious ham","$1 off any delicious ham") for x in s: print x print re.search(r,x,re.I) print ""
[ ">>> import re\n>>> onedollar = re.compile(r'^[^\\$]*\\$[^\\$]*$')\n>>> onedollar.match('$1 off delicious ham.')\n<_sre.SRE_Match object at 0x7fe253c9c4a8>\n>>> onedollar.match('$1 off delicious $5 ham.')\n>>>\n\nBreakdown of regexp:\n^ Anchor at start of string\n[^\\$]* Zero or more characters that are not $\n\\$ ...
[ 11, 7, 2, 1, 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0003166619_python_regex_string.txt
Q: Why does this simple Python script reveal the incorrect answer? I'm again working on Project Euler, this time problem #4. The point of this script is to find the largest palindromic product of two three digit numbers. I thought it was fairly straightforward to solve, but I'm getting an answer that is too low. More specifically, I am getting 580085, and the answer is 906609. Could someone tell me what about this is incorrect? #!/usr/bin/env python # encoding: utf-8 """ P4.py Created by Andrew Levenson on 2010-06-29. Copyright (c) 2010 __MyCompanyName__. All rights reserved. """ import sys import os def main(): for x in range(100, 1000): for y in range(100, 1000): z = str( x * y ) s = str( z[::-1] ) # Reverse z if z == s: t = z print t if __name__ == '__main__': main() A: Your code doesn't make sure it prints the largest product, since there could later be a smaller product which replaces it. To fix it, initialize t to zero, and replace your condition with if z==s and int(z)>t: t = int(z) Or equivalently, if z==s: t = max(t,int(z)) Edit: Fixed int/string issues above. It's a bit cleaner to avoid the conversion to string and back to int like this though: def isPalindrome(x): s = str(x) return s == s[::-1] t = 0 for x in range(100, 1000): for y in range(100, 1000): z = x * y if isPalindrome(z) and z > t: t = z print t A: Here's a tricky but correct way to do it in a single expression...: def main(): print max(p for x in range(100, 1000) for y in range(x, 1000) for p in (x * y,) if str(p) == str(p)[::-1]) The tricky part is the single-item for p clause which plays the role of an assignment (just to stop recomputing that product several times;-). Note that the accepted answer is wrong (as are several others), because it looks for the string "max", which is different from the int max -- try running it, and you'll see!-) A: The problem is to find the largest palindrome. You have nothing here to find the largest, simply the last. You assumed the last one would be the largest, but that isn't so because you are examining the entire ZxZ square of possibilities. For example, you are considering 200*101 after you've considered 101*999. A: Because of the way you're using the 2 for loops you're going to get the number with the largest x value, not the largest product. 906609 = 993 * 913 Then x keeps incrementing and the next palindrome is: 580085 = 995 * 583 You need a variable to keep track of the largest palindrome you've found. def main(): largest = 0 for x in range(100, 1000): for y in range(100, 1000): z = str( x * y ) s = str( z[::-1] ) # Reverse z if z == s: t = int(z) if t > largest: largest = t print largest A: You need to add a check if the one you found is larger than the one you already have. A: I'll add that you can save yourself some time in this test. All 6 digit palindromes must be divisible by 11. Therefore at least one of the factors must be divisible by 11.
Why does this simple Python script reveal the incorrect answer?
I'm again working on Project Euler, this time problem #4. The point of this script is to find the largest palindromic product of two three digit numbers. I thought it was fairly straightforward to solve, but I'm getting an answer that is too low. More specifically, I am getting 580085, and the answer is 906609. Could someone tell me what about this is incorrect? #!/usr/bin/env python # encoding: utf-8 """ P4.py Created by Andrew Levenson on 2010-06-29. Copyright (c) 2010 __MyCompanyName__. All rights reserved. """ import sys import os def main(): for x in range(100, 1000): for y in range(100, 1000): z = str( x * y ) s = str( z[::-1] ) # Reverse z if z == s: t = z print t if __name__ == '__main__': main()
[ "Your code doesn't make sure it prints the largest product, since there could later be a smaller product which replaces it. To fix it, initialize t to zero, and replace your condition with\nif z==s and int(z)>t:\n t = int(z)\n\nOr equivalently,\nif z==s:\n t = max(t,int(z))\n\nEdit: Fixed int/string issues ab...
[ 6, 6, 3, 2, 1, 0 ]
[]
[]
[ "palindrome", "python" ]
stackoverflow_0003145897_palindrome_python.txt
Q: Use 2 sound cards I need to play a sound with sound card "A", while recording another sound using sound card "B". I know how to play or record a sound (using PyAudio), but I don't know how to choose which sound card to use for it. I have the impression that PyAudio doesn't allow choosing the sound card, but I might be wrong (I'm a beginner at Python). A: It appears that PortAudio, the C package that PyAudio wraps, has the ability to choose a sound card. PortAudio has the parameters / methods PaDeviceIndex, Pa_getdeviceCount(), and PaUseHostAPISpecificDeviceSpecification. For some reason, PyAudio does not wrap those parameters / methods.
Use 2 sound cards
I need to play a sound with sound card "A", while recording another sound using sound card "B". I know how to play or record a sound (using PyAudio), but I don't know how to choose which sound card to use for it. I have the impression that PyAudio doesn't allow choosing the sound card, but I might be wrong (I'm a beginner at Python).
[ "It appears that PortAudio, the C package that PyAudio wraps, has the ability to choose a sound card.\nPortAudio has the parameters / methods PaDeviceIndex, Pa_getdeviceCount(), and PaUseHostAPISpecificDeviceSpecification.\nFor some reason, PyAudio does not wrap those parameters / methods.\n" ]
[ 0 ]
[]
[]
[ "python", "soundcard" ]
stackoverflow_0003165200_python_soundcard.txt
Q: Python: How to make object attribute refer call a method I'd like for an attribute call like object.x to return the results of some method, say object.other.other_method(). How can I do this? Edit: I asked a bit soon: it looks like I can do this with object.__dict__['x']=object.other.other_method() Is this an OK way to do this? A: Use the property decorator class Test(object): # make sure you inherit from object @property def x(self): return 4 p = Test() p.x # returns 4 Mucking with the __dict__ is dirty, especially when @property is available. A: Have a look at the built-in property function. A: Use a property http://docs.python.org/library/functions.html#property class MyClass(object): def __init__(self, x): self._x = x def get_x(self): print "in get_x: do something here" return self._x def set_x(self, x): print "in set_x: do something" self._x = x x = property(get_x, set_x) if __name__ == '__main__': m = MyClass(10) # getting x print 'm.x is %s' % m.x # setting x m.x = 5 # getting new x print 'm.x is %s' % m.x A: This will only call other_method once when it is created object.__dict__['x']=object.other.other_method() Instead you could do this object.x = property(object.other.other_method) Which calls other_method everytime object.x is accessed Of course you aren't really using object as a variable name, are you?
Python: How to make object attribute refer call a method
I'd like for an attribute call like object.x to return the results of some method, say object.other.other_method(). How can I do this? Edit: I asked a bit soon: it looks like I can do this with object.__dict__['x']=object.other.other_method() Is this an OK way to do this?
[ "Use the property decorator\nclass Test(object): # make sure you inherit from object\n @property\n def x(self):\n return 4\n\np = Test()\np.x # returns 4\n\nMucking with the __dict__ is dirty, especially when @property is available.\n", "Have a look at the built-in property function.\n", "Use a pro...
[ 50, 11, 6, 4 ]
[]
[]
[ "attributes", "python" ]
stackoverflow_0003166773_attributes_python.txt
Q: Python images display How can I create a python script that runs through the images (1.jpeg-n.jpeg) in a directory on a mac and displays them in a browser OR via another python program? Do I import a file to python and than display in browser? Do I extract the file names 1,2,3,4,5 and add that to a list, which I give to another function that calls a browser and displays? Any help would be great. Thanks! A: Using Tkinter and PIL for this purpose is pretty trivial. Add muskies example to the information from this thread that contains this example: # use a Tkinter label as a panel/frame with a background image # note that Tkinter only reads gif and ppm images # use the Python Image Library (PIL) for other image formats # free from [url]http://www.pythonware.com/products/pil/index.htm[/url] # give Tkinter a namespace to avoid conflicts with PIL # (they both have a class named Image) import Tkinter as tk from PIL import Image, ImageTk root = tk.Tk() root.title('background image') # pick an image file you have .bmp .jpg .gif. .png # load the file and covert it to a Tkinter image object imageFile = "Flowers.jpg" image1 = ImageTk.PhotoImage(Image.open(imageFile)) # get the image size w = image1.width() h = image1.height() # position coordinates of root 'upper left corner' x = 0 y = 0 # make the root window the size of the image root.geometry("%dx%d+%d+%d" % (w, h, x, y)) # root has no image argument, so use a label as a panel panel1 = tk.Label(root, image=image1) panel1.pack(side='top', fill='both', expand='yes') # put a button on the image panel to test it button2 = tk.Button(panel1, text='button2') button2.pack(side='top') # save the panel's image from 'garbage collection' panel1.image = image1 # start the event loop root.mainloop() Of course if you're more familiar with another GUI, go ahead and adapt the example, it shouldn't take much. A: You first have to find all image filenames. You can use os.listdir(...) to get all files in a certain directory, or glob.glob(...) to find all files matching a certain pattern. Showing the images is the second and more challenging part of this. The first option is to open the images in an external program, this can be a web browser. On (most) platforms a command firefox 1.jpeg will open the image 1.jpeg in the Firefox browser. You can use the subprocess module to execute such commands. If you want to show them using a nice GUI, you have to create a GUI using some framework and use this. But if you are a beginner this might be a little bit too difficult for you. For example: import glob import subprocess files = glob.glob('dir/*.jpeg') for file in files: subprocess.call(['firefox', file]) A: muksie's answer already contains very useful advice. If don't want to write the HTML file yourself or want something a little fancier you could use a small script I wrote for the MDP library. This basically allows you to just do: import slideshow slideshow.show_image_slideshow(filenames, image_size=(80,60)) This will create an HTML slideshow and open it in your browser. You can grab just the needed files here (only templet.py and the two slideshow files are needed), which might be better for you than getting the full library. A: It might be a lot easier to just generate a static web page with pictures than building a GUI for displaying pictures. You can just generate a hmtl page, put the images on it and start your web browser with the newly created html file. this gives you some possibilities for layout as well. If you just want a picture in the browser then muksie gave a working example.
Python images display
How can I create a python script that runs through the images (1.jpeg-n.jpeg) in a directory on a mac and displays them in a browser OR via another python program? Do I import a file to python and than display in browser? Do I extract the file names 1,2,3,4,5 and add that to a list, which I give to another function that calls a browser and displays? Any help would be great. Thanks!
[ "Using Tkinter and PIL for this purpose is pretty trivial. Add muskies example to the information from this thread that contains this example:\n# use a Tkinter label as a panel/frame with a background image\n# note that Tkinter only reads gif and ppm images\n# use the Python Image Library (PIL) for other image form...
[ 5, 4, 1, 0 ]
[]
[]
[ "image", "python" ]
stackoverflow_0003166221_image_python.txt
Q: Py-appscript: How can I make message with Mail.app I'm trying to create mail with py-appscript (AppleScript interface for python). I tried following code, from appscript import * mail = app('Mail') msg = mail.make(new=k.outgoing_message, with_properties={'visible':True, 'content':"hello", 'subject':"appscript", 'sender':'taichino@gmail.com' }) but got following error messages, and I couldn't find out any information for that... CommandError: Command failed: OSERROR: -1701 MESSAGE: Some parameter is missing for command. COMMAND: app(u'/Applications/Mail.app').make('outgoing_message', with_properties={'content': 'hello', 'visible': True, 'sender': 'taichino@gmail.com', 'subject': 'appscript'}) Suggestions, please? A: Problem solved by myself, following code works fine. from appscript import * mail = app('Mail') msg = mail.make(new=k.outgoing_message) msg.subject.set("hello"), msg.content.set("appscript") msg.to_recipients.end.make( new=k.to_recipient, with_properties={k.address: 'taichino@gmail.com'} ) msg.send() Insted of setting properties in constructor, set each property separately.
Py-appscript: How can I make message with Mail.app
I'm trying to create mail with py-appscript (AppleScript interface for python). I tried following code, from appscript import * mail = app('Mail') msg = mail.make(new=k.outgoing_message, with_properties={'visible':True, 'content':"hello", 'subject':"appscript", 'sender':'taichino@gmail.com' }) but got following error messages, and I couldn't find out any information for that... CommandError: Command failed: OSERROR: -1701 MESSAGE: Some parameter is missing for command. COMMAND: app(u'/Applications/Mail.app').make('outgoing_message', with_properties={'content': 'hello', 'visible': True, 'sender': 'taichino@gmail.com', 'subject': 'appscript'}) Suggestions, please?
[ "Problem solved by myself, following code works fine.\nfrom appscript import *\n\nmail = app('Mail')\nmsg = mail.make(new=k.outgoing_message)\nmsg.subject.set(\"hello\"),\nmsg.content.set(\"appscript\")\nmsg.to_recipients.end.make(\n new=k.to_recipient,\n with_properties={k.address: 'taichino@gmail.com'}\n)\n...
[ 0 ]
[]
[]
[ "applescript", "python" ]
stackoverflow_0003166175_applescript_python.txt
Q: Cherrypy multithreading example I do know that cherrypy is a multithreaded and also has a threadpool implementation. So I wanted to try an example showing multithreaded behaviour. Now lets say I've my some function in the root class and rest all things are configured def testPage(self, *args, **kwargs): current = threading.currentThread() print 'Starting ' , current time.sleep(5) print 'Ending ' ,current return '<html>Hello World</html>' Now lets say I run my page as http://localhost:6060/root/testPage in 3-4 tabs of browser. What result I get is Starting <WorkerThread(CP WSGIServer Thread-10, started 4844)> Ending <WorkerThread(CP WSGIServer Thread-10, started 4844)> Starting <WorkerThread(CP WSGIServer Thread-7, started 4841)> Ending <WorkerThread(CP WSGIServer Thread-7, started 4841)> Starting <WorkerThread(CP WSGIServer Thread-10, started 4844)> Ending <WorkerThread(CP WSGIServer Thread-10, started 4844)> The thing I can clearly understand that it's creating new threads for processing every new request but I cannot figure out why every time I get starting...ending..starting..ending and why not starting...starting..ending..ending sometimes Because what my assumption is that time.sleep will make some thread to suspend and other one can execute at that time. A: This is almost certainly a limitation of your browser and not of CherryPy. Firefox 2, for example, will make no more than 2 concurrent requests to the same domain, even with multiple tabs. And if each tab is also fetching a favicon...that leaves one hit at a time on your handler. See http://www.cherrypy.org/ticket/550 for a ticket with similar source code, and a longer proof.
Cherrypy multithreading example
I do know that cherrypy is a multithreaded and also has a threadpool implementation. So I wanted to try an example showing multithreaded behaviour. Now lets say I've my some function in the root class and rest all things are configured def testPage(self, *args, **kwargs): current = threading.currentThread() print 'Starting ' , current time.sleep(5) print 'Ending ' ,current return '<html>Hello World</html>' Now lets say I run my page as http://localhost:6060/root/testPage in 3-4 tabs of browser. What result I get is Starting <WorkerThread(CP WSGIServer Thread-10, started 4844)> Ending <WorkerThread(CP WSGIServer Thread-10, started 4844)> Starting <WorkerThread(CP WSGIServer Thread-7, started 4841)> Ending <WorkerThread(CP WSGIServer Thread-7, started 4841)> Starting <WorkerThread(CP WSGIServer Thread-10, started 4844)> Ending <WorkerThread(CP WSGIServer Thread-10, started 4844)> The thing I can clearly understand that it's creating new threads for processing every new request but I cannot figure out why every time I get starting...ending..starting..ending and why not starting...starting..ending..ending sometimes Because what my assumption is that time.sleep will make some thread to suspend and other one can execute at that time.
[ "This is almost certainly a limitation of your browser and not of CherryPy. Firefox 2, for example, will make no more than 2 concurrent requests to the same domain, even with multiple tabs. And if each tab is also fetching a favicon...that leaves one hit at a time on your handler.\nSee http://www.cherrypy.org/ticke...
[ 2 ]
[]
[]
[ "cherrypy", "multithreading", "python" ]
stackoverflow_0003164560_cherrypy_multithreading_python.txt
Q: Storing XML/HTML files inside a SQLite database - Possible? Is it possible to directly store a XML/HTML file inside a SQLite database? I'm writing a program in python which is supposed to parse XML/HTML files and store the values inside the database. However, the fields inside the XML/HTML files may vary and I thought it would be easier to simply store the entire XML/HTML file inside the database and then parse it only when used. Is this possible with python and SQLite? Or am I approaching this problem from the wrong angle? Thanks in advance! EDIT: Could anyone share a code sample on how one would store the file? I understand that it is possible but I'm unsure on how to go about doing it. A: You can store your XML/HTML file as text without problems in a text column. The obvious downside is that you can't really query for the values in your XML. Edit: Here is an example. Just read your XML file into a variable and store it in the DB like you would store any string, alongside with any other values you want to store. When you want to use the XML, just read it from DB and parse it with an XML parser. # connect to database and create table import sqlite3 conn = sqlite3.connect(":memory:") conn.execute('''create table my_table (value1 integer, value2 integer, xml text)''') # read text from your input file containing xml f = file('/tmp/my_file.xml') xml_string_from_file = f.read() # insert text into database cur = conn.cursor() cur.execute('''insert into my_table (value1, value2, xml) values (?, ?, ?)''', (23, 42, xml_string_from_file)) conn.commit() # read from database into variable cur.execute('''select * from my_table''') xml_string_from_db = cur.fetchone()[2] # parse with the XML parser of your choice from xml.dom.minidom import parseString dom = parseString(xml_string_from_db)
Storing XML/HTML files inside a SQLite database - Possible?
Is it possible to directly store a XML/HTML file inside a SQLite database? I'm writing a program in python which is supposed to parse XML/HTML files and store the values inside the database. However, the fields inside the XML/HTML files may vary and I thought it would be easier to simply store the entire XML/HTML file inside the database and then parse it only when used. Is this possible with python and SQLite? Or am I approaching this problem from the wrong angle? Thanks in advance! EDIT: Could anyone share a code sample on how one would store the file? I understand that it is possible but I'm unsure on how to go about doing it.
[ "You can store your XML/HTML file as text without problems in a text column.\nThe obvious downside is that you can't really query for the values in your XML.\nEdit: \nHere is an example. Just read your XML file into a variable and store it in the DB like you would store any string, alongside with any other values y...
[ 7 ]
[]
[]
[ "python", "sqlite", "xml" ]
stackoverflow_0003167139_python_sqlite_xml.txt
Q: Python dictionaries: changing the order of nesting I have a dictionary, with 300 key value pairs, where each of the keys are integers and the values are dictionaries with three key value pairs. The inner dictionaries all have the same keys, but different values. The whole thing looks pretty much like this: nested_dicts = {1: {'name1':88.4, 'name2':22.1, 'name3':115.7}, 2: {'name1':89.4, 'name2':23.7, 'name3':117.9} ... 300:{'name1':110.1, 'name2':36.6, 'name3':122.4} } If it's not clear from the above example of the data structure, this nested dictionary should probably look like this: better_dict = {'name1': [88.4, 89.4, ..., 110.1], 'name2': [22.1, 23.7, ..., 36.6], 'name3': [115.7, 117.9, ..., 122.4]} So, I'd like to do a transformation from nested_dicts to better_dict. I'm having trouble pulling this off. I've gotten close, but my trouble comes from trying to figure out how to make sure that the resulting lists are in the correct order. That is, the order of the values in the list should correspond to the keys in the outer dictionary of the original nested_dict. Also, my code uses for loops, but I feel like this is a natural application of generators/list comprehensions. Any help would be appreciated. A: After adjusting your input dict to be: >>> nested_dicts {0: {'name2': 22.1, 'name3': 115.7, 'name1': 88.4}, 1: {'name2': 23.7, 'name3': 117.9, 'name1': 89.4}, 2: {'name2': 36.6, 'name3': 122.4, 'name1': 110.1}} >>> for i in sorted(nested_dicts): for k, v in nested_dicts[i].items(): if k not in n: n[k] = [None] * len(nested_dicts) n[k][i] = v >>> n defaultdict(<class 'list'>, {'name2': [22.1, 23.7, 36.6], 'name3': [115.7, 117.9, 122.4], 'name1': [88.4, 89.4, 110.1]}) I have to note that your original structure just needs to be a list of dicts, given restrictions on keys. ETA: your request to preserve key order would necessitate proper indexes in your original nested_dict. That is there needs to be a continuous sequence starting from 0. A: In python2.7+ {n:[nested_dicts[i][n] for i in range(1,301)] for n in ["name1","name2","name3"]} for python2.6 dict((n, [nested_dicts[i][n] for i in range(1,301)]) for n in ["name1","name2","name3"]) note that the positions in your lists are indexed from 0, not 1
Python dictionaries: changing the order of nesting
I have a dictionary, with 300 key value pairs, where each of the keys are integers and the values are dictionaries with three key value pairs. The inner dictionaries all have the same keys, but different values. The whole thing looks pretty much like this: nested_dicts = {1: {'name1':88.4, 'name2':22.1, 'name3':115.7}, 2: {'name1':89.4, 'name2':23.7, 'name3':117.9} ... 300:{'name1':110.1, 'name2':36.6, 'name3':122.4} } If it's not clear from the above example of the data structure, this nested dictionary should probably look like this: better_dict = {'name1': [88.4, 89.4, ..., 110.1], 'name2': [22.1, 23.7, ..., 36.6], 'name3': [115.7, 117.9, ..., 122.4]} So, I'd like to do a transformation from nested_dicts to better_dict. I'm having trouble pulling this off. I've gotten close, but my trouble comes from trying to figure out how to make sure that the resulting lists are in the correct order. That is, the order of the values in the list should correspond to the keys in the outer dictionary of the original nested_dict. Also, my code uses for loops, but I feel like this is a natural application of generators/list comprehensions. Any help would be appreciated.
[ "After adjusting your input dict to be:\n>>> nested_dicts\n{0: {'name2': 22.1, 'name3': 115.7, 'name1': 88.4},\n 1: {'name2': 23.7, 'name3': 117.9, 'name1': 89.4},\n 2: {'name2': 36.6, 'name3': 122.4, 'name1': 110.1}}\n>>> for i in sorted(nested_dicts):\n for k, v in nested_dicts[i].items():\n if k not in...
[ 4, 3 ]
[]
[]
[ "dictionary", "list_comprehension", "python", "sorting" ]
stackoverflow_0003167143_dictionary_list_comprehension_python_sorting.txt
Q: Using Beautiful Soup Python module to replace tags with plain text I am using Beautiful Soup to extract 'content' from web pages. I know some people have asked this question before and they were all pointed to Beautiful Soup and that's how I got started with it. I was able to successfully get most of the content but I am running into some challenges with tags that are part of the content. (I am starting off with a basic strategy of: if there are more than x-chars in a node then it is content). Let's take the html code below as an example: <div id="abc"> some long text goes <a href="/"> here </a> and hopefully it will get picked up by the parser as content </div> results = soup.findAll(text=lambda(x): len(x) > 20) When I use the above code to get at the long text, it breaks (the identified text will start from 'and hopefully..') at the tags. So I tried to replace the tag with plain text as follows: anchors = soup.findAll('a') for a in anchors: a.replaceWith('plain text') The above does not work because Beautiful Soup inserts the string as a NavigableString and that causes the same problem when I use findAll with the len(x) > 20. I can use regular expressions to parse the html as plain text first, clear out all the unwanted tags and then call Beautiful Soup. But I would like to avoid processing the same content twice -- I am trying to parse these pages so I can show a snippet of content for a given link (very much like Facebook Share) -- and if everything is done with Beautiful Soup, I presume it will be faster. So my question: is there a way to 'clear tags' and replace them with 'plain text' using Beautiful Soup. If not, what will be best way to do so? Thanks for your suggestions! Update: Alex's code worked very well for the sample example. I also tried various edge cases and they all worked fine (with the modification below). So I gave it a shot on a real life website and I run into issues that puzzle me. import urllib from BeautifulSoup import BeautifulSoup page = urllib.urlopen('http://www.engadget.com/2010/01/12/kingston-ssdnow-v-dips-to-30gb-size-lower-price/') anchors = soup.findAll('a') i = 0 for a in anchors: print str(i) + ":" + str(a) for a in anchors: if (a.string is None): a.string = '' if (a.previousSibling is None and a.nextSibling is None): a.previousSibling = a.string elif (a.previousSibling is None and a.nextSibling is not None): a.nextSibling.replaceWith(a.string + a.nextSibling) elif (a.previousSibling is not None and a.nextSibling is None): a.previousSibling.replaceWith(a.previousSibling + a.string) else: a.previousSibling.replaceWith(a.previousSibling + a.string + a.nextSibling) a.nextSibling.extract() i = i+1 When I run the above code, I get the following error: 0:<a href="http://www.switched.com/category/ces-2010">Stay up to date with Switched's CES 2010 coverage</a> Traceback (most recent call last): File "parselink.py", line 44, in <module> a.previousSibling.replaceWith(a.previousSibling + a.string + a.nextSibling) TypeError: unsupported operand type(s) for +: 'Tag' and 'NavigableString' When I look at the HTML code, 'Stay up to date.." does not have any previous sibling (I did not how previous sibling worked until I saw Alex's code and based on my testing it looks like it is looking for 'text' before the tag). So, if there is no previous sibling, I am surprised that it is not going through the if logic of a.previousSibling is None and a;nextSibling is None. Could you please let me know what I am doing wrong? -ecognium A: An approach that works for your specific example is: from BeautifulSoup import BeautifulSoup ht = ''' <div id="abc"> some long text goes <a href="/"> here </a> and hopefully it will get picked up by the parser as content </div> ''' soup = BeautifulSoup(ht) anchors = soup.findAll('a') for a in anchors: a.previousSibling.replaceWith(a.previousSibling + a.string) results = soup.findAll(text=lambda(x): len(x) > 20) print results which emits $ python bs.py [u'\n some long text goes here ', u' and hopefully it \n will get picked up by the parser as content\n'] Of course, you'll probably need to take a bit more care, i.e., what if there's no a.string, or if a.previousSibling is None -- you'll need suitable if statements to take care of such corner cases. But I hope this general idea can help you. (In fact you may want to also merge the next sibling if it's a string -- not sure how that plays with your heuristics len(x) > 20, but say for example that you have two 9-character strings with an <a> containing a 5-character strings in the middle, perhaps you'd want to pick up the lot as a "23-characters string"? I can't tell because I don't understand the motivation for your heuristic). I imagine that besides <a> tags you'll also want to remove others, such as <b> or <strong>, maybe <p> and/or <br>, etc...? I guess this, too, depends on what the actual idea behind your heuristics is! A: When I tried to flatten tags in the document, that way, the tags' entire content would be pulled up to its parent node in place (I wanted to reduce the content of a p tag with all sub-paragraphs, lists, div and span, etc. inside but get rid of the style and font tags and some horrible word-to-html generator remnants), I found it rather complicated to do with BeautifulSoup itself since extract() also removes the content and replaceWith() unfortunatetly doesn't accept None as argument. After some wild recursion experiments, I finally decided to use regular expressions either before or after processing the document with BeautifulSoup with the following method: import re def flatten_tags(s, tags): pattern = re.compile(r"<(( )*|/?)(%s)(([^<>]*=\\\".*\\\")*|[^<>]*)/?>"%(isinstance(tags, basestring) and tags or "|".join(tags))) return pattern.sub("", s) The tags argument is either a single tag or a list of tags to be flattened.
Using Beautiful Soup Python module to replace tags with plain text
I am using Beautiful Soup to extract 'content' from web pages. I know some people have asked this question before and they were all pointed to Beautiful Soup and that's how I got started with it. I was able to successfully get most of the content but I am running into some challenges with tags that are part of the content. (I am starting off with a basic strategy of: if there are more than x-chars in a node then it is content). Let's take the html code below as an example: <div id="abc"> some long text goes <a href="/"> here </a> and hopefully it will get picked up by the parser as content </div> results = soup.findAll(text=lambda(x): len(x) > 20) When I use the above code to get at the long text, it breaks (the identified text will start from 'and hopefully..') at the tags. So I tried to replace the tag with plain text as follows: anchors = soup.findAll('a') for a in anchors: a.replaceWith('plain text') The above does not work because Beautiful Soup inserts the string as a NavigableString and that causes the same problem when I use findAll with the len(x) > 20. I can use regular expressions to parse the html as plain text first, clear out all the unwanted tags and then call Beautiful Soup. But I would like to avoid processing the same content twice -- I am trying to parse these pages so I can show a snippet of content for a given link (very much like Facebook Share) -- and if everything is done with Beautiful Soup, I presume it will be faster. So my question: is there a way to 'clear tags' and replace them with 'plain text' using Beautiful Soup. If not, what will be best way to do so? Thanks for your suggestions! Update: Alex's code worked very well for the sample example. I also tried various edge cases and they all worked fine (with the modification below). So I gave it a shot on a real life website and I run into issues that puzzle me. import urllib from BeautifulSoup import BeautifulSoup page = urllib.urlopen('http://www.engadget.com/2010/01/12/kingston-ssdnow-v-dips-to-30gb-size-lower-price/') anchors = soup.findAll('a') i = 0 for a in anchors: print str(i) + ":" + str(a) for a in anchors: if (a.string is None): a.string = '' if (a.previousSibling is None and a.nextSibling is None): a.previousSibling = a.string elif (a.previousSibling is None and a.nextSibling is not None): a.nextSibling.replaceWith(a.string + a.nextSibling) elif (a.previousSibling is not None and a.nextSibling is None): a.previousSibling.replaceWith(a.previousSibling + a.string) else: a.previousSibling.replaceWith(a.previousSibling + a.string + a.nextSibling) a.nextSibling.extract() i = i+1 When I run the above code, I get the following error: 0:<a href="http://www.switched.com/category/ces-2010">Stay up to date with Switched's CES 2010 coverage</a> Traceback (most recent call last): File "parselink.py", line 44, in <module> a.previousSibling.replaceWith(a.previousSibling + a.string + a.nextSibling) TypeError: unsupported operand type(s) for +: 'Tag' and 'NavigableString' When I look at the HTML code, 'Stay up to date.." does not have any previous sibling (I did not how previous sibling worked until I saw Alex's code and based on my testing it looks like it is looking for 'text' before the tag). So, if there is no previous sibling, I am surprised that it is not going through the if logic of a.previousSibling is None and a;nextSibling is None. Could you please let me know what I am doing wrong? -ecognium
[ "An approach that works for your specific example is:\nfrom BeautifulSoup import BeautifulSoup\n\nht = '''\n<div id=\"abc\">\n some long text goes <a href=\"/\"> here </a> and hopefully it \n will get picked up by the parser as content\n</div>\n'''\nsoup = BeautifulSoup(ht)\n\nanchors = soup.findAll('a')\nfor...
[ 4, 1 ]
[]
[]
[ "html_content_extraction", "python" ]
stackoverflow_0002061718_html_content_extraction_python.txt
Q: Fast lookup for dictionary vector to a given vector. High dimensions I'm looking for an answer that scales, but for my specific purpose, I have a 48th dimension vector. This could be represented as an array of 48 integers all between 0 and 255. I have a large dictionary of these vectors, approximately 25 thousand of them. I need to be able to take a vector that may or may not be in my database, and quickly find which vector from the database is closest. By closest, I mean in terms of traditional distance formula. My code will end up in python but this is more a general question. Brute Force is too slow. I need a near dictionary speed lookup. Anyone have an idea? A: I would suggest implementing a kd-tree on which you can perform Nearest neighbour search. The worst case search time for N points in k dimensions is O(k.N^(1-1/k)) so it should scale sublinearly in N. If I have time I will come back to this answer and provide a less terse explanation that Wikipedia's. Since you're working in python this Scipy cookbook entry on kdtrees should help. A: Another technique that will prove useful is locality sensitive hashing: http://en.wikipedia.org/wiki/Locality_sensitive_hashing Its not clear from your question whether you need -exact- nearest neighbors. If you are happy with returning a vector that is approximately the nearest neighbor, there are faster solutions. See here (http://www.cs.umd.edu/~mount/ANN/)
Fast lookup for dictionary vector to a given vector. High dimensions
I'm looking for an answer that scales, but for my specific purpose, I have a 48th dimension vector. This could be represented as an array of 48 integers all between 0 and 255. I have a large dictionary of these vectors, approximately 25 thousand of them. I need to be able to take a vector that may or may not be in my database, and quickly find which vector from the database is closest. By closest, I mean in terms of traditional distance formula. My code will end up in python but this is more a general question. Brute Force is too slow. I need a near dictionary speed lookup. Anyone have an idea?
[ "I would suggest implementing a kd-tree on which you can perform Nearest neighbour search. The worst case search time for N points in k dimensions is O(k.N^(1-1/k)) so it should scale sublinearly in N.\nIf I have time I will come back to this answer and provide a less terse explanation that Wikipedia's. \nSince y...
[ 8, 4 ]
[]
[]
[ "algorithm", "math", "python", "vector" ]
stackoverflow_0003163854_algorithm_math_python_vector.txt
Q: django ORM: make query Possible Duplicate: Django equivalent for count and group by I'm studying django. In my project I'm having trouble with making a query with django ORM: SELECT MIN( id ) AS id, domain, COUNT( * ) AS cnt FROM app_competition WHERE word_id = 1545 GROUP BY domain Help me please make this query A: You need some Aggregation for this! What you need to do in your case is two things: First, use values to force GROUPBY on your query, then annotate your query using the built-in functions Min and Count If my django-orm fu is correct, your query should look something like this: from django.db.models import Min, Count Competition.objects.values('domain').filter(word_id=1545).annotate(id=Min('id'), cnt=Count('id')) Key things to note: You need to place the values call before any annotations to force it to GROUPBY, then the rest is pretty self explanatory. Didn't test the query so I hope I got it right :)
django ORM: make query
Possible Duplicate: Django equivalent for count and group by I'm studying django. In my project I'm having trouble with making a query with django ORM: SELECT MIN( id ) AS id, domain, COUNT( * ) AS cnt FROM app_competition WHERE word_id = 1545 GROUP BY domain Help me please make this query
[ "You need some Aggregation for this!\nWhat you need to do in your case is two things: First, use values to force GROUPBY on your query, then annotate your query using the built-in functions Min and Count\nIf my django-orm fu is correct, your query should look something like this:\nfrom django.db.models import Min, ...
[ 2 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0003167516_django_orm_python.txt
Q: Rename a computer programmatically I need to automate the changing of the hostname of a computer, but I can't figure out how to do it inside a program. My options are open; I would be happy with a solution in any of the following: Command line Java Python C# (would prefer one of the other 3, but this is ok) It would be helpful to learn how to do this on both Linux and Windows. A: For Unix-based systems: Command line: $ hostname "host.domain.com" Python (sort of): import os os.system('hostname "host.domain.com"') A: You could also do this in powershell on windows. Seems safer to me than changing registry keys by hand : $computer = Get-WmiObject Win32_ComputerSystem -OriginalPCname OriginalName -computername $originalPCName $computer.Rename("NEWCOMPUTERNAME") } see this poshcode page A: In Windows you have to modify registry keys and the reboot the system. You actually have to change two entries: HostName under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\TcpIp\Parameters and ComputerName under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName Please note that if the computer ha joined an NT Domain this change could be harmful (and in this case you have an additional entry to change under TcpIp\Parameters).
Rename a computer programmatically
I need to automate the changing of the hostname of a computer, but I can't figure out how to do it inside a program. My options are open; I would be happy with a solution in any of the following: Command line Java Python C# (would prefer one of the other 3, but this is ok) It would be helpful to learn how to do this on both Linux and Windows.
[ "For Unix-based systems:\nCommand line:\n$ hostname \"host.domain.com\"\n\nPython (sort of):\nimport os\nos.system('hostname \"host.domain.com\"')\n\n", "You could also do this in powershell on windows. Seems safer to me than changing registry keys by hand :\n$computer = Get-WmiObject Win32_ComputerSystem -Origin...
[ 3, 2, 0 ]
[]
[]
[ "c#", "hostname", "java", "python" ]
stackoverflow_0003167469_c#_hostname_java_python.txt
Q: Scraping a table using BeautifulSoup I have a question which i suspect is fairly straight forward. I have the following type of page from which I want to collect the information in the last table (if you scroll all the way down it is the one in the box labelled "Procedure"): http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-2&language=EN The html for the table I want to scrape looks like this: <tbody><tr class="doc_title"> <td style="background-image: url(&quot;/img/struct/navigation/gradient_blue.gif&quot;);" align="left" valign="top"><img src="/img/struct/functional/arrow_title_doc.gif" alt="" align="absmiddle" border="0" height="14" width="8"> <span style="font-weight: bold;">PROCEDURE</span></td><td style="background-image: url(&quot;/img/struct/navigation/gradient_blue.gif&quot;);" align="right" valign="top"> <table border="0" cellpadding="3" cellspacing="0" width="50"> <tbody><tr><td align="center"><a href="#top"><img src="/img/struct/functional/top_doc.gif" alt="" border="0" height="16" width="16"></a></td><td align="center"><img src="/img/struct/navigation/spacer.gif" alt="" border="0" height="10" width="15"></td><td align="center"><a href="#title2"><img src="/img/struct/functional/sort_up.gif" alt="" border="0" height="10" width="15"></a></td></tr></tbody></table></td></tr> <tr class="contents" valign="top"><td colspan="2"> <p></p><table style="border-collapse: collapse; width: 481.85pt;" align="center" cellspacing="0"> <tbody><tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Title</span></p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style="">Mutual assistance for the recovery of claims relating to taxes, duties and other measures</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">References</span></p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style=""><a href="http://ec.europa.eu/prelex/liste_resultats.cfm?CL=en&amp;ReqId=0&amp;DocType=COM&amp;DocYear=2009&amp;DocNum=0028">COM(2009)0028</a> – C6-0061/2009 – <a href="/oeil/FindByProcnum.do?lang=en&amp;procnum=CNS/2009/0007">2009/0007(CNS)</a></p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Date of consulting Parliament</span></p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style="">16.2.2009</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Committee responsible</span></p> <p style="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date announced in plenary</p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style="">ECON</p> <p style="">19.10.2009</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0pt 0.75pt; border-style: solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Committee(s) asked for opinion(s)</span></p> <p style="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date announced in plenary</p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.88%;" rowspan="1" colspan="2"> <p style="">CONT</p> <p style="">19.10.2009</p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">JURI</p> <p style="">19.10.2009</p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="border-width: 0.75pt 1pt 0pt 0pt; border-style: solid solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="1"> <p style="">&nbsp;</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Not delivering opinions</span></p> <p style="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date of decision</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.88%;" rowspan="1" colspan="2"> <p style="">CONT</p> <p style="">1.10.2009</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">JURI</p> <p style="">5.10.2009</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0pt; border-style: solid solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="1"> <p style="">&nbsp;</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Rapporteur(s)</span></p> <p style="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date appointed</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 20.59%;" rowspan="1" colspan="3"> <p style="">Theodor Dumitru Stolojan</p> <p style="">21.7.2009</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 20.59%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0pt; border-style: solid solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 20.59%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0pt 0.75pt; border-style: solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Discussed in committee</span></p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.88%;" rowspan="1" colspan="2"> <p style="">10.11.2009</p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">1.12.2009</p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">21.1.2010</p> </td> <td style="border-width: 0.75pt 1pt 0pt 0pt; border-style: solid solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="1"> <p style="">&nbsp;</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Date adopted</span></p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.88%;" rowspan="1" colspan="2"> <p style="">27.1.2010</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0pt; border-style: solid solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="1"> <p style="">&nbsp;</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Result of final vote</span></p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 12.94%;" rowspan="1" colspan="1"> <p style="">+:</p> <p style="">–:</p> <p style="">0:</p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0pt; border-style: solid solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 48.82%;" rowspan="1" colspan="6"> <p style="">39</p> <p style="">0</p> <p style="">1</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Members present for the final vote</span></p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style="">Burkhard Balz, Sharon Bowles, Udo Bullmann, Pascal Canfin, Nikolaos Chountis, George Sabin Cutaş, Leonardo Domenici, Derk Jan Eppink, Markus Ferber, Elisa Ferreira, Vicky Ford, José Manuel García-Margallo y Marfil, Jean-Paul Gauzès, Sylvie Goulard, Enikő Győri, Liem Hoang Ngoc, Eva Joly, Othmar Karas, Wolf Klinz, Jürgen Klute, Werner Langen, Astrid Lulling, Arlene McCarthy, Ivari Padar, Alfredo Pallone, Anni Podimata, Antolín Sánchez Presedo, Olle Schmidt, Edward Scicluna, Peter Simon, Peter Skinner, Theodor Dumitru Stolojan, Ivo Strejček, Kay Swinburne, Marianne Thyssen, Ramon Tremosa i Balcells</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-left: 0.75pt solid rgb(0, 0, 0); border-right: 1pt solid rgb(0, 0, 0); border-top: 0.75pt solid rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Substitute(s) present for the final vote</span></p> </td> <td style="border-left: 0.75pt solid rgb(0, 0, 0); border-right: 1pt solid rgb(0, 0, 0); border-top: 0.75pt solid rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style="">Marta Andreasen, Sophie Briard Auconie, David Casa, Danuta Jazłowiecka, Arturs Krišjānis Kariņš, Philippe Lamberts, Andreas Schwab</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 38.24%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 12.94%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 2.94%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 4.71%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 10.58%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 10%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 5.29%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 15.3%;" rowspan="1" colspan="1"></td> <td style="" rowspan="1" colspan="1"></td></tr> </tbody></table> </td></tr> </tbody> The problem I am facing is that the tags for the tables do not have identifiers (as far as I can tell), so I dont know how to select this one table and scrape the information from it. I have been using BeautifilSoup so far to get other information from the website, but I am at a loss for how to scrape this one table. If anyone can show me how to proceed I would ne most grateful! With kind regards, Thomas A: You can find elements by other attributes if you're a bit clever. I took this shot at scraping your data, and it probably isn't the best – but, it gets you close. The first thing I noticed was you definitely wanted data after the second appearance of the word "PROCEDURE" (first being the link, second being the header). So, I split on that: data = html.split("PROCEDURE", 2)[2] Then, I looked for <td> tags with rowspan=1: bs = BeautifulSoup.BeautifulSoup(data) tds = bs.findAll("td", { "rowspan": 1 }) Getting closer... >>> tds[0].text u'Title' >>> tds[1].text u'Mutual assistance for the recovery of claims relating to taxes, duties and other measures' >>> tds[3].text u'References' >>> tds[4].text u'COM(2009)00282009/0007(CNS)2009 a>' Note that I skipped index 2 in tds, since they use a spacer or something (it's empty). Anyway, that's a start. The real trick I found with BeautifulSoup was to only feed it the data in the area you know you're looking for, because then there's less to skim through. It prides itself on accepting bad-looking input, too, so don't be afraid to feed it garbage. I went a bit further in the list of elements, and it isn't perfect. You'll need to refine the search, since they have <td> elements within <td>s for the values.
Scraping a table using BeautifulSoup
I have a question which i suspect is fairly straight forward. I have the following type of page from which I want to collect the information in the last table (if you scroll all the way down it is the one in the box labelled "Procedure"): http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-2&language=EN The html for the table I want to scrape looks like this: <tbody><tr class="doc_title"> <td style="background-image: url(&quot;/img/struct/navigation/gradient_blue.gif&quot;);" align="left" valign="top"><img src="/img/struct/functional/arrow_title_doc.gif" alt="" align="absmiddle" border="0" height="14" width="8"> <span style="font-weight: bold;">PROCEDURE</span></td><td style="background-image: url(&quot;/img/struct/navigation/gradient_blue.gif&quot;);" align="right" valign="top"> <table border="0" cellpadding="3" cellspacing="0" width="50"> <tbody><tr><td align="center"><a href="#top"><img src="/img/struct/functional/top_doc.gif" alt="" border="0" height="16" width="16"></a></td><td align="center"><img src="/img/struct/navigation/spacer.gif" alt="" border="0" height="10" width="15"></td><td align="center"><a href="#title2"><img src="/img/struct/functional/sort_up.gif" alt="" border="0" height="10" width="15"></a></td></tr></tbody></table></td></tr> <tr class="contents" valign="top"><td colspan="2"> <p></p><table style="border-collapse: collapse; width: 481.85pt;" align="center" cellspacing="0"> <tbody><tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Title</span></p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style="">Mutual assistance for the recovery of claims relating to taxes, duties and other measures</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">References</span></p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style=""><a href="http://ec.europa.eu/prelex/liste_resultats.cfm?CL=en&amp;ReqId=0&amp;DocType=COM&amp;DocYear=2009&amp;DocNum=0028">COM(2009)0028</a> – C6-0061/2009 – <a href="/oeil/FindByProcnum.do?lang=en&amp;procnum=CNS/2009/0007">2009/0007(CNS)</a></p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Date of consulting Parliament</span></p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style="">16.2.2009</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Committee responsible</span></p> <p style="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date announced in plenary</p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style="">ECON</p> <p style="">19.10.2009</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0pt 0.75pt; border-style: solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Committee(s) asked for opinion(s)</span></p> <p style="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date announced in plenary</p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.88%;" rowspan="1" colspan="2"> <p style="">CONT</p> <p style="">19.10.2009</p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">JURI</p> <p style="">19.10.2009</p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="border-width: 0.75pt 1pt 0pt 0pt; border-style: solid solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="1"> <p style="">&nbsp;</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Not delivering opinions</span></p> <p style="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date of decision</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.88%;" rowspan="1" colspan="2"> <p style="">CONT</p> <p style="">1.10.2009</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">JURI</p> <p style="">5.10.2009</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0pt; border-style: solid solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="1"> <p style="">&nbsp;</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Rapporteur(s)</span></p> <p style="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date appointed</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 20.59%;" rowspan="1" colspan="3"> <p style="">Theodor Dumitru Stolojan</p> <p style="">21.7.2009</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 20.59%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0pt; border-style: solid solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 20.59%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0pt 0.75pt; border-style: solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Discussed in committee</span></p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.88%;" rowspan="1" colspan="2"> <p style="">10.11.2009</p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">1.12.2009</p> </td> <td style="border-width: 1pt 0pt 0pt; border-style: solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">21.1.2010</p> </td> <td style="border-width: 0.75pt 1pt 0pt 0pt; border-style: solid solid none none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="1"> <p style="">&nbsp;</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Date adopted</span></p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.88%;" rowspan="1" colspan="2"> <p style="">27.1.2010</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="2"> <p style="">&nbsp;</p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0pt; border-style: solid solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 15.3%;" rowspan="1" colspan="1"> <p style="">&nbsp;</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Result of final vote</span></p> </td> <td style="border-width: 0.75pt 0pt 1pt; border-style: solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 12.94%;" rowspan="1" colspan="1"> <p style="">+:</p> <p style="">–:</p> <p style="">0:</p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0pt; border-style: solid solid solid none; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 48.82%;" rowspan="1" colspan="6"> <p style="">39</p> <p style="">0</p> <p style="">1</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Members present for the final vote</span></p> </td> <td style="border-width: 0.75pt 1pt 0.75pt 0.75pt; border-style: solid; border-color: rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style="">Burkhard Balz, Sharon Bowles, Udo Bullmann, Pascal Canfin, Nikolaos Chountis, George Sabin Cutaş, Leonardo Domenici, Derk Jan Eppink, Markus Ferber, Elisa Ferreira, Vicky Ford, José Manuel García-Margallo y Marfil, Jean-Paul Gauzès, Sylvie Goulard, Enikő Győri, Liem Hoang Ngoc, Eva Joly, Othmar Karas, Wolf Klinz, Jürgen Klute, Werner Langen, Astrid Lulling, Arlene McCarthy, Ivari Padar, Alfredo Pallone, Anni Podimata, Antolín Sánchez Presedo, Olle Schmidt, Edward Scicluna, Peter Simon, Peter Skinner, Theodor Dumitru Stolojan, Ivo Strejček, Kay Swinburne, Marianne Thyssen, Ramon Tremosa i Balcells</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border-left: 0.75pt solid rgb(0, 0, 0); border-right: 1pt solid rgb(0, 0, 0); border-top: 0.75pt solid rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 38.24%;" rowspan="1" colspan="1"> <p style=""><span style="font-weight: bold;">Substitute(s) present for the final vote</span></p> </td> <td style="border-left: 0.75pt solid rgb(0, 0, 0); border-right: 1pt solid rgb(0, 0, 0); border-top: 0.75pt solid rgb(0, 0, 0); padding: 2.8pt 5.1pt; vertical-align: top; width: 61.76%;" rowspan="1" colspan="7"> <p style="">Marta Andreasen, Sophie Briard Auconie, David Casa, Danuta Jazłowiecka, Arturs Krišjānis Kariņš, Philippe Lamberts, Andreas Schwab</p> </td> <td style="" rowspan="1" colspan="1"></td></tr> <tr style=""> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 38.24%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 12.94%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 2.94%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 4.71%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 10.58%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 10%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 5.29%;" rowspan="1" colspan="1"></td> <td style="border: medium none; margin: 0pt; padding: 0pt; width: 15.3%;" rowspan="1" colspan="1"></td> <td style="" rowspan="1" colspan="1"></td></tr> </tbody></table> </td></tr> </tbody> The problem I am facing is that the tags for the tables do not have identifiers (as far as I can tell), so I dont know how to select this one table and scrape the information from it. I have been using BeautifilSoup so far to get other information from the website, but I am at a loss for how to scrape this one table. If anyone can show me how to proceed I would ne most grateful! With kind regards, Thomas
[ "You can find elements by other attributes if you're a bit clever. I took this shot at scraping your data, and it probably isn't the best – but, it gets you close.\nThe first thing I noticed was you definitely wanted data after the second appearance of the word \"PROCEDURE\" (first being the link, second being the ...
[ 3 ]
[]
[]
[ "beautifulsoup", "python", "screen_scraping" ]
stackoverflow_0003167106_beautifulsoup_python_screen_scraping.txt
Q: importing files residing in an unrelated path Consider I have a directory called root that has two directories: x and y. I have a module file that resides in x, let us call that test.py. Now in y, I have a module that needs to call test.py I am doing a simple: from x import test And it works. I was wondering, how this works? EDIT: How it works, as in there was no __init__.py file in x, but yet from y I was able to call a module from there. A: It doesn't. You, or your operating system, or your Python site startup scripts, have modified PYTHONPATH. 14:59 jsmith@upsidedown pwd /Users/jsmith/Test/Test2/root 14:59 jsmith@upsidedown cat x/test.py def hello(): print "hello" 14:59 jsmith@upsidedown cat y/real.py #!/usr/bin/python from x import test test.hello() 14:59 jsmith@upsidedown y/real.py Traceback (most recent call last): File "y/real.py", line 3, in <module> from x import test ImportError: No module named x A: Because there's a path to it. Try this: import sys print sys.path That should output all the places python uses as the starting direcctory to resolve module locations. So for example, if root is actually in /home/PulpFiction/root (or C:\Documents and Settings\PulpFiction\My Documents\root on windows), you'll see something like this: ['', '/usr/local/lib/python2.6/dist-packages', *more stuff*, '/home/PulpFiction/root'] or on windows: ['', 'C:\\python26\\site-packages', *more stuff here*, 'C:\Documents and Settings\PulpFiction\My Documents\root'] There are a few ways sys.path can be set (that I know of): The directory you run the script from Environment variable (PYTHONPATH to be exact) Windows Registry (on windows only obviously) Manually appending a path to the sys.path variable yourself in the code I'm guessing the reason it work for you is you have a script in root (let's say main.py), and that script end up importing from both x and y. Since you're running the script in the root directory it's added to the python path, which allows from x import test to work. EDIT There's no __init__.py eh? You sure there isn't an __init__.pyc there (note the C in pyc)?
importing files residing in an unrelated path
Consider I have a directory called root that has two directories: x and y. I have a module file that resides in x, let us call that test.py. Now in y, I have a module that needs to call test.py I am doing a simple: from x import test And it works. I was wondering, how this works? EDIT: How it works, as in there was no __init__.py file in x, but yet from y I was able to call a module from there.
[ "It doesn't. You, or your operating system, or your Python site startup scripts, have modified PYTHONPATH.\n14:59 jsmith@upsidedown pwd\n/Users/jsmith/Test/Test2/root\n\n14:59 jsmith@upsidedown cat x/test.py\ndef hello():\n print \"hello\"\n\n14:59 jsmith@upsidedown cat y/real.py\n#!/usr/bin/python\nfrom x impo...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003168378_python.txt
Q: Library to render Directed Graphs (similar to graphviz) on Google App Engine I am looking for a Java or Python library that can render graphs in the Dot language as image file. The problem is that I need a library that I can use on Google App Engine. Basically I am looking for a library that can convert the text description of a directed graph into an image of the graph. For example: Covert this edge list: [A,B] [B,C] [A,C] [C,D] Into this image: I used Graphviz for this example, but I know it is not possible for me to use it with Google App Engine. A: Canviz is what you are looking for: it is a JavaScript library for drawing Graphviz graphs to a web browser canvas. It works with most browsers. Using Canviz has advantages for your web application over generating and sending bitmapped images and imagemaps to the browser: The server only needs to have Graphviz generate xdot text; this is faster than generating bitmapped images. Only the xdot text needs to be transferred to the browser; this is smaller than binary image data, and, if the browser supports it (which most do), the text can be gzip- or bzip2-compressed. The web browser performs the drawing, not the server; this reduces server load. The user can resize the graph without needing to involve the server; this is faster than having the server draw and send the graph in a different size. To see it in action, look here. A: Google Charts API now supports GraphViz experimentally. (Note that the entire Image Charts project is officially deprecated.) A: I do not think there is such pure python library, the best you can do is use NetworkX, it can draw using matplotlib or pygraphviz. Maybe you can modify networkx's matplotlib code to draw on server side, here is the code Another problem is google app engine doesn't have any drawing API, but you may simply use SVG to generate such graphs or may be google charts API have something already there. A: You could take a look at the flash based perfuse project if just need to display a graph and not having it embedded as an image is acceptable. They have some example applications of the library such as this Dependency Graph.
Library to render Directed Graphs (similar to graphviz) on Google App Engine
I am looking for a Java or Python library that can render graphs in the Dot language as image file. The problem is that I need a library that I can use on Google App Engine. Basically I am looking for a library that can convert the text description of a directed graph into an image of the graph. For example: Covert this edge list: [A,B] [B,C] [A,C] [C,D] Into this image: I used Graphviz for this example, but I know it is not possible for me to use it with Google App Engine.
[ "Canviz is what you are looking for: it is a JavaScript library for drawing Graphviz graphs to a web browser canvas. It works with most browsers.\n\nUsing Canviz has advantages for your web application over generating and sending bitmapped images and imagemaps to the browser:\n\nThe server only needs to have Graphv...
[ 19, 12, 0, 0 ]
[]
[]
[ "google_app_engine", "graph", "graphviz", "java", "python" ]
stackoverflow_0002264157_google_app_engine_graph_graphviz_java_python.txt
Q: how to extends the parent html page on google app engine templates | ....a.html |.....admin |..... index.html |..... b.html in google app engine templates, i can use this to extends b.html in index.html: {% extends 'b.html' %} but how to extends a.html in index.html. thanks A: You can only have one extends per template. It's like single inheritance in OOP languages like C# and Java. This question has an answer that will give you some good ideas for laying out your templates and having a good template inheritence scheme
how to extends the parent html page on google app engine
templates | ....a.html |.....admin |..... index.html |..... b.html in google app engine templates, i can use this to extends b.html in index.html: {% extends 'b.html' %} but how to extends a.html in index.html. thanks
[ "You can only have one extends per template. It's like single inheritance in OOP languages like C# and Java. \nThis question has an answer that will give you some good ideas for laying out your templates and having a good template inheritence scheme\n" ]
[ 1 ]
[]
[]
[ "extends", "google_app_engine", "python", "templates" ]
stackoverflow_0003168532_extends_google_app_engine_python_templates.txt
Q: Possible to retrieve steam server list in python? I wanted to hear whether it was possible to find a way to retrieve steam servers in python? If so, how could one go about it? A: Valve has documented the Master Server Query Protocol rather well. There is also a Python library called SourceLib that provides an interface to the server list.
Possible to retrieve steam server list in python?
I wanted to hear whether it was possible to find a way to retrieve steam servers in python? If so, how could one go about it?
[ "Valve has documented the Master Server Query Protocol rather well. There is also a Python library called SourceLib that provides an interface to the server list.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003148231_python.txt
Q: Django Custom Template Tags In Google App Engine I am trying to include the following Tag In Google App Engine Web Application: http://www.djangosnippets.org/snippets/1357/ Is there any configuration of this file to make it work with Google App Engine? Cause I followed the Django Template tutorials: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ and have this structure: templatetags/ __init__.py range_template.py in the Template file, I have {%load range_template%} But I am getting the error: TemplateSyntaxError: 'range_template' is not a valid tag library: Could not load template library from django.templatetags.range_template, No module named range_template The other thing that might be a problem why this ain't working is, the INSTALL_APPS settings.py file. Not sure how to configure it. I have a settings.py file in the root of my application and included this: INSTALLED_APPS = ('templatetags') Any advice would be greatly appreciated. A: try doing the following: $ python ./manage.py startapp foo Add foo to installed apps: INSTALLED_APPS += ('foo',) And move your templatetags directory into your foo app. Something like: ./djangoproject __init__.py settings.py urls.py etc.. foo/ __init__.py templatetags/ __init__.py range_template.py Django convention is that template tag code resides in apps, in directories named templatetags (see docs). I assume the same would be true for GAE. A: In case someone searches for this, I wrote a small article in 2008 about this: http://daily.profeth.de/2008/04/using-custom-django-template-helpers.html A: Please make sure to restart the development server after following the above step
Django Custom Template Tags In Google App Engine
I am trying to include the following Tag In Google App Engine Web Application: http://www.djangosnippets.org/snippets/1357/ Is there any configuration of this file to make it work with Google App Engine? Cause I followed the Django Template tutorials: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ and have this structure: templatetags/ __init__.py range_template.py in the Template file, I have {%load range_template%} But I am getting the error: TemplateSyntaxError: 'range_template' is not a valid tag library: Could not load template library from django.templatetags.range_template, No module named range_template The other thing that might be a problem why this ain't working is, the INSTALL_APPS settings.py file. Not sure how to configure it. I have a settings.py file in the root of my application and included this: INSTALLED_APPS = ('templatetags') Any advice would be greatly appreciated.
[ "try doing the following:\n$ python ./manage.py startapp foo\n\nAdd foo to installed apps:\nINSTALLED_APPS += ('foo',)\n\nAnd move your templatetags directory into your foo app. Something like:\n./djangoproject\n __init__.py\n settings.py\n urls.py\n etc..\n foo/\n __init__.py\n templat...
[ 4, 4, 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0000770854_django_google_app_engine_python.txt
Q: how to show a html page in a js file on google app engine $('#upload').click(function(){ $('#main .right').html("{% extends 'a.html' %}") }) but this is error , how to make this code running . thanks A: Let me guess -- your element ends up containing "{% extends 'a.html' %}"? If so, it's because your js file is not being parsed by the template engine. In any case, you might be better served by making this an AJAX request, like the following: $('#upload').click(function() { $.get("a.html", function(data) { $('#main .right').html(data); }); }); If you're feeling unusually fancy, you can add some animation to let the user know that a request is pending. A: $('#upload').click(function(){ $('#main .right').html("{% extends 'a.html' %}") }) Do you mean {% include %}? I can't see what purpose putting an extends inside a script block would serve. If you're actually templating into that {% ... %} block successfully, then you're including a load of HTML content. HTML content usually has lots of newlines and " characters in it, both of which will immediately terminate the JavaScript string literal inside the html() call and cause a big old syntax error. (Other characters that will cause trouble include \ and </.) If you wanted this to work, you'd need to take the output of the a.html template and encode it using JavaScript string literal rules. For a normal string this would be done using the escapejs filter in Django or the json library in general. However I don't think there's any way to do filtering on the output of an {% include %} command. How about including the HTML in a hidden part of the document and showing/hiding it from script?
how to show a html page in a js file on google app engine
$('#upload').click(function(){ $('#main .right').html("{% extends 'a.html' %}") }) but this is error , how to make this code running . thanks
[ "Let me guess -- your element ends up containing \"{% extends 'a.html' %}\"? If so, it's because your js file is not being parsed by the template engine. In any case, you might be better served by making this an AJAX request, like the following:\n$('#upload').click(function() {\n $.get(\"a.html\", function(data)...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "jquery", "python" ]
stackoverflow_0003168498_google_app_engine_jquery_python.txt
Q: Python parsing files I need to know the best approach for the following scenario lets say we have some huge file which logs the output of the compilation and there are couple of error patterns which I want to test against this file, for eg. error patterns could be - : error: - : error [A-Z]*[\d ]* - [A-Z]*[\d]* [E\e|rror: - " Cannot open include file " - " Could not find " - "is not a member of" - "has not been declared" Let me know if this would be efficient: dump the file in some variable and close the file grep for each error from the list or create the regular expression for each of error and parse through the variable Thank you A: If the log file is large, it may not be a good idea to load it to memory. Instead, you may precompile all regular expressions and test against them line by line, e.g.: def has_error(filename): with file(filename, 'r') as logfile: for line in logfile: for regexp in MY_REGEXPS: if regexp.search(line): return True return False A: Given that the log file is large, the (more) efficient way to check for errors would be to iterate through the file one line at a time and check each line against your patterns. You wouldn't want to be holding a huge file in memory unnecessarily. In Python, probably something like this: err = re.compile(': error(?::| [A-Z]*[\d ]*)|[A-Z]*\d* [Ee]rror:|' + '" (?:Cannot open include file|Could not find) "|' + '"(?:is not a member of|has not been declared)"') with open('file.log') as f: for line in f: m = err.search(line) if m is not None: # this line indicates an error though you might have to change the regular expression to suit your needs. An alternative would be to have a list of static strings, e.g. err_list = ['error', 'Cannot open include file', 'Could not find', 'is not a member of', 'has not been declared'] and just search for each string in each line: with open('file.log') as f: for line in f: if any(line.find(e) for e in err_list): # this line indicates an error A: This really wouldn't be efficient as you're reading a huge amount of data into memory and then trying to operate on it. Unless you have a huge amount of memory, it's probably not a good idea. Use a generator instead: def parser(filename): with open(filename, 'r') as f: # For use in python > 2.4 I *think*. for line in f: if anymatches(line): # or whatever you want to do to generate a yield line # true/false value This will have the benefit of not loading the whole file into memory, and also only producing the matches as you ask for them - so if you want only the first N matches you can do this: for i, match in zip(xrange(N), parser('mylogfile')): #do something with match
Python parsing files
I need to know the best approach for the following scenario lets say we have some huge file which logs the output of the compilation and there are couple of error patterns which I want to test against this file, for eg. error patterns could be - : error: - : error [A-Z]*[\d ]* - [A-Z]*[\d]* [E\e|rror: - " Cannot open include file " - " Could not find " - "is not a member of" - "has not been declared" Let me know if this would be efficient: dump the file in some variable and close the file grep for each error from the list or create the regular expression for each of error and parse through the variable Thank you
[ "If the log file is large, it may not be a good idea to load it to memory. Instead, you may precompile all regular expressions and test against them line by line, e.g.:\ndef has_error(filename):\n with file(filename, 'r') as logfile:\n for line in logfile:\n for regexp in MY_REGEXPS:\n ...
[ 2, 0, 0 ]
[]
[]
[ "grep", "parsing", "python", "regex" ]
stackoverflow_0003168759_grep_parsing_python_regex.txt
Q: Complex HTML parsing with Python I am already aware of tag based HTML parsing in Python using BeautifulSoup, htmllib etc. However, I want a powerful engine which can do complex tasks like read html tables, lists etc. and present these as simple to use objects within code. Does python have such powerful libraries? A: BeautifulSoup is a nice library and provides a good way to parse HTML with some handy ways to parse the data very easily. What you are trying to do, can easily be done using some simple regular expressions. You can write regular expressions to search for a particular pattern of data and extract the data you need. A: You might consider lxml which has a powerful HTML processor. There is another complementary module that relies on lxml called pyquery that might be just what you're looking for. PyQuery has jQuery-like syntax, so if you're used to jQuery you'll be able to jump right in. Here is a simple example to get the first <ul> item from aol.com: >>> from pyquery import PyQuery as pq >>> import urllib >>> data = urllib.urlopen('http://aol.com').read() >>> d = pq(data) >>> first_ul = d('ul:first') >>> first_ul [<ul#dhL2>] >>> print first_ul <ul id="dhL2"><li class="dhL1"><a accesskey="" href="https://new.aol.com/productsweb/?promocode=827693&amp;ncid=txtlnkuswebr00000074" name="om_dirbtn1" class="_o4-0" id="om_dirbtn1">Get Free Mail</a></li> </ul> A: The standard HTML parsers are already pretty good at giving you simple objects (e.g. iterables). Creating anything more complex than a 2D list from a table would likely be dependent on the data that was in the page. With that said... Here's a link to a blog post by someone who wrote a script to convert html tables to python lists. The actual file is located here. I've never heard of a standard python library that does these sorts of operations, so your best bet might be Googling each case as you need it. Chances are someone has done what you are trying to do. Disclaimer: You should always read and understand any code you find online before pasting it into your own applications! Citing who/where it's from is good too!
Complex HTML parsing with Python
I am already aware of tag based HTML parsing in Python using BeautifulSoup, htmllib etc. However, I want a powerful engine which can do complex tasks like read html tables, lists etc. and present these as simple to use objects within code. Does python have such powerful libraries?
[ "BeautifulSoup is a nice library and provides a good way to parse HTML with some handy ways to parse the data very easily. \nWhat you are trying to do, can easily be done using some simple regular expressions. You can write regular expressions to search for a particular pattern of data and extract the data you need...
[ 2, 2, 0 ]
[]
[]
[ "html_parsing", "python" ]
stackoverflow_0003167679_html_parsing_python.txt
Q: Finding the intersection of two vector equations I've been trying to solve this and I found an equation that gives the possibility of zero division errors. Not the best thing: v1 = (a,b) v2 = (c,d) d1 = (e,f) d2 = (h,i) l1: v1 + λd1 l2: v2 + µd2 Equation to find vector intersection of l1 and l2 programatically by re-arranging for lambda. (a,b) + λ(e,f) = (c,d) + µ(h,i) a + λe = c + µh b +λf = d + µi µh = a + λe - c µi = b +λf - d µ = (a + λe - c)/h µ = (b +λf - d)/i (a + λe - c)/h = (b +λf - d)/i a/h + λe/h - c/h = b/i +λf/i - d/i λe/h - λf/i = (b/i - d/i) - (a/h - c/h) λ(e/h - f/i) = (b - d)/i - (a - c)/h λ = ((b - d)/i - (a - c)/h)/(e/h - f/i) Intersection vector = (a + λe,b + λf) Not sure if it would even work in some cases. I haven't tested it. I need to know how to do this for values as in that example a-i. Thank you. A: If you do a Google search for intersection of lines you'll find lots of formulas that don't involve division by one of the coordinates. The sputsoft one referenced from wikipedia has a good explanation of the algorithm. Regarding your math, you are too quick to divide by h and i. A solution can be arrived at by postponing division. For example, multiply the equation for µh by i and the one for µi by h to get two equations for µhi. This then gives a final equation for λ that is equivalent to yours, but without the potentially illegal divisions: λ = ((b - d)h - (a - c)i)/(ei - fh) Just multiply top and bottom of your λ by hi. A: Make sure the d1 vector is not parallel (or near parallel) to the d2 vector before your computation. If they are parallel, your lines do not intersect and you get your zero-division error. Using your vars, if (ei - fh) equals or is near 0, your lines are parallel. A: Here's the solution with a python function. v1 and v2 are the position vectors. d1 and d2 are the direction vectors. def vector_intersection(v1,v2,d1,d2): ''' v1 and v2 - Vector points d1 and d2 - Direction vectors returns the intersection point for the two vector line equations. ''' if d1[0] == 0 and d2[0] != 0 or d1[1] == 0 and d2[1] != 0: if d1[0] == 0 and d2[0] != 0: mu = float(v1[0] - v2[0])/d2[0] elif d1[1] == 0 and d2[1] != 0: mu = float(v1[1] - v2[1])/d2[1] return (v2[0] + mu* d2[0],v2[1] + mu * d2[1]) else: if d1[0] != 0 and d1[1] != 0 and d2[0] != 0 and d2[1] != 0: if d1[1]*d2[0] - d1[0]*d2[1] == 0: raise ValueError('Direction vectors are invalid. (Parallel)') lmbda = float(v1[0]*d2[1] - v1[1]*d2[0] - v2[0]*d2[1] + v2[1]*d2[0])/(d1[1]*d2[0] - d1[0]*d2[1]) elif d2[0] == 0 and d1[0] != 0: lmbda = float(v2[0] - v1[0])/d1[0] elif d2[1] == 0 and d1[1] != 0: lmbda = float(v2[1] - v1[1])/d1[1] else: raise ValueError('Direction vectors are invalid.') return (v1[0] + lmbda* d1[0],v1[1] + lmbda * d1[1])
Finding the intersection of two vector equations
I've been trying to solve this and I found an equation that gives the possibility of zero division errors. Not the best thing: v1 = (a,b) v2 = (c,d) d1 = (e,f) d2 = (h,i) l1: v1 + λd1 l2: v2 + µd2 Equation to find vector intersection of l1 and l2 programatically by re-arranging for lambda. (a,b) + λ(e,f) = (c,d) + µ(h,i) a + λe = c + µh b +λf = d + µi µh = a + λe - c µi = b +λf - d µ = (a + λe - c)/h µ = (b +λf - d)/i (a + λe - c)/h = (b +λf - d)/i a/h + λe/h - c/h = b/i +λf/i - d/i λe/h - λf/i = (b/i - d/i) - (a/h - c/h) λ(e/h - f/i) = (b - d)/i - (a - c)/h λ = ((b - d)/i - (a - c)/h)/(e/h - f/i) Intersection vector = (a + λe,b + λf) Not sure if it would even work in some cases. I haven't tested it. I need to know how to do this for values as in that example a-i. Thank you.
[ "If you do a Google search for intersection of lines you'll find lots of formulas that don't involve division by one of the coordinates. The sputsoft one referenced from wikipedia has a good explanation of the algorithm. \nRegarding your math, you are too quick to divide by h and i. A solution can be arrived at by ...
[ 1, 0, 0 ]
[]
[]
[ "c++", "graphics", "math", "python" ]
stackoverflow_0003066635_c++_graphics_math_python.txt
Q: Help with cPickle in Python 2.6 I tried the following code I python. This is my first attempt at pickling. import Tkinter import cPickle root = Tkinter.Tk() root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1) root.sclX.pack(ipadx=75) root.resizable(False,False) root.title('Scale') with open('myconfig.pk', 'wb') as f: cPickle.dump(f, root.config(), -1) cPickle.dump(f, root.sclX.config(), -1) root.mainloop() But get the following error: Traceback (most recent call last): File "<string>", line 244, in run_nodebug File "C:\Python26\pickleexample.py", line 17, in <module> cPickle.dump(f, root.config(), -1) TypeError: argument must have 'write' attribute What am I doing wrong? EDIT: I tried the following code, and it works! Now how do I make it so when the program is restarted the scale is in the same position it was when the program was last closed? import Tkinter import cPickle root = Tkinter.Tk() root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1) root.sclX.pack(ipadx=75) root.resizable(False,False) root.title('Scale') with open('myconfig.pk', 'wb') as f: cPickle.dump(root.config(), f, -1); cPickle.dump(root.sclX.config(), f, -1); root.mainloop() A: Try switching the order of the arguments: cPickle.dump(root.config(), f, -1) cPickle.dump(root.sclX.config(), f, -1) According to the documentation, the file should be the second argument, and the object to be pickled should be the first. A: I think you have the parameters in the wrong order. See the docs here. Try below: cPickle.dump(root.config(), f, -1); cPickle.dump(root.sclX.config(), f, -1);
Help with cPickle in Python 2.6
I tried the following code I python. This is my first attempt at pickling. import Tkinter import cPickle root = Tkinter.Tk() root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1) root.sclX.pack(ipadx=75) root.resizable(False,False) root.title('Scale') with open('myconfig.pk', 'wb') as f: cPickle.dump(f, root.config(), -1) cPickle.dump(f, root.sclX.config(), -1) root.mainloop() But get the following error: Traceback (most recent call last): File "<string>", line 244, in run_nodebug File "C:\Python26\pickleexample.py", line 17, in <module> cPickle.dump(f, root.config(), -1) TypeError: argument must have 'write' attribute What am I doing wrong? EDIT: I tried the following code, and it works! Now how do I make it so when the program is restarted the scale is in the same position it was when the program was last closed? import Tkinter import cPickle root = Tkinter.Tk() root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1) root.sclX.pack(ipadx=75) root.resizable(False,False) root.title('Scale') with open('myconfig.pk', 'wb') as f: cPickle.dump(root.config(), f, -1); cPickle.dump(root.sclX.config(), f, -1); root.mainloop()
[ "Try switching the order of the arguments:\ncPickle.dump(root.config(), f, -1)\ncPickle.dump(root.sclX.config(), f, -1)\n\nAccording to the documentation, the file should be the second argument, and the object to be pickled should be the first.\n", "I think you have the parameters in the wrong order. See the docs...
[ 2, 1 ]
[]
[]
[ "pickle", "python", "python_2.6", "tkinter" ]
stackoverflow_0003168894_pickle_python_python_2.6_tkinter.txt
Q: Programmatically interrupting raw_input Is there a way to programmatically interrupt Python's raw_input? Specifically, I would like to present a prompt to the user, but also listen on a socket descriptor (using select, for instance) and interrupt the prompt, output something, and redisplay the prompt if data comes in on the socket. The reason for using raw_input rather than simply doing select on sys.stdin is that I would like to use the readline module to provide line editing functionality for the prompt. A: As far as I know... "Sort of". raw_input is blocking so the only way I can think of is spawning a subprocess/thread to retrieve the input, and then simply communicate with the thread/subprocess. It's a pretty dirty hack (at least it seems that way to me), but it should work cross platform. The other alternative, of course, is to use either the curses module on linux or get this one for windows.
Programmatically interrupting raw_input
Is there a way to programmatically interrupt Python's raw_input? Specifically, I would like to present a prompt to the user, but also listen on a socket descriptor (using select, for instance) and interrupt the prompt, output something, and redisplay the prompt if data comes in on the socket. The reason for using raw_input rather than simply doing select on sys.stdin is that I would like to use the readline module to provide line editing functionality for the prompt.
[ "As far as I know... \"Sort of\".\nraw_input is blocking so the only way I can think of is spawning a subprocess/thread to retrieve the input, and then simply communicate with the thread/subprocess. It's a pretty dirty hack (at least it seems that way to me), but it should work cross platform. The other alternative...
[ 2 ]
[]
[]
[ "input", "python", "readline" ]
stackoverflow_0003167956_input_python_readline.txt
Q: Python fast string parsing, manipulation I am using python to parse the incoming comma separated string. I want to do some calculation afterwards on the data. The length of the string is: 800 characters with 120 comma separated fields. There such 1.2 million strings to process. for v in item.values(): l.extend(get_fields(v.split(','))) #process l get_fields uses operator.itemgetter() to extract around 20 fields out of 120. This entire operation takes about 4-5 minutes excluding the time to bring in the data. In the later part of the program I insert these lines into sqlite memory table for further use. But overall 4-5 minutes time for just parsing and getting a list is not good for my project. I run this processing in around 6-8 threads. Does switching to C/C++ might help? A: Are you loading a dict with your file records? Probably better to process the data directly: datafile = file("file_with_1point2million_records.dat") # uncomment next to skip over a header record # file.next() l = sum(get_fields(v.split(',')) for v in file, []) This avoids creating any overall data structures, and only accumulated the desired values as returned by get_fields. A: Your program might be slowing down trying to allocate enough memory for 1.2M strings. In other words, the speed problem might not be due to the string parsing/manipulation, but rather in the l.extend. To test this hypothsis, you could put a print statement in the loop: for v in item.values(): print('got here') l.extend(get_fields(v.split(','))) If the print statements get slower and slower, you can probably conclude l.extend is the culprit. In this case, you may see significant speed improvement if you can move the processing of each line into the loop. PS: You probably should be using the csv module to take care of the parsing for you in a more high-level manner, but I don't think that will affect the speed very much.
Python fast string parsing, manipulation
I am using python to parse the incoming comma separated string. I want to do some calculation afterwards on the data. The length of the string is: 800 characters with 120 comma separated fields. There such 1.2 million strings to process. for v in item.values(): l.extend(get_fields(v.split(','))) #process l get_fields uses operator.itemgetter() to extract around 20 fields out of 120. This entire operation takes about 4-5 minutes excluding the time to bring in the data. In the later part of the program I insert these lines into sqlite memory table for further use. But overall 4-5 minutes time for just parsing and getting a list is not good for my project. I run this processing in around 6-8 threads. Does switching to C/C++ might help?
[ "Are you loading a dict with your file records? Probably better to process the data directly:\ndatafile = file(\"file_with_1point2million_records.dat\")\n# uncomment next to skip over a header record\n# file.next()\n\nl = sum(get_fields(v.split(',')) for v in file, [])\n\nThis avoids creating any overall data stru...
[ 3, 2 ]
[]
[]
[ "parsing", "performance", "python", "string" ]
stackoverflow_0003168560_parsing_performance_python_string.txt
Q: How should I organize a list of items by their category in Django? I have a "Category" model, and a "Project" model, which contains a ForeignKey to "Category." So each Project can only belong to one Category. I want to create a list that ends up looking like the following: Category 1 Project 1 Project 2 Category 2 Project 3 Project 4 etc. I think the following psuedocode will work: <ul class="category-list"> {% for c in category %} <li>{{ c.title }}</li> <ul class="project-list"> {% for p in project WHERE CATEGORY = C %} <li>{{ p.title }}</li> {% endfor %} </ul> {% endfor %} </ul> The part I'm having trouble with is the "WHERE CATEGORY = C" part. How do I express this in Django template code? A: {% for p in c.project_set.all %} Look in the Django documentation for following relationships backwards. A: You can do this by using the regroup tag http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#regroup
How should I organize a list of items by their category in Django?
I have a "Category" model, and a "Project" model, which contains a ForeignKey to "Category." So each Project can only belong to one Category. I want to create a list that ends up looking like the following: Category 1 Project 1 Project 2 Category 2 Project 3 Project 4 etc. I think the following psuedocode will work: <ul class="category-list"> {% for c in category %} <li>{{ c.title }}</li> <ul class="project-list"> {% for p in project WHERE CATEGORY = C %} <li>{{ p.title }}</li> {% endfor %} </ul> {% endfor %} </ul> The part I'm having trouble with is the "WHERE CATEGORY = C" part. How do I express this in Django template code?
[ "{% for p in c.project_set.all %}\n\nLook in the Django documentation for following relationships backwards. \n", "You can do this by using the regroup tag http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#regroup\n" ]
[ 3, 2 ]
[]
[]
[ "django", "loops", "python", "templates" ]
stackoverflow_0003169027_django_loops_python_templates.txt
Q: Google App Engine Python Authentication from API I'm currently building a Python webapp on the Google App Engine and I want to expose various parts of my application via a JSON API. This API may be used in the form of a mobile client, or (for the purposes of testing) a headless Python script. I need to be able to authenticate users before they perform operations on the API. I notice that the Users API does not support simple authentication [in the form of authenticate(username, password)] so merely sending the username/password to a URL and then later using some given token would not work. Ultimately, I would like the application to use Facebook Connect in addition to its own logins. Could somebody please suggest how is the best way to authenticate users in this situation, using a remote JSON API and the Google App Engine? Cheers A: You might want to check out the recently released oauth support. Failing that, you can implement your own authentication, for example by using simple or digest authentication. A: Just for the record, I ended up going with the wonderful Tipfy framework in the end.
Google App Engine Python Authentication from API
I'm currently building a Python webapp on the Google App Engine and I want to expose various parts of my application via a JSON API. This API may be used in the form of a mobile client, or (for the purposes of testing) a headless Python script. I need to be able to authenticate users before they perform operations on the API. I notice that the Users API does not support simple authentication [in the form of authenticate(username, password)] so merely sending the username/password to a URL and then later using some given token would not work. Ultimately, I would like the application to use Facebook Connect in addition to its own logins. Could somebody please suggest how is the best way to authenticate users in this situation, using a remote JSON API and the Google App Engine? Cheers
[ "You might want to check out the recently released oauth support. Failing that, you can implement your own authentication, for example by using simple or digest authentication.\n", "Just for the record, I ended up going with the wonderful Tipfy framework in the end.\n" ]
[ 0, 0 ]
[]
[]
[ "api", "google_app_engine", "python", "web_applications" ]
stackoverflow_0003074889_api_google_app_engine_python_web_applications.txt
Q: What data type should my widgets accept/return? I'm building a form class in python for producing and validating HTML forms. Each field has an associated widget which defines how the field is rendered. When the widget is created, it is passed in a (default) value so that it knows what to display the first time it is rendered. After the form is submitted, the widget is asked for a value. I delegate this to the widget rather than just nabbing it from the POST data because a widget may consist of several HTML inputs (think of a month/day/year selector). Only the widget knows how to mash these together into one value. Problem is, I don't know if I should have the widget always accept a string, and always return a string for consistency, or accept and return a data type consistent with its purpose (i.e., a date selector should probably return a DateTime object). The philosophy behind my form class is "mix and match". You choose what widget you want, and what validators/formatters/converters you want to run on it. Which I guess lends itself towards "use strings" and let the developer decide on the data type afterwords, but... I can't think of a good but. Do you anticipate any problems with this approach? A: While simply passing strings around seems like a useful idea, I think you're going to discover it doesn't work as well as you might hope. Think about the date example—instead of passing around a date object, instead you pass around a str of the format "2010-01-01". In order to work with that data, every user of the class needs to know not only that it's a str which represents a date, but what the format of that string is. In other words, you haven't gained anything. Worse, you lose the ability to pass a datetime object into the widget (unless you take extra steps to deal with that case). The validator or formatter issue isn't as big a deal as you might think; how often are you going to want to validate a string which doesn't represent a date as if it were a date? A: This approach is quite generic and serializing to and from strings should always work fine. You could also save the state of a widget to a file or send it over a network for recreating another widget from it. Some potential issues or aspects to consider: Localization: how to interpret the string regarding the culture, which format is the canonical format for comparisons. Performance: some transformations might be time consuming, but I assume for human interaction that will be far fast enough.
What data type should my widgets accept/return?
I'm building a form class in python for producing and validating HTML forms. Each field has an associated widget which defines how the field is rendered. When the widget is created, it is passed in a (default) value so that it knows what to display the first time it is rendered. After the form is submitted, the widget is asked for a value. I delegate this to the widget rather than just nabbing it from the POST data because a widget may consist of several HTML inputs (think of a month/day/year selector). Only the widget knows how to mash these together into one value. Problem is, I don't know if I should have the widget always accept a string, and always return a string for consistency, or accept and return a data type consistent with its purpose (i.e., a date selector should probably return a DateTime object). The philosophy behind my form class is "mix and match". You choose what widget you want, and what validators/formatters/converters you want to run on it. Which I guess lends itself towards "use strings" and let the developer decide on the data type afterwords, but... I can't think of a good but. Do you anticipate any problems with this approach?
[ "While simply passing strings around seems like a useful idea, I think you're going to discover it doesn't work as well as you might hope.\nThink about the date example—instead of passing around a date object, instead you pass around a str of the format \"2010-01-01\". In order to work with that data, every user o...
[ 2, 1 ]
[]
[]
[ "design_patterns", "python" ]
stackoverflow_0003169096_design_patterns_python.txt
Q: Sequence file name being used as key in Hadoop output? I'm trying to use Dumbo/Hadoop to calculate TF-IDF for a bunch of small text files using this example http://dumbotics.com/2009/05/17/tf-idf-revisited/ To improve efficiency, I've packaged the text files into a sequence file using Stuart Sierra's tool -- http://stuartsierra.com/2008/04/24/a-million-little-files The sequence file uses my original filenames (324324.txt [the object_id.txt]) as the key and the file contents as the value. Problem is that each line of output looks like: [aftershocks, s3://mybucket/input/test-seq-file] 7.606329176204189E-4 What I want is: [aftershocks, 324324.txt] 7.606329176204189E-4 What am I doing wrong? I'm running the job with: dumbo start tfidf.py -hadoop /home/hadoop -input s3://mybucket/input/ test-seq-file -output s3://mybucket/output/test3 -param doccount=11 - outputformat text A: I made the following tweaks to the first mapper and everything started working. #Original version @opt("addpath", "yes") def mapper1(key, value): for word in value.split(): yield (key[0], word), 1 #Edits version def mapper1(key, value): for word in value.split(): yield (key, word), 1
Sequence file name being used as key in Hadoop output?
I'm trying to use Dumbo/Hadoop to calculate TF-IDF for a bunch of small text files using this example http://dumbotics.com/2009/05/17/tf-idf-revisited/ To improve efficiency, I've packaged the text files into a sequence file using Stuart Sierra's tool -- http://stuartsierra.com/2008/04/24/a-million-little-files The sequence file uses my original filenames (324324.txt [the object_id.txt]) as the key and the file contents as the value. Problem is that each line of output looks like: [aftershocks, s3://mybucket/input/test-seq-file] 7.606329176204189E-4 What I want is: [aftershocks, 324324.txt] 7.606329176204189E-4 What am I doing wrong? I'm running the job with: dumbo start tfidf.py -hadoop /home/hadoop -input s3://mybucket/input/ test-seq-file -output s3://mybucket/output/test3 -param doccount=11 - outputformat text
[ "I made the following tweaks to the first mapper and everything started working.\n#Original version\n@opt(\"addpath\", \"yes\")\ndef mapper1(key, value):\n for word in value.split():\n yield (key[0], word), 1\n\n#Edits version\ndef mapper1(key, value):\n for word in value.split():\n yield (key, ...
[ 1 ]
[]
[]
[ "hadoop", "mapreduce", "python" ]
stackoverflow_0003151811_hadoop_mapreduce_python.txt
Q: Where can I get some proxy list good for use it with Python? Where? I'm trying google and any of the proxys I've tried worked... I'm trying urllib.open with it... I don't know if urllib need some special proxy type or something like that... Thank you ps: I need some proxies to ping a certain website and not got banned from my ip A: Try setting up your own proxy and connecting to it... A: You probably don't even need to use a proxy. The urllib module knows how to contact web servers directly. You may need to use a proxy if you're behind certain kinds of corporate firewalls, but in that case you can't just choose any proxy to use, you have to use the corporate proxy. In such a case, a list of open proxies on Google isn't going to help you.
Where can I get some proxy list good for use it with Python?
Where? I'm trying google and any of the proxys I've tried worked... I'm trying urllib.open with it... I don't know if urllib need some special proxy type or something like that... Thank you ps: I need some proxies to ping a certain website and not got banned from my ip
[ "Try setting up your own proxy and connecting to it...\n", "You probably don't even need to use a proxy. The urllib module knows how to contact web servers directly. \nYou may need to use a proxy if you're behind certain kinds of corporate firewalls, but in that case you can't just choose any proxy to use, you ha...
[ 0, 0 ]
[]
[]
[ "proxy", "python" ]
stackoverflow_0003169425_proxy_python.txt
Q: Py GTK Drawing area and Rich Text Editor I would like to include a rich text editor in a pygtk drawing area for an application i am developing. The editor ( a small resizable widget ) should be able to move around the drawing area like a rectangle. I am not sure how to start as I am pretty new to PyGTK. thank you ! A: BloGTK seems to use an HTML widget for rich text. Those aren't quite as flexible for plain text. Here's a link that should be helpful: http://www.kksou.com/php-gtk2/articles/apply-styles-to-GtkTextView-using-GtkTextTag---Part-1.php A: gtk.TextView is "rich", in that it can display all types of formatting and even embedded widgets. If you want the functionality of editing rich text, you will have to write something yourself, though others have tried in applications like BloGTK. From which you could steal codes. A: You could use GtkLayout instead od GtkDrawingArea. You can place child widgets on GtkLayout and paint on it like on a GtkDrawingArea. http://library.gnome.org/devel/gtk/stable/GtkLayout.html
Py GTK Drawing area and Rich Text Editor
I would like to include a rich text editor in a pygtk drawing area for an application i am developing. The editor ( a small resizable widget ) should be able to move around the drawing area like a rectangle. I am not sure how to start as I am pretty new to PyGTK. thank you !
[ "BloGTK seems to use an HTML widget for rich text. Those aren't quite as flexible for plain text.\nHere's a link that should be helpful:\nhttp://www.kksou.com/php-gtk2/articles/apply-styles-to-GtkTextView-using-GtkTextTag---Part-1.php\n", "gtk.TextView is \"rich\", in that it can display all types of formatting a...
[ 1, 0, 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0002650591_pygtk_python.txt
Q: python: c# binary datetime encoding I need to extract financial price data from a binary file. This price data is normally extracted by a piece of C# code. The biggest problem I'm having is getting a meaningful datetime. The binary data looks like this: '\x14\x11\x00\x00{\x14\xaeG\xe1z(@\x9a\x99\x99\x99\x99\x99(@q=\n\xd7\xa3p(@\x9a\x99\x99\x99\x99\x99(@\xac\x00\x19\x00\x00\x00\x00\x00\x08\x01\x00\x00\x00"\xd8\x18\xe0\xdc\xcc\x08' The C# code that extracts it correctly is: StockID = reader.ReadInt32(); Open = reader.ReadDouble(); High = reader.ReadDouble(); Low = reader.ReadDouble(); Close = reader.ReadDouble(); Volume = reader.ReadInt64(); TotalTrades = reader.ReadInt32(); Timestamp = reader.ReadDateTime(); This is where I've gotten in python. I have a couple concerns about it. In [1]: barlength = 56; barformat = 'i4dqiq' In [2]: pricebar = f.read(barlength) In [3]: pricebar Out[3]: '\x95L\x00\x00)\\\x8f\xc2\xf5\xc8N@D\x1c\xeb\xe26\xcaN@\x7fj\xbct\x93\xb0N@\xd7\xa3p=\n\xb7N@\xf6\xdb\x02\x00\x00\x00\x00\x00J\x03\x00\x00\x00"\xd8\x18\xe0\xdc\xcc\x08' In [4]: struct.unpack(barformat, pricebar) Out[4]: (19605, # stock id 61.57, # open 61.579800000000006, # high 61.3795, # low 61.43, # close 187382, # volume -- seems reasonable 842, # TotalTrades -- seems reasonable 634124502600000000L # datetime -- no idea what this means! ) I used python's built in struct module but have some concerns about it. I'm not sure what format characters correspond to Int32 vs Int64 in the C# code, though several different tries returned the same python tuple. I'm concerned though since the output for some of the fields doesn't seem to be very sensitive to the format I specify: For example, the TotalTrades field returns the same amount if i specify it as either signed or unsigned int OR signed or unsigned long (l, L, i, or I) I can't make any sense of the date return field. This is actually my biggest problem. A: As far as I know, .net timestamps are ticks since 0001-01-01T00:00:00Z where a tick is 100 nanoseconds. So: >>> x = 634124502600000000 >>> secs = x / 10.0 ** 7 >>> secs 63412450260.0 >>> import datetime >>> delta = datetime.timedelta(seconds=secs) >>> delta datetime.timedelta(733940, 34260) >>> ts = datetime.datetime(1,1,1) + delta >>> ts datetime.datetime(2010, 6, 18, 9, 31) >>> The date part is 2010-06-18. Are you in a timezone that's 9.5 hours away from UTC? It would be rather useful in verifying this calculation if you were to supply TWO timestamp values together with the expected answers. Addressing your concern """I'm concerned though since the output for some of the fields doesn't seem to be very sensitive to the format I specify: For example, the TotalTrades field returns the same amount if i specify it as either signed or unsigned int OR signed or unsigned long (l, L, i, or I)""": They are not sensitive because (1) "long" and "int" mean the same (32 bits) and (2) the smaller half of all possible unsigned numbers have the same representation as signed numbers. For example, in 8-bit numbers, the numbers 0 to 127 inclusive have the same bit pattern whether signed or unsigned. A: Without seeing the C# source containing the ReadInt32, ReadDouble, ReadDateTime etc methods it will be impossible to give a definitive answer, but... I'm not really sure what the difference is between the i and l format characters, but I think you're correct in using i/l for Int32 and q for Int64. Again, I don't know the difference between the i/l or I/L format characters, but since they all represent 32-bit integers then their binary representation should be the same for all values between 0 and 2147483647 inclusive. If it's possible for TotalTrades to be negative, or exceed 2147483647, then you should investigate further. If not then don't worry about it. It looks to me like your serialized date field is probably equivalent to DateTime.Ticks. If that's the case then the serialized value will be the number of ticks -- that is, the number of 100 nanosecond intervals -- since 00:00:00 on 1 January 0001. By that reckoning, the value shown in your question -- 634124502600000000 -- would represent 09:31:00 on 18 June 2010.
python: c# binary datetime encoding
I need to extract financial price data from a binary file. This price data is normally extracted by a piece of C# code. The biggest problem I'm having is getting a meaningful datetime. The binary data looks like this: '\x14\x11\x00\x00{\x14\xaeG\xe1z(@\x9a\x99\x99\x99\x99\x99(@q=\n\xd7\xa3p(@\x9a\x99\x99\x99\x99\x99(@\xac\x00\x19\x00\x00\x00\x00\x00\x08\x01\x00\x00\x00"\xd8\x18\xe0\xdc\xcc\x08' The C# code that extracts it correctly is: StockID = reader.ReadInt32(); Open = reader.ReadDouble(); High = reader.ReadDouble(); Low = reader.ReadDouble(); Close = reader.ReadDouble(); Volume = reader.ReadInt64(); TotalTrades = reader.ReadInt32(); Timestamp = reader.ReadDateTime(); This is where I've gotten in python. I have a couple concerns about it. In [1]: barlength = 56; barformat = 'i4dqiq' In [2]: pricebar = f.read(barlength) In [3]: pricebar Out[3]: '\x95L\x00\x00)\\\x8f\xc2\xf5\xc8N@D\x1c\xeb\xe26\xcaN@\x7fj\xbct\x93\xb0N@\xd7\xa3p=\n\xb7N@\xf6\xdb\x02\x00\x00\x00\x00\x00J\x03\x00\x00\x00"\xd8\x18\xe0\xdc\xcc\x08' In [4]: struct.unpack(barformat, pricebar) Out[4]: (19605, # stock id 61.57, # open 61.579800000000006, # high 61.3795, # low 61.43, # close 187382, # volume -- seems reasonable 842, # TotalTrades -- seems reasonable 634124502600000000L # datetime -- no idea what this means! ) I used python's built in struct module but have some concerns about it. I'm not sure what format characters correspond to Int32 vs Int64 in the C# code, though several different tries returned the same python tuple. I'm concerned though since the output for some of the fields doesn't seem to be very sensitive to the format I specify: For example, the TotalTrades field returns the same amount if i specify it as either signed or unsigned int OR signed or unsigned long (l, L, i, or I) I can't make any sense of the date return field. This is actually my biggest problem.
[ "As far as I know, .net timestamps are ticks since 0001-01-01T00:00:00Z where a tick is 100 nanoseconds. So:\n>>> x = 634124502600000000\n>>> secs = x / 10.0 ** 7\n>>> secs\n63412450260.0\n>>> import datetime\n>>> delta = datetime.timedelta(seconds=secs)\n>>> delta\ndatetime.timedelta(733940, 34260)\n>>> ts = datet...
[ 3, 0 ]
[]
[]
[ "binary", "c#", "python" ]
stackoverflow_0003169517_binary_c#_python.txt
Q: Python Error Catching & FTP Trying to get a handle on the FTP library in Python. :) Got this so far. from ftplib import FTP server = '127.0.0.1' port = '57422' print 'FTP Client (' + server + ') port: ' + port try: ftp = FTP() ftp.connect(server, port, 3) print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"' ftp.cwd('\\') x = '1' currentDir = '' except: //***What do I put here?*** http://docs.python.org/library/ftplib.html says there are several error codes I can catch but I can't do except: ftplib.all_errors Second question. :P How can I retrieve more specific information on the error? Perhaps the error code? Very new to python (an hour in or so). A: I can't do except: ftplib.all_errors Of course not, that's simply bad syntax! But of course you can do it with proper syntax: except ftplib.all_errors: i.e., the colon after the tuple of exceptions. How can I retrieve more specific information on the error? Perhaps the error code? except ftplib.all_errors as e: errorcode_string = str(e).split(None, 1)[0] E.g., '530' will now be the value of errorcode_string when the complete error message was '530 Login authentication failed'. You can find the rest of the exception in the docs. A: You write except Exception, e: #you can specify type of Exception also print str(e) A: You dont want to try catch an Exception class unless you have to. Exception is a catch all, instead catch the specific class being thrown, socket.error import ftplib import socket <-- server = '127.0.0.1' port = '57422' print 'FTP Client (' + server + ') port: ' + port ftp = ftplib.FTP() try: ftp.connect(server, port, 3) print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"' ftp.cwd('\\') x = '1' currentDir = '' except socket.error,e: <-- print 'unable to connect!,%s'%e
Python Error Catching & FTP
Trying to get a handle on the FTP library in Python. :) Got this so far. from ftplib import FTP server = '127.0.0.1' port = '57422' print 'FTP Client (' + server + ') port: ' + port try: ftp = FTP() ftp.connect(server, port, 3) print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"' ftp.cwd('\\') x = '1' currentDir = '' except: //***What do I put here?*** http://docs.python.org/library/ftplib.html says there are several error codes I can catch but I can't do except: ftplib.all_errors Second question. :P How can I retrieve more specific information on the error? Perhaps the error code? Very new to python (an hour in or so).
[ "\nI can't do\n\nexcept: ftplib.all_errors\n\nOf course not, that's simply bad syntax! But of course you can do it with proper syntax:\nexcept ftplib.all_errors:\n\ni.e., the colon after the tuple of exceptions.\n\nHow can I retrieve more specific\n information on the error? Perhaps the\n error code?\n\nexcept f...
[ 24, 2, 1 ]
[]
[]
[ "ftp", "python" ]
stackoverflow_0003169725_ftp_python.txt
Q: Generating Combinations in python I am not sure how to go about this in Python, if its even possible. What I need to do is create an array (or a matrix, or vector?) from 3 separate arrays. Each array as 4 elements as such, they return this: Class1 = [1,2,3,4] Class2 = [1,2,3,4] Class3 = [1,2,3,4] Now what I would like to do is return all possible combinations of these three classes. Example: 1 1 1 2 1 1 3 1 1 4 1 1 1 2 1 2 2 1 3 2 1 4 2 1... ...and so on to 64 rows (4 elements *16 possible combinations for each class = 64 rows I am hoping there is a way to do this in python. I am sure there is but I am not sure what the most efficient way to go about would be. Perhaps a "for in" loop statement that iterates over each element for each class? Or now that I am researching this, would itertools handle this? Thanks in advance for any help offered. A: What you want is called a Cartesian product: import itertools iterables = [ [1,2,3,4], [88,99], ['a','b'] ] for t in itertools.product(*iterables): print t A: The simplest way: for i in Class1: for j in Class2: for k in Class3: print (i,j,k) A: Check the Python itertools standard module: itertools.combinations(iterable, r) Return r length subsequences of elements from the input iterable.
Generating Combinations in python
I am not sure how to go about this in Python, if its even possible. What I need to do is create an array (or a matrix, or vector?) from 3 separate arrays. Each array as 4 elements as such, they return this: Class1 = [1,2,3,4] Class2 = [1,2,3,4] Class3 = [1,2,3,4] Now what I would like to do is return all possible combinations of these three classes. Example: 1 1 1 2 1 1 3 1 1 4 1 1 1 2 1 2 2 1 3 2 1 4 2 1... ...and so on to 64 rows (4 elements *16 possible combinations for each class = 64 rows I am hoping there is a way to do this in python. I am sure there is but I am not sure what the most efficient way to go about would be. Perhaps a "for in" loop statement that iterates over each element for each class? Or now that I am researching this, would itertools handle this? Thanks in advance for any help offered.
[ "What you want is called a Cartesian product:\nimport itertools\n\niterables = [ [1,2,3,4], [88,99], ['a','b'] ]\n\nfor t in itertools.product(*iterables):\n print t\n\n", "The simplest way:\nfor i in Class1:\n for j in Class2:\n for k in Class3:\n print (i,j,k)\n\n", "Check the Python i...
[ 43, 8, 2 ]
[]
[]
[ "arrays", "combinations", "matrix", "multidimensional_array", "python" ]
stackoverflow_0003169825_arrays_combinations_matrix_multidimensional_array_python.txt
Q: how do i take advantage of sqlite manifest typing / type affinity using sqlalchemy? I like the idea of sqlite's manifest typing / type affinity: http://www.sqlite.org/datatype3.html Essentially, if I set a column's affinity as 'numeric', it will duck type integers or floats to store them as such, but still allow me to store strings if I want to. Seems to me this is the best 'default' type for a column when i'm not sure ahead of time of what data i want to store in it. so off i go: metadata = MetaData() new_table = Table(table_name, metadata ) for col_name in column_headings: new_table.append_column(Column(col_name, sqlite.NUMERIC, #this should duck-type numbers but can handle strings as well primary_key=col_name in primary_key_columns)) new_table.create(self.engine, checkfirst=False) but when i try and store some string values, eg "abc" in the table, sqlalchemy falls over: File "[...]\sqlalchemy\processors.py", line 79, in to_float return float(value) ValueError: invalid literal for float(): abc Boo, hiss. So, is there any way I can convince sqlalchemy to let sqlite do the typing? perhaps i can use a type from sqlalchemy.types instead of sqlachemy.dialects.sqlite? [edit:] for bonus points: i need to be able to access tables via introspection / reflection. so some kind of way of having this work with meta.reflect() would be great! ;-) A: OK, here's what I've come up with: Define a custom column type, as per http://www.sqlalchemy.org/docs/reference/sqlalchemy/types.html#custom-types a combination of the documentation and some trial & error have given me this: class MyDuckType(sqlalchemy.types.TypeDecorator): """ SQLALchemy custom column type, designed to let sqlite handle the typing using 'numeric affinity' which intelligently handles both numbers and strings """ impl = sqlite.NUMERIC def bind_processor(self, dialect): #function for type coercion during db write return None #ie pass value as-is, let sqlite do the typing def result_processor(self, dialect, coltype): #function for type coercion during db read return None #ie pass value as sqlite has stored it, should be ducktyped already def process_bind_param(self, value, dialect): #any changes to an individual value before store in DN return value def process_result_value(self, value, dialect): #any changes to an individual value after retrieve from DB return value def copy(self): #not quite sure what this is for return MyDuckType() The current sqlalchemy dialect type returns to_float in bind_processor, which is why I was getting the errors before. i.m.v.v.h.o., this is a bug. for my bonus points: manually setting column type to MyDuckType in my metadata.reflect() code: def get_database_tables(engine): meta = MetaData() meta.reflect(bind=engine) tables = meta.raw_tables for tbl in tables.values(): for col in tbl.c: col.type = MyDuckType() return tables seems to work for me. Any suggestions / improvements? A: Essentially, if I set a column's affinity as 'numeric', it will duck type integers or floats to store them as such, but still allow me to store strings if I want to. If you don't declare a column type at all, SQLite will let you store any type without performing conversions. This may be a better choice if you want to distinguish 123 from '123'.
how do i take advantage of sqlite manifest typing / type affinity using sqlalchemy?
I like the idea of sqlite's manifest typing / type affinity: http://www.sqlite.org/datatype3.html Essentially, if I set a column's affinity as 'numeric', it will duck type integers or floats to store them as such, but still allow me to store strings if I want to. Seems to me this is the best 'default' type for a column when i'm not sure ahead of time of what data i want to store in it. so off i go: metadata = MetaData() new_table = Table(table_name, metadata ) for col_name in column_headings: new_table.append_column(Column(col_name, sqlite.NUMERIC, #this should duck-type numbers but can handle strings as well primary_key=col_name in primary_key_columns)) new_table.create(self.engine, checkfirst=False) but when i try and store some string values, eg "abc" in the table, sqlalchemy falls over: File "[...]\sqlalchemy\processors.py", line 79, in to_float return float(value) ValueError: invalid literal for float(): abc Boo, hiss. So, is there any way I can convince sqlalchemy to let sqlite do the typing? perhaps i can use a type from sqlalchemy.types instead of sqlachemy.dialects.sqlite? [edit:] for bonus points: i need to be able to access tables via introspection / reflection. so some kind of way of having this work with meta.reflect() would be great! ;-)
[ "OK, here's what I've come up with:\nDefine a custom column type, as per\nhttp://www.sqlalchemy.org/docs/reference/sqlalchemy/types.html#custom-types\na combination of the documentation and some trial & error have given me this:\nclass MyDuckType(sqlalchemy.types.TypeDecorator):\n \"\"\"\n SQLALchemy custom c...
[ 1, 0 ]
[]
[]
[ "python", "sqlalchemy", "sqlite", "typing" ]
stackoverflow_0003044518_python_sqlalchemy_sqlite_typing.txt
Q: why my code stop in secound while loop? #hello , i wounder why my code keep stoping at the secound while loop and doesn't do anything print"*******************************" a = 0 deg_list =[] deg_list_a=[] deg_list_b=[] deg_list_c=[] degree=input("Enter the students Degree:") while a<=degree: deg_list.append(degree); degree=input("Enter the students Degree:") print "Degree List :",deg_list print len(deg_list) while len(deg_list)>=0: if deg_list[a]>=16: deg_list_a.append(deg_list[a]) x=+1 elif 15>deg_list[a]>=10: deg_list_b.append(deg_list[a]) x=+1 else : deg_list_b.append(deg_list[a]) x=+1 print deg_list_a print deg_list_b print deg_list_c A: Your code enters an endless loop. Both of your while loops have problems with the condition which allows them to terminate. Since your code never changes the value of a, the first loop becomes while 0<=degree, and so the first loop terminates when the user inputs a negative value. But the variable a can be removed from your program. The while loop continues as long as len(deg_list) >= 0. However, no code within the loop decreases the length of deg_list, so the while loop continues forever. The code below could help you get this working: deg_list =[] deg_list_a=[] deg_list_b=[] deg_list_c=[] degree=input("Enter the students Degree:") while degree > 0: deg_list.append(degree); degree=input("Enter the students Degree:") print len(deg_list) while len(deg_list) > 0: # Strictly greater than 0, not equal to 0. if deg_list[0] >= 16: # Use pop to access first element deg_list_a.append(deg_list.pop(0)) elif deg_list[0] >= 10: # One comparison per statement, only. deg_list_b.append(deg_list.pop(0)) else: deg_list_c.append(deg_list.pop(0)) # c, not b. print deg_list_a print deg_list_b print deg_list_c A: You're never modifying deg_list, so your loop becomes infinite. Even removing all elements wouldn't help since you're comparing against 0 -- the loop condition will never be false. A: Well. It looks to me that a is set to 0 in the beginning and then never changed, so doing something with deg_list[a], that is the first element in the list, isn't going to do very much. In addition, your looping condition is len(deg_list) >= 0, and len(deg_list) will never change. But there are more fundamental issues with your code. Imagine you were changing the length of deg_list: in this case you would be changing the very list you're looping over, which is usually (if you are not very very certain what you're doing) a recipe for disaster. What I think you should envisage doing is a loop along the lines of: for degree in deg_list: if [degree fulfils some condition]: [do something with degree] elif [degree fulfils some other condition]: [do something else] ... else: [whatever] Last, from your comparison it seems that the "degrees" are all small integers. You may want to test for that -- it's user input and you have to expect anything being thrown at your input -- before doing things like if degree >= 16. A: It looks like you are trying to loop through all the members of deg_list, but you are waiting for deg_list to be empty, and each time through the loop you are incrementing "x," which is never even read. If you really are trying to traverse through deg_list, try this for your second loop: for degree in deg_list: if degree >= 16: deg_list_a.append(degree) elif degree >= 10: deg_list_b.append(degree) else : deg_list_c.append(degree)
why my code stop in secound while loop?
#hello , i wounder why my code keep stoping at the secound while loop and doesn't do anything print"*******************************" a = 0 deg_list =[] deg_list_a=[] deg_list_b=[] deg_list_c=[] degree=input("Enter the students Degree:") while a<=degree: deg_list.append(degree); degree=input("Enter the students Degree:") print "Degree List :",deg_list print len(deg_list) while len(deg_list)>=0: if deg_list[a]>=16: deg_list_a.append(deg_list[a]) x=+1 elif 15>deg_list[a]>=10: deg_list_b.append(deg_list[a]) x=+1 else : deg_list_b.append(deg_list[a]) x=+1 print deg_list_a print deg_list_b print deg_list_c
[ "Your code enters an endless loop. \nBoth of your while loops have problems with the condition which allows them to terminate. Since your code never changes the value of a, the first loop becomes while 0<=degree, and so the first loop terminates when the user inputs a negative value. But the variable a can be re...
[ 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003169919_python.txt