content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: how does execfile() work in python? does the file which is sent as an argument to execfile runs as an independent process / thread or is the code imported and then executed ? . Also i wanted to know how efficient is it compared to running threads / process . A: The file is not run in a separate thread or process, it runs synchronously with the caller.
how does execfile() work in python?
does the file which is sent as an argument to execfile runs as an independent process / thread or is the code imported and then executed ? . Also i wanted to know how efficient is it compared to running threads / process .
[ "The file is not run in a separate thread or process, it runs synchronously with the caller.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0004033669_python.txt
Q: Simplify this python code I've written a program to check if my thought about solution on paper is right (and it is). The task: how many zeros is in the back of multiplication of all numbers from 10 to 200. It is 48 and it is a simple to calculate manually. I never write on python seriously and this is what I get: mul = 1 for i in range(10, 200 + 1): mul *= i string = str(mul) string = string[::-1] count = 0; for c in str(string): if c == '0': count += 1 else: break print count print mul I bet it is possible to write the same more elegant in such language like a python. ps: yes, it is a homework, but not mine - i just helped a guy ;-) A: A straight-forward implementation that doesn't involve calculating the factorial (so that it works with big numbers, ie 2000000!) (edited): fives = 0 twos = 0 for i in range(10, 201): while i % 5 == 0: fives = fives + 1 i /= 5 while i % 2 == 0: twos = twos + 1 i /= 2 print(min(fives, twos)) A: import math answer = str(math.factorial(200) / math.factorial(9)) count = len(answer) - len(answer.rstrip('0')) Import the math library Calculate the factorial of 200 and take away the first 9 numbers Strip away zeros from the right and find out the difference in lengths A: print sum(1 + (not i%25) + (not i%125) for i in xrange(10,201,5)) A: import itertools mul = reduce(lambda x,y: x*y, range(10, 200+1)) zeros = itertools.takewhile(lambda s: s == "0", reversed(str(mul))) print len(list(zeros)) The second line calculates the product, the third gets an iterator of all trailing zeros in that number, the last prints the number of that zeros. A: len(re.search('0*$', str(reduce(lambda x, y: x*y, range(10, 200 + 1),1))).group(0)) A: Do you mean zeroes? What is null otherwise? Wouldn't some mathematics make it simpler? How many 5s in 200 is len([x for x in range(5, 201, 5)]) = 40 How many 25s in 200 is len([x for x in range(25, 201, 5) if x%25 == 0]) = 8 How many 125s in 200 is len([x for x in range(120, 201, 5) if x%125 == 0]) = 1 Total 5s = 49 200! = 5^49 * 2 ^49 * (other numbers not divisible by 2 or 5) So there are 49 zeroes A: mul = str(reduce(lambda x,y: x*y, xrange(10, 201))) count = len(mul) - len(mul.rstrip("0"))
Simplify this python code
I've written a program to check if my thought about solution on paper is right (and it is). The task: how many zeros is in the back of multiplication of all numbers from 10 to 200. It is 48 and it is a simple to calculate manually. I never write on python seriously and this is what I get: mul = 1 for i in range(10, 200 + 1): mul *= i string = str(mul) string = string[::-1] count = 0; for c in str(string): if c == '0': count += 1 else: break print count print mul I bet it is possible to write the same more elegant in such language like a python. ps: yes, it is a homework, but not mine - i just helped a guy ;-)
[ "A straight-forward implementation that doesn't involve calculating the factorial (so that it works with big numbers, ie 2000000!) (edited):\nfives = 0\ntwos = 0\nfor i in range(10, 201):\n while i % 5 == 0:\n fives = fives + 1\n i /= 5\n while i % 2 == 0:\n twos = twos + 1\n i /= 2\nprint(m...
[ 11, 6, 4, 3, 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004028844_python.txt
Q: What do i build my alpha platform on, PHP, Ruby, Python, .NET, etc? I am developing a social networking website in the facebook/foursquare-ish space. I have gotten such varied feedback on what platform I should develop in. Of course it will be heavily influenced by who I hire, but i was hoping for a little additional feedback from the larger community. Thanks. A: It doesn't matter. StackOverflow was written in ASP .NET MVC and it's awesome. Twitter was written in Rails and it's super popular. Facebook was written in PHP and half a billion people use it. It's not the technology, it's the community. That's the hard part. Just pick one and go. Your best bet might actually be to find the technology that the most smart people are using while still working for the least amount of money. A: Write in assembler if you're comfortable with that. :) Some questions you should ask yourself: Are there hosting restrictions? No point in coding ASP.net when you have a PHP-only host/server. Are there technical restrictions? E.g. if you want to use SQL Server as a back-end, going with ASP.net may make your life easier. What other requirements do you have? Does it have to run on the JVM? Do you want to compile stuff all the time or do you want an interpreted language? etc. etc. What experience do you have? If you're already familiar with Python, why switch to Ruby? My best tip is: use what's best for the job at hand according to the above questions. For me, I'd use Ruby on Rails for the project you described. Rails offers all the tools I need for a large project like that. Please let us know when and what you've decided :)
What do i build my alpha platform on, PHP, Ruby, Python, .NET, etc?
I am developing a social networking website in the facebook/foursquare-ish space. I have gotten such varied feedback on what platform I should develop in. Of course it will be heavily influenced by who I hire, but i was hoping for a little additional feedback from the larger community. Thanks.
[ "It doesn't matter.\nStackOverflow was written in ASP .NET MVC and it's awesome.\nTwitter was written in Rails and it's super popular.\nFacebook was written in PHP and half a billion people use it. \nIt's not the technology, it's the community. That's the hard part.\nJust pick one and go. Your best bet might act...
[ 7, 1 ]
[]
[]
[ ".net", "php", "python", "ruby_on_rails" ]
stackoverflow_0004033735_.net_php_python_ruby_on_rails.txt
Q: Is python a stable platform for facebook development? I'm trying to build my first facebook app, and it seems that the python facebook (pyfacebook) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented. Are there any mature python frontends for facebook? If not, what's the best language for facebook development? A: The updated location of pyfacebook is on github. Plus, as arstechnica well explains: PyFacebook is also very easy to extend when new Facebook API methods are introduced. Each Facebook API method is described in the PyFacebook library using a simple data structure that specifies the method's name and parameter types. so, even should you be using a pyfacebook version that doesn't yet implement some brand-new thing you need, it's easy to add said thing, as Ryan Paul shows here regarding some of the stream functions (back in April right after they were launched). A: Facebook's own Python-SDK covers the newer Graph API now: http://github.com/facebook/python-sdk/ A: Try this site instead. It's pyfacebooks site on GitHub. The one you have is outdated. A: If you're a facebook newbie, I'd suggest doing your first couple of apps in PHP. Facebook is written in PHP, the APIs are really designed around PHP (although they are language-neutral, theoretically.) The latest API support and most of the sample code is always in PHP. Once you get the hang of it, you can definitely write FB apps in other languages, including Python, Actionscript, etc. But my experience with other platforms is that they never work "out of the box" with Facebook the way PHP does. This is nothing against python! I like the language alot.
Is python a stable platform for facebook development?
I'm trying to build my first facebook app, and it seems that the python facebook (pyfacebook) wrapper is really out of date, and the most relevant functions, like stream functions, are not implemented. Are there any mature python frontends for facebook? If not, what's the best language for facebook development?
[ "The updated location of pyfacebook is on github. Plus, as arstechnica well explains:\n\nPyFacebook is also very easy to extend\n when new Facebook API methods are\n introduced. Each Facebook API method\n is described in the PyFacebook library\n using a simple data structure that\n specifies the method's name ...
[ 13, 11, 4, 3 ]
[]
[]
[ "api", "facebook", "python" ]
stackoverflow_0001027990_api_facebook_python.txt
Q: django site administration (entering fixtures data) I have a django site. a snippet of myapp/models.py looks like this: class Continent(models.Model): name = models.CharField(max_length=128, db_index=True, unique=True) class GeographicRegion(models.Model): continent = models.ForeignKey(Continent, null=False) name = models.CharField(max_length=128, null=False) When I am attempting to add new geographic regions, when I click the drop down list (select control) to choose a continent, the only values (options) in the drop down list are: continent object continent object continent object continent object continent object continent object I was expecting to see the names of the continents instead, so I could create relevant geographic regions per continent. How do I get the name to show in the list instead of 'continent object'? Hint: i added str(self) and repr(self) methods to my ContinentAdmin model in myapp/admin.py like this: myapp/admin.py 58 class ContinentAdmin(admin.ModelAdmin): 59 def __repr__(self): 60 return self.name 61 62 admin.site.register(Continent,ContinentAdmin) , however this had no (observable) effect A: You need to define __unicode__ method in model: def __unicode__(self): return self.name
django site administration (entering fixtures data)
I have a django site. a snippet of myapp/models.py looks like this: class Continent(models.Model): name = models.CharField(max_length=128, db_index=True, unique=True) class GeographicRegion(models.Model): continent = models.ForeignKey(Continent, null=False) name = models.CharField(max_length=128, null=False) When I am attempting to add new geographic regions, when I click the drop down list (select control) to choose a continent, the only values (options) in the drop down list are: continent object continent object continent object continent object continent object continent object I was expecting to see the names of the continents instead, so I could create relevant geographic regions per continent. How do I get the name to show in the list instead of 'continent object'? Hint: i added str(self) and repr(self) methods to my ContinentAdmin model in myapp/admin.py like this: myapp/admin.py 58 class ContinentAdmin(admin.ModelAdmin): 59 def __repr__(self): 60 return self.name 61 62 admin.site.register(Continent,ContinentAdmin) , however this had no (observable) effect
[ "You need to define __unicode__ method in model:\ndef __unicode__(self):\n return self.name\n\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004034434_django_python.txt
Q: Understanding __call__ and list.sort(key) I have the following code I am trying to understand: >>> class DistanceFrom(object): def __init__(self, origin): self.origin = origin def __call__(self, x): return abs(x - self.origin) >>> nums = [1, 37, 42, 101, 13, 9, -20] >>> nums.sort(key=DistanceFrom(10)) >>> nums [9, 13, 1, 37, -20, 42, 101] Can anyone explain how this works? As far as I have understood, __call__ is what is called when object() is called - calling the object as a function. What I don't understand is how nums.sort(key=DistanceFrom(10)). How does this work? Can anyone please explain this line? Thanks! A: __call__ in python allows a class to be run as if it's a function. You can try this out manually: >>> dis = DistanceFrom(10) >>> print dis(10), dis(5), dis(0) 0 5 10 >>> What sort does is call that function for every item in your list and uses the returned value as sort key. In this example you'll get a list back with the items closest to 10 first, and the one further away more towards the end. A: Here I have defined a function DistanceFrom() which can be used in a similar way to your class, but might be easier to follow >>> def DistanceFrom(origin): ... def f(x): ... retval = abs(x - origin) ... print "f(%s) = %s"%(x, retval) ... return retval ... return f ... >>> nums = [1, 37, 42, 101, 13, 9, -20] >>> nums.sort(key=DistanceFrom(10)) f(1) = 9 f(37) = 27 f(42) = 32 f(101) = 91 f(13) = 3 f(9) = 1 f(-20) = 30 >>> nums [9, 13, 1, 37, -20, 42, 101] So you see that the object returned by DistanceFrom is called once for each item of nums and then nums is returned sorted in accordance with the returned values A: It sorts list nums in place using a key function object DistanceFrom(10). It needs to be callable because key needs to be callable. The resulting output is sorted by their "remoteness" from 10, that is 9 is the closest value to 10, 101 is the farthest one. After the object is initialised and passed as a key parameter to the sort method, on each iteration it will be called with the current value (that's what x is) and returned value would be used to determine x's position in the resulting list. A: When you call something that means you are expecting it to return a value. When you create a class that has the __call__ method defined, you are dictating that an instance of that class can behave as a function does. For the purpose of this question, this: class DistanceFrom(object): def __init__(self, origin): self.origin = origin def __call__(self, x): return abs(x - self.origin) Is functionally equivalent to: def distance_from(origin, other): return abs(other - origin) As for the key argument to sort, here is your explanation straight from the Python documentation: key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly) A: The Python docs are quite good whenever I find I don't understand the fundamentals. I located these with google. The key parameter is a function that sort will call on the elements of the list. I located this doc by googling sort site:http://docs.python.org/ and then searching for key=. __call__ is a function you can add to an object to make that object callable as if it were a function. I found this doc by googling __call__ site:http://docs.python.org/ and then following the link to the doc for __call__.
Understanding __call__ and list.sort(key)
I have the following code I am trying to understand: >>> class DistanceFrom(object): def __init__(self, origin): self.origin = origin def __call__(self, x): return abs(x - self.origin) >>> nums = [1, 37, 42, 101, 13, 9, -20] >>> nums.sort(key=DistanceFrom(10)) >>> nums [9, 13, 1, 37, -20, 42, 101] Can anyone explain how this works? As far as I have understood, __call__ is what is called when object() is called - calling the object as a function. What I don't understand is how nums.sort(key=DistanceFrom(10)). How does this work? Can anyone please explain this line? Thanks!
[ "__call__ in python allows a class to be run as if it's a function. You can try this out manually:\n>>> dis = DistanceFrom(10)\n>>> print dis(10), dis(5), dis(0)\n0 5 10\n>>> \n\nWhat sort does is call that function for every item in your list and uses the returned value as sort key. In this example you'll get a li...
[ 8, 7, 4, 1, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0004034455_python_sorting.txt
Q: Python: Parsing JSON String List for Each JSON Object I use the json module and the dumps method to obtain a string which represents a list of json objects : import json jsonstring = json.dumps(data) I would like to iterate over this string to obtain each JSON object as a string. Any suggestions? Thanks in advance. P.S. I have tried the following: for jsonobject in jsonstring: print jsonobject But what happens is that each single letter is printed separately rather than the jsonobject as a whole. A: for jsonobject in json.loads(jasonstring): print jsonobject A: You should iterate over your data before you turn it into a string, then turn each element of the data into JSON: for d in data: jsonstring = json.dumps(d)
Python: Parsing JSON String List for Each JSON Object
I use the json module and the dumps method to obtain a string which represents a list of json objects : import json jsonstring = json.dumps(data) I would like to iterate over this string to obtain each JSON object as a string. Any suggestions? Thanks in advance. P.S. I have tried the following: for jsonobject in jsonstring: print jsonobject But what happens is that each single letter is printed separately rather than the jsonobject as a whole.
[ "for jsonobject in json.loads(jasonstring):\n print jsonobject\n\n", "You should iterate over your data before you turn it into a string, then turn each element of the data into JSON:\nfor d in data:\n jsonstring = json.dumps(d)\n\n" ]
[ 3, 1 ]
[]
[]
[ "json", "list", "python", "string" ]
stackoverflow_0004034599_json_list_python_string.txt
Q: Tweepy twitter oauth authentication not returning oauth_verifier I am using a python library called "tweepy" for twitter. When I try to authorize the user, twitter is supposed to redirect to a callback url with auth_token and oauth_verifier. I am getting only auth_token in the url. Anyone else had the same problem? A: Twitter only uses oauth_verifier (PINs) for desktop applications. For web applications, Twitter bypasses this and does not use it. You can re-check your application settings at http://dev.twitter.com/apps
Tweepy twitter oauth authentication not returning oauth_verifier
I am using a python library called "tweepy" for twitter. When I try to authorize the user, twitter is supposed to redirect to a callback url with auth_token and oauth_verifier. I am getting only auth_token in the url. Anyone else had the same problem?
[ "Twitter only uses oauth_verifier (PINs) for desktop applications. For web applications, Twitter bypasses this and does not use it. You can re-check your application settings at http://dev.twitter.com/apps\n" ]
[ 2 ]
[]
[]
[ "api", "oauth", "python", "tweepy", "twitter" ]
stackoverflow_0004033789_api_oauth_python_tweepy_twitter.txt
Q: Roman representation of integers Possible Duplicate: How do you find a roman numeral equivalent of an integer I am looking for a simple algorithm (preferably in Python). How to translate a given integer number to a Roman number? string Roman(int Num){...} For example, Roman(1981) must produce "MCMLXXXI". A: I needed the opposite one time (going from Roman numerals to int). Wikipedia has surprisingly detailed information on how Roman numerals work. Once you realize that things are this well-defined and that a specification is available this easily, translating it to code is fairly trivial. A: Here is a lengthy explanation how to do it with a lot of source code attached: http://www.faqs.org/docs/javap/c9/ex-9-3-answer.html But I think it could be done more efficient. A: Check out the code at this ActiveState link. The code looks fairly well documented. A: I can't think of a third party library that has this functionality. Sometimes you have to write some stuff yourself, although there are plenty of examples of how do to this online. Here is one from RoseIndia A: For hundreds, tens and units the rule is pretty much the same, i.e. you have a 1, 5 and 10 character the representation will be the same for each, just that the letters change. You could have a table of 10 entries which represents a template 0 - 1 = U 2 = UU 3 = UUU 4 = UF 5 = F 6 = FU 7 = FUU 8 = FUUU 9 = UT Now also have for units, tens and hundreds your table: Units = IVX Tens = XLC Hundreds = CDM Apply your template for the number to the letter representation so a U is replaced by the first character, an F by the second and a T by the 3rd. Thousands are just an M for each thousand. Build your string starting with the thousands, then the hundreds, then the tens and then the units. If you were building it backwards of course you could start with the units modding by 10, then construct your units string, divide by 10 and mod again and shift to the tens string, repeat with the hundreds string and when you get to the thousands string you will know it by the fact your string has just one character i.e. an M.
Roman representation of integers
Possible Duplicate: How do you find a roman numeral equivalent of an integer I am looking for a simple algorithm (preferably in Python). How to translate a given integer number to a Roman number? string Roman(int Num){...} For example, Roman(1981) must produce "MCMLXXXI".
[ "I needed the opposite one time (going from Roman numerals to int). Wikipedia has surprisingly detailed information on how Roman numerals work. Once you realize that things are this well-defined and that a specification is available this easily, translating it to code is fairly trivial.\n", "Here is a lengthy e...
[ 3, 1, 1, 1, 0 ]
[]
[]
[ "algorithm", "c++", "java", "python", "roman_numerals" ]
stackoverflow_0004035155_algorithm_c++_java_python_roman_numerals.txt
Q: Pylons, cookies not being destroyed I am trying to remove a cookie called "session" to logout a user. request.cookies.pop('session', None) response.set_cookie('session', '', max_age=-100, domain='.example.org') response.set_cookie('session', '', max_age=-100, domain='www.example.org') response.delete_cookie('session', '', domain='.example.org') response.delete_cookie('session', '', domain='www.example.org') As you can see, I am literally trying everything right now. Nothing seems to erase the cookie. Any help is appreciated. Thank you! A: If you're using Pylons' built-in sessions with Beaker, it is much simpler to use session.invalidate() and session.delete(). Are you using Beaker, or are you rolling your own solution for this ?
Pylons, cookies not being destroyed
I am trying to remove a cookie called "session" to logout a user. request.cookies.pop('session', None) response.set_cookie('session', '', max_age=-100, domain='.example.org') response.set_cookie('session', '', max_age=-100, domain='www.example.org') response.delete_cookie('session', '', domain='.example.org') response.delete_cookie('session', '', domain='www.example.org') As you can see, I am literally trying everything right now. Nothing seems to erase the cookie. Any help is appreciated. Thank you!
[ "If you're using Pylons' built-in sessions with Beaker, it is much simpler to use session.invalidate() and session.delete(). \nAre you using Beaker, or are you rolling your own solution for this ?\n" ]
[ 0 ]
[]
[]
[ "cookies", "pylons", "python", "session_cookies" ]
stackoverflow_0003936798_cookies_pylons_python_session_cookies.txt
Q: Python: 'import node.py' raises "No module named py"-error I have a file main.py like this: import node.py [my code...] and a node.py like this: [more of my code] When executing main.py, I get this error: File "/home/loldrup/repo/trunk/src/src/main.py", line 2, in <module> import node.py ImportError: No module named py A: You should just say import node. The . in the name makes python think you want to load a submodule named py of the packagenode, hence the error. All of this is explained in detail in the Python Tutorial. A: If you have a function named node in a module called node, the clearest thing to do is: from node import node This adds the name node to the local symbol table and makes it reference the function named node in the node module. It's often less confusing if you give the module and its members different names - though as you learn when you start working with the datetime class in the datetime module, it's not so confusing that the included batteries don't do it.
Python: 'import node.py' raises "No module named py"-error
I have a file main.py like this: import node.py [my code...] and a node.py like this: [more of my code] When executing main.py, I get this error: File "/home/loldrup/repo/trunk/src/src/main.py", line 2, in <module> import node.py ImportError: No module named py
[ "You should just say import node. The . in the name makes python think you want to load a submodule named py of the packagenode, hence the error. All of this is explained in detail in the Python Tutorial.\n", "If you have a function named node in a module called node, the clearest thing to do is:\nfrom node impor...
[ 9, 0 ]
[ "I friend helped me out. It turns out I shall use:\nfrom node import *\n\n" ]
[ -2 ]
[ "python", "python_import" ]
stackoverflow_0004032780_python_python_import.txt
Q: How to include annotation in JSON string? I've got a view that returns a list of shipments encoded as JSON... def get_new_shipments(request): # ... shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \ .annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount')) return json_response(shipments) def json_response(data): response = HttpResponse(mimetype='application/json') serializer = serializers.get_serializer("json")() data = list(data) serializer.serialize(data, ensure_ascii=False, stream=response) return response But I don't see those annotations in the JSON anywhere... how do I get them to be included? A: This seems to work: return HttpResponse(simplejson.dumps(list(shipments.values()), ensure_ascii=False, default=json_formatter), mimetype='application/json') def json_formatter(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() elif isinstance(obj, Decimal): return unicode(obj) else: raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj)) credit
How to include annotation in JSON string?
I've got a view that returns a list of shipments encoded as JSON... def get_new_shipments(request): # ... shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \ .annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount')) return json_response(shipments) def json_response(data): response = HttpResponse(mimetype='application/json') serializer = serializers.get_serializer("json")() data = list(data) serializer.serialize(data, ensure_ascii=False, stream=response) return response But I don't see those annotations in the JSON anywhere... how do I get them to be included?
[ "This seems to work:\nreturn HttpResponse(simplejson.dumps(list(shipments.values()), ensure_ascii=False, default=json_formatter), mimetype='application/json')\n\ndef json_formatter(obj):\n if isinstance(obj, datetime.datetime):\n return obj.isoformat()\n elif isinstance(obj, Decimal):\n return u...
[ 1 ]
[]
[]
[ "django", "python", "simplejson" ]
stackoverflow_0004035686_django_python_simplejson.txt
Q: Fastest DNS library for python What library is the fastest to make hundreds of DNS queries in multi-tasking. I've googled round DNS libraries for python. I found that adns is said to be fastest. But it's not Windows-compatible. Are there any cross-platform compatible DNS libraries for python? A: Twisted's DNS library is cross platform. Whether or not it's the "fastest" is debateable but Twisted performs very well on the whole. I'd be surprised if it couldn't saturate your I/O link. One point of note though: Twisted uses asynchronous I/O rather than multi-tasking to achieve concurrency. Async I/O is a very good mechanism for handling concurrent queries but it requires a different programming style from the typcial threaded approach. The learning curve can be steep but it's fairly short and, in my opinion, it's well worth the effort.
Fastest DNS library for python
What library is the fastest to make hundreds of DNS queries in multi-tasking. I've googled round DNS libraries for python. I found that adns is said to be fastest. But it's not Windows-compatible. Are there any cross-platform compatible DNS libraries for python?
[ "Twisted's DNS library is cross platform. Whether or not it's the \"fastest\" is debateable but Twisted performs very well on the whole. I'd be surprised if it couldn't saturate your I/O link.\nOne point of note though: Twisted uses asynchronous I/O rather than multi-tasking to achieve concurrency. Async I/O is a v...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0004034251_python.txt
Q: How can "k in d" be False, but "k in d.keys()" be True? I have some python code that's throwing a KeyError exception. So far I haven't been able to reproduce outside of the operating environment, so I can't post a reduced test case here. The code that's raising the exception is iterating through a loop like this: for k in d.keys(): if condition: del d[k] The del[k] line throws the exception. I've added a try/except clause around it and have been able to determine that k in d is False, but k in d.keys() is True. The keys of d are bound methods of old-style class instances. The class implements __cmp__ and __hash__, so that's where I've been focusing my attention. A: k in d.keys() will test equality iteratively for each key, while k in d uses __hash__, so your __hash__ may be broken (i.e. it returns different hashes for objects that compare equal). A: Simple example of what's broken, for interest: >>> count = 0 >>> class BrokenHash(object): ... def __hash__(self): ... global count ... count += 1 ... return count ... ... def __eq__(self, other): ... return True ... >>> foo = BrokenHash() >>> bar = BrokenHash() >>> foo is bar False >>> foo == bar True >>> baz = {bar:1} >>> foo in baz False >>> foo in baz.keys() True A: Don't delete items in d while iterating over it, store the keys you want to delete in a list and delete them in another loop: deleted = [] for k in d.keys(): if condition: deleted.append(k) for k in deleted: del d[k]
How can "k in d" be False, but "k in d.keys()" be True?
I have some python code that's throwing a KeyError exception. So far I haven't been able to reproduce outside of the operating environment, so I can't post a reduced test case here. The code that's raising the exception is iterating through a loop like this: for k in d.keys(): if condition: del d[k] The del[k] line throws the exception. I've added a try/except clause around it and have been able to determine that k in d is False, but k in d.keys() is True. The keys of d are bound methods of old-style class instances. The class implements __cmp__ and __hash__, so that's where I've been focusing my attention.
[ "k in d.keys() will test equality iteratively for each key, while k in d uses __hash__, so your __hash__ may be broken (i.e. it returns different hashes for objects that compare equal).\n", "Simple example of what's broken, for interest:\n>>> count = 0\n>>> class BrokenHash(object):\n... def __hash__(self):\n...
[ 18, 5, 4 ]
[ "What you're doing would throw a a concurrent modification exception in Java. d.keys() creates a list of the keys as they exist when you call it, but that list is now static - modifications to d will not change a stored version of d.keys(). So when you iterate over d.keys() but delete items, you end up with the pos...
[ -1 ]
[ "dictionary", "python", "python_2.x" ]
stackoverflow_0004036114_dictionary_python_python_2.x.txt
Q: Subtracting the current and previous item in a list It is very common to write a loop and remember the previous. I want a generator that does that for me. Something like: import operator def foo(it): it = iter(it) f = it.next() for s in it: yield f, s f = s Now subtract pair-wise. L = [0, 3, 4, 10, 2, 3] print list(foo(L)) print [x[1] - x[0] for x in foo(L)] print map(lambda x: -operator.sub(*x), foo(L)) # SAME Outputs: [(0, 3), (3, 4), (4, 10), (10, 2), (2, 3)] [3, 1, 6, -8, 1] [3, 1, 6, -8, 1] What is a good name for this operation? What is a better way to write this? Is there a built-in function that does something similar? Trying to use 'map' didn't simplify it. What does? A: [y - x for x,y in zip(L,L[1:])] A: l = [(0,3), (3,4), (4,10), (10,2), (2,3)] print [(y-x) for (x,y) in l] Outputs: [3, 1, 6, -8, 1] A: Recipe from iterools: from itertools import izip, tee def pairwise(iterable): "s -> (s0,s1), (s1,s2), (s2, s3), ..." a, b = tee(iterable) next(b, None) return izip(a, b) and then: >>> L = [0, 3, 4, 10, 2, 3] >>> [b - a for a, b in pairwise(L)] [3, 1, 6, -8, 1] [EDIT] Also, this works (Python < 3): >>> map(lambda(a, b):b - a, pairwise(L))
Subtracting the current and previous item in a list
It is very common to write a loop and remember the previous. I want a generator that does that for me. Something like: import operator def foo(it): it = iter(it) f = it.next() for s in it: yield f, s f = s Now subtract pair-wise. L = [0, 3, 4, 10, 2, 3] print list(foo(L)) print [x[1] - x[0] for x in foo(L)] print map(lambda x: -operator.sub(*x), foo(L)) # SAME Outputs: [(0, 3), (3, 4), (4, 10), (10, 2), (2, 3)] [3, 1, 6, -8, 1] [3, 1, 6, -8, 1] What is a good name for this operation? What is a better way to write this? Is there a built-in function that does something similar? Trying to use 'map' didn't simplify it. What does?
[ "[y - x for x,y in zip(L,L[1:])]\n\n", "l = [(0,3), (3,4), (4,10), (10,2), (2,3)]\nprint [(y-x) for (x,y) in l]\n\nOutputs: [3, 1, 6, -8, 1]\n", "Recipe from iterools:\nfrom itertools import izip, tee\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, N...
[ 47, 4, 4 ]
[]
[]
[ "python" ]
stackoverflow_0004029436_python.txt
Q: 3rd party applications inside iFrames? I am about to build a web application and I want to allow other developers extend it with their own applications. Should I do this with iFrames like Facebook? Is this a good practice? Are there other alternatives that let other developers extend my application (that is for the user it looks like it's from my application). To be specific: I want developers to be able to code applications that is embedded on my web application. Eg. if I have a file on my application they could provide a way for the users to interact with that file. Maybe a "preview" application that let the users preview the file. Another application might draw a mindmap tree view of all the user's files. What is the best way of doing this? iFrame + Restful API on backend for data exchange? Let them insert javascript on backend + frontend + html + css on my web application? Other alternatives? A: If you meant "embed" rather than "extend" and you just want people to drop a little box on a page and that's it, then an iframe should be fine. However, if you want two-way communication or mashupability — rather than "opaque blob of HTML and hope for the best" communication — then a JavaScript or REST API might be a better call. More specifics would make for an easier answer. If the functionality you need is on the level of an embedded ad or stackoverlflow flair then an iframe would work, if the functionality is more along the lines of a Google Map then an API of some sort would work better. A: It depends on what you mean by "extend". When you use iFrames with 3rd parties, presumably vended from different domains than the host page, then you are constrained by cross-domain issues and cannot interact with the contents of those iFrames. If that's not an issue for you, then you can go ahead and try that strategy, but I can't see how merely adding iFrames without interopability is "extending" your web application.
3rd party applications inside iFrames?
I am about to build a web application and I want to allow other developers extend it with their own applications. Should I do this with iFrames like Facebook? Is this a good practice? Are there other alternatives that let other developers extend my application (that is for the user it looks like it's from my application). To be specific: I want developers to be able to code applications that is embedded on my web application. Eg. if I have a file on my application they could provide a way for the users to interact with that file. Maybe a "preview" application that let the users preview the file. Another application might draw a mindmap tree view of all the user's files. What is the best way of doing this? iFrame + Restful API on backend for data exchange? Let them insert javascript on backend + frontend + html + css on my web application? Other alternatives?
[ "If you meant \"embed\" rather than \"extend\" and you just want people to drop a little box on a page and that's it, then an iframe should be fine.\nHowever, if you want two-way communication or mashupability — rather than \"opaque blob of HTML and hope for the best\" communication — then a JavaScript or REST API ...
[ 1, 0 ]
[]
[]
[ "html", "javascript", "python", "ruby" ]
stackoverflow_0004033325_html_javascript_python_ruby.txt
Q: WxPython Incompatible With Snow Leopard? Recently I upgraded to Snow Leopard, and now I can't run programs built with wxPython. The errors I get are (from Eclipse + PyDev): import wx File "/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT/System/Library/Frameworks /Python.framework/Versions/2.6/Extras/lib/ python/wx-2.8-mac-unicode/wx/__init__.py", line 45, in <module> File "/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib /python/wx-2.8-mac-unicode/wx/_core.py", line 4, in <module> ImportError:/System/Library/Frameworks /Python.framework/Versions/2.6/Extras/lib/python /wx-2.8-mac-unicode/wx/_core_.so: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode) I don't really understand them and would appreciate if you could help me to do so, also, if you do know what's going on, how can I go about fixing them? Maybe this has something to do with the fact that Snow Leopard is 64-bit? Thanks!! A: The problem is that WxPython is only available on the Mac in 32-bit mode; however, by default, Python will start up in 64-bit mode. To fix this problem, create the following shell script named python_32: #! /bin/bash export VERSIONER_PYTHON_PREFER_32_BIT=yes /usr/bin/python "$@" Make the script executable (chmod a+x python_32) and place the script in your path. Now, simply invoke python_32 to get an interactive Python console in which you can use WxPython. If you want to write a Python script that uses this, you can use the shebang: #! /usr/bin/env python_32. Now to explain... the basic problem is that 32-bit and 64-bit code uses a different application binary interface (ABI), and so 32-bit code and 64-bit code cannot coexist in the same library/executable/process. In order to support 64-bit mode, it needs to have been compiled in 64-bit mode; likewise, to support 32-bit mode, it needs to have been compiled in 32-bit mode. Under OS X, it is possible, using universal binaries to support both... however, it needs to be compiled in both modes (and then merged). WxWidgets probably uses Carbon, which is only available in 32-bit mode (Cocoa is available in both 32-bit and 64-bit mode... Apple didn't bother making Carbon available in both modes, since it is being deprecated), which would explain why WxPython, in turn, could only be provided in 32-bit mode. This, in turn, means that using it in Python requires you to launch Python in 32-bit mode (Python is a universal binary with both 32-bit and 64-bit versions of itself available in the same binary file, so it can be launched in either mode). Alternative Option I don't recommend doing this, because I think you should leave the defaults as they are, but since you might not have enough shell scripting knowledge (you need to use "./python_32" or place it in a folder that is listed in your "$PATH" environment variable and invoke it as "python_32") to follow the former option, you might want to simply execute the following command which will make 32-bit mode the default: defaults write com.apple.versioner.python Prefer-32-Bit -bool yes If you decide you want to switch back into 64-bit mode, you can then use the following command: defaults write com.apple.versioner.python Prefer-32-Bit -bool no Note that both commands are to be executed on the Terminal (not within Python). Source I should point out that both recomendations are based on man python on Mac OS X. So, if you have any other questions, you should definitely read the man page as the error message has urged you to do. A: While I see this is already answered, the answer is slightly wrong. The 2.9 series DOES have a Mac 64-bit build, albeit only for Python 2.7. See http://wxpython.org/download.php and look for the Cocoa build. From what I gather on the wxPython mailing list and IRC channel, you'll want to download a Python 64-bit build from python.org rather than using the Mac-included snake. A: You might also want to try arch command when invoking python:arch -i386 /usr/bin/python2.6 if you can't get Python to run with the correct environmental settings. The '-i386' switch makes a universal binary run in Intel 32-bit mode. '-x86_64' makes it run in Intel 64-bit mode. -ppc and -ppc64 is for PPC architectures. If you still get errors then it might point to a compile issue. On my machine I have the stock apple Python and a version from Macports. The arch command works using the apple binaries and I can import wx successfully from the command line but I still get errors from the Macports binary: Bad CPU type in executable I'm guessing I'll have to go back and recompile my Macports python binary and make sure it produces a universal binary or something like that (sigh). A: Another solution is to download and install Python 2.6 for OS X from python.org and install wxPython for OS X from here with it. The python.org 2.6 is newer (2.6.5 as of now) than the Apple-supplied Python (2.6.1) in Snow Leopard and it is 32-bit only. A: This worked for me (from http://www.python-forum.de/viewtopic.php?f=19&t=24322&view=previous) In .profile, add the following line alias py32='arch -i386 /Library/Frameworks/Python.framework/Versions/2.7/bin/pythonw2.7' then invoke your script with py32 A: Hm. The script provided didn't work for me-- I changed it as follows: #! /bin/bash echo "-----------------Python 2.6 - 32 Bit setup --------------------" echo "Running" $1 export VERSIONER_PYTHON_PREFER_32_BIT yes /usr/bin/python2.6 $1 Still didn't work. I get the same message. Re-read the man page to make sure I wasn't misunderstanding, and I'm no further forward: ImportError: /usr/local/lib/wxPython-unicode-2.8.10.1/lib/python2.6/site-packages/wx-2.8-mac-unicode/wx/_core_.so: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode) Not really sure why this doesn't work, unless there is some sort of rebuild that needs to be done against the wx core that gives it 32/64-bit compatibility. Any suggestions, anyone? I'd like to use the out-of-the-box Python install from Apple (be easier for my work), and I'd like to avoid any more ridiculous hacks
WxPython Incompatible With Snow Leopard?
Recently I upgraded to Snow Leopard, and now I can't run programs built with wxPython. The errors I get are (from Eclipse + PyDev): import wx File "/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT/System/Library/Frameworks /Python.framework/Versions/2.6/Extras/lib/ python/wx-2.8-mac-unicode/wx/__init__.py", line 45, in <module> File "/var/tmp/wxWidgets/wxWidgets-13~231/2.6/DSTROOT /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib /python/wx-2.8-mac-unicode/wx/_core.py", line 4, in <module> ImportError:/System/Library/Frameworks /Python.framework/Versions/2.6/Extras/lib/python /wx-2.8-mac-unicode/wx/_core_.so: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode) I don't really understand them and would appreciate if you could help me to do so, also, if you do know what's going on, how can I go about fixing them? Maybe this has something to do with the fact that Snow Leopard is 64-bit? Thanks!!
[ "The problem is that WxPython is only available on the Mac in 32-bit mode; however, by default, Python will start up in 64-bit mode. To fix this problem, create the following shell script named python_32:\n\n#! /bin/bash\nexport VERSIONER_PYTHON_PREFER_32_BIT=yes\n/usr/bin/python \"$@\"\n\nMake the script executabl...
[ 25, 15, 2, 1, 1, 0 ]
[]
[]
[ "eclipse", "pydev", "python", "wxpython" ]
stackoverflow_0002565201_eclipse_pydev_python_wxpython.txt
Q: How to interface a simple keypad with the computer and mobile using PYTHON? The problem is that i want to interface my mobile phone with my computer using a keypad in between. The interfacing should be done in Python environment as this would help me in my further work. the things which i need is inteface my computer with the keypad using python interface the same keypad with a mobile phone so that i can control the general features of my mobile phone with that keypad using the python code. A: The most general way to connect your computer to a phone would be over TCP/IP, likely delivered via WiFi to your phone. If using an Android, BlueTooth would be another option, but iOS will not connect to unapproved BT devices. Programming on the handset will likely have to be done in the native language. It's an absolute requirement of iOS, and I'm not sure if you can use Python/Jython to build a full app on Android yet. On the PC side, you could easily use Python, perhaps its socket module to talk with the handset over TCP/IP or pySerial's serial if you use BlueTooth RFCOMM/SPP; though managing the actual BT connection is very complex and very sensitive to drivers.
How to interface a simple keypad with the computer and mobile using PYTHON?
The problem is that i want to interface my mobile phone with my computer using a keypad in between. The interfacing should be done in Python environment as this would help me in my further work. the things which i need is inteface my computer with the keypad using python interface the same keypad with a mobile phone so that i can control the general features of my mobile phone with that keypad using the python code.
[ "The most general way to connect your computer to a phone would be over TCP/IP, likely delivered via WiFi to your phone. If using an Android, BlueTooth would be another option, but iOS will not connect to unapproved BT devices.\nProgramming on the handset will likely have to be done in the native language. It's a...
[ 0 ]
[]
[]
[ "keypad", "python", "user_interface" ]
stackoverflow_0004035334_keypad_python_user_interface.txt
Q: How to limit program's execution time when using subprocess? I want to use subprocess to run a program and I need to limit the execution time. For example, I want to kill it if it runs for more than 2 seconds. For common programs, kill() works well. But if I try to run /usr/bin/time something, kill() can’t really kill the program. My code below seems doesn’t work well. The program is still running. import subprocess import time exec_proc = subprocess.Popen("/usr/bin/time -f \"%e\\n%M\" ./son > /dev/null", stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True) max_time = 1 cur_time = 0.0 return_code = 0 while cur_time <= max_time: if exec_proc.poll() != None: return_code = exec_proc.poll() break time.sleep(0.1) cur_time += 0.1 if cur_time > max_time: exec_proc.kill() A: If you're using Python 2.6 or later, you can use the multiprocessing module. from multiprocessing import Process def f(): # Stuff to run your process here p = Process(target=f) p.start() p.join(timeout) if p.is_alive(): p.terminate() Actually, multiprocessing is the wrong module for this task since it is just a way to control how long a thread runs. You have no control over any children the thread may run. As singularity suggests, using signal.alarm is the normal approach. import signal import subprocess def handle_alarm(signum, frame): # If the alarm is triggered, we're still in the exec_proc.communicate() # call, so use exec_proc.kill() to end the process. frame.f_locals['self'].kill() max_time = ... stdout = stderr = None signal.signal(signal.SIGALRM, handle_alarm) exec_proc = subprocess.Popen(['time', 'ping', '-c', '5', 'google.com'], stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) signal.alarm(max_time) try: (stdout, stderr) = exec_proc.communicate() except IOError: # process was killed due to exceeding the alarm finally: signal.alarm(0) # do stuff with stdout/stderr if they're not None A: do it like so in your command line: perl -e 'alarm shift @ARGV; exec @ARGV' <timeout> <your_command> this will run the command <your_command> and terminate it in <timeout> second. a dummy example : # set time out to 5, so that the command will be killed after 5 second command = ['perl', '-e', "'alarm shift @ARGV; exec @ARGV'", "5"] command += ["ping", "www.google.com"] exec_proc = subprocess.Popen(command) or you can use the signal.alarm() if you want it with python but it's the same. A: I use os.kill() but am not sure if it works on all OSes. Pseudo code follows, and see Doug Hellman's page. proc = subprocess.Popen(['google-chrome']) os.kill(proc.pid, signal.SIGUSR1)</code>
How to limit program's execution time when using subprocess?
I want to use subprocess to run a program and I need to limit the execution time. For example, I want to kill it if it runs for more than 2 seconds. For common programs, kill() works well. But if I try to run /usr/bin/time something, kill() can’t really kill the program. My code below seems doesn’t work well. The program is still running. import subprocess import time exec_proc = subprocess.Popen("/usr/bin/time -f \"%e\\n%M\" ./son > /dev/null", stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True) max_time = 1 cur_time = 0.0 return_code = 0 while cur_time <= max_time: if exec_proc.poll() != None: return_code = exec_proc.poll() break time.sleep(0.1) cur_time += 0.1 if cur_time > max_time: exec_proc.kill()
[ "If you're using Python 2.6 or later, you can use the multiprocessing module.\nfrom multiprocessing import Process\n\ndef f():\n # Stuff to run your process here\n\np = Process(target=f)\np.start()\np.join(timeout)\nif p.is_alive():\n p.terminate()\n\n\nActually, multiprocessing is the wrong module for this t...
[ 9, 3, 0 ]
[]
[]
[ "kill", "python", "subprocess" ]
stackoverflow_0004033578_kill_python_subprocess.txt
Q: Tkinter Canvas Does Not Display I'm attempting to learn some Python and Tkinter. The sample code below is intended to put two windows on the screen, a few buttons, and a Canvas with an image in it and some lines drawn on it. The windows and buttons appear just fine, however I'm not seeing either the canvas image or canvas lines. I'd appreciate some help to figure out what's need to make my canvas display. from Tkinter import * import Image, ImageTk class App: def __init__(self, master): def scrollWheelClicked(event): print "Wheel wheeled" frame = Frame(master) frame.pack() self.button = Button(frame, text = "QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) top = Toplevel() canvas = Canvas(master=top, width=600, height=600) image = Image.open("c:\lena.jpg") photo = ImageTk.PhotoImage(image) item = canvas.create_image(0, 0, image=photo) canvas.create_line(0, 0, 200, 100) canvas.create_line(0, 100, 200, 0, fill="red", dash=(4, 4)) canvas.create_rectangle(50, 25, 150, 75, fill="blue") canvas.pack testBtn = Button(top, text = "test button") testBtn.pack() def say_hi(self): print "hi there everyone!" root = Tk() app = App(root) root.mainloop() A: I solved this problem: self.photo = ImageTk.PhotoImage(image) self.item = canvas.create_image(0, 0, image=self.photo) A reference to the ImageTk instance must be stored somewhere, or when your App.__init__() method returns, it will be garbage collected, and the canvas will not be able to display it. (Tkinter does not keep a reference to the image.) One way to keep a reference to it is by storing it in "self.photo", or a variable named 'photo', or, like most programmers do for constant variables (variables that don't change, like 'TEN = 10'), 'PHOTO = PhotoImage(...)' Of why... I have no idea. Importing the module 'gc' (Python 3's garbage collection module, built in) and running gc.disable() doesn't work. (If you want to try it: https://docs.python.org/3/library/gc.html) A: You need parenthesis when calling pack on the canvas object. Otherwise, you're just referring to the function object, not calling it. For example: canvas.pack() Another example: >>>def hello(): ... print "hello world" ... return >>>hello returns the function reference (function hello at 0x....) >>>hello() actually calls the hello function
Tkinter Canvas Does Not Display
I'm attempting to learn some Python and Tkinter. The sample code below is intended to put two windows on the screen, a few buttons, and a Canvas with an image in it and some lines drawn on it. The windows and buttons appear just fine, however I'm not seeing either the canvas image or canvas lines. I'd appreciate some help to figure out what's need to make my canvas display. from Tkinter import * import Image, ImageTk class App: def __init__(self, master): def scrollWheelClicked(event): print "Wheel wheeled" frame = Frame(master) frame.pack() self.button = Button(frame, text = "QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) top = Toplevel() canvas = Canvas(master=top, width=600, height=600) image = Image.open("c:\lena.jpg") photo = ImageTk.PhotoImage(image) item = canvas.create_image(0, 0, image=photo) canvas.create_line(0, 0, 200, 100) canvas.create_line(0, 100, 200, 0, fill="red", dash=(4, 4)) canvas.create_rectangle(50, 25, 150, 75, fill="blue") canvas.pack testBtn = Button(top, text = "test button") testBtn.pack() def say_hi(self): print "hi there everyone!" root = Tk() app = App(root) root.mainloop()
[ "I solved this problem:\nself.photo = ImageTk.PhotoImage(image)\nself.item = canvas.create_image(0, 0, image=self.photo)\n\nA reference to the ImageTk instance must be stored somewhere, or when your App.__init__() method returns, it will be garbage collected, and the canvas will not be able to display it. (Tkinter...
[ 7, 4 ]
[]
[]
[ "python", "tkinter", "tkinter_canvas" ]
stackoverflow_0002223985_python_tkinter_tkinter_canvas.txt
Q: Apache Chainsaw with Python and multiple tabs I am using Apache Chainsaw with python (using the XMLLayout formatter, sending log messages to Chainsaw) How can I make Chainsaw display multiple log tabs, one for each logging source ? currently it displays all messages, regardless of which process sent them, to a single tab A: By default, Chainsaw routes events to tabs based by looking at the values of 'hostname' and 'application' properties of each logging event (essentially MDC entries if they exist). If you define those properties in your XML representation of each logging event, Chainsaw will route events to individual tabs based on those values. You can change the default tab routing expression from 'PROP.hostname - PROP.application' to anything you'd like - just use the expression syntax to identify which field or property name to use in the routing of events (in the application-wide preferences screen). More info on the expression syntax is available from the Help/Tutorial menu. By the way, there is an updated version of Chainsaw - a developer snapshot, will be released soon - available here with a ton of new features: http://people.apache.org/~sdeboy
Apache Chainsaw with Python and multiple tabs
I am using Apache Chainsaw with python (using the XMLLayout formatter, sending log messages to Chainsaw) How can I make Chainsaw display multiple log tabs, one for each logging source ? currently it displays all messages, regardless of which process sent them, to a single tab
[ "By default, Chainsaw routes events to tabs based by looking at the values of 'hostname' and 'application' properties of each logging event (essentially MDC entries if they exist). \nIf you define those properties in your XML representation of each logging event, Chainsaw will route events to individual tabs based...
[ 1 ]
[]
[]
[ "log4j", "logging", "python" ]
stackoverflow_0004034047_log4j_logging_python.txt
Q: Search app in Django I am building search app using django & sphinx. I got the setup working but when I search I get irrelevant results. Here is what I do - # this is in my trial_data Model search = SphinxSearch( index = 'trial_data trial_datastemmed', weights = {'name': 100,}, mode = 'SPH_MATCH_ALL', rankmode = 'SPH_RANK_BM25', ) When I search I get this (from my trial data) - from trial.models import * res = trial_data.search.query('godfather') for i in res: print i 3 Godfathers (7.000000) Bonanno: A Godfather's Story (1999) (6.400000) Disco Godfather (4.300000) Godfather (6.100000) Godfather: The Legend Continues (0.000000) Herschell Gordon Lewis: The Godfather of Gore (2010) (6.900000) Mafia: Farewell to the Godfather (0.000000) Mumbai Godfather (2.600000) Russian Godfathers (2005) (7.000000) Stan Tracey: The Godfather of British Jazz (2003) (6.200000) The Black Godfather (3.500000) The Burglar's Godfather (0.000000) The Fairy Godfather (0.000000) The Fairy Godfather (0.000000) The Godfather (9.200000) The Godfather (1991) (6.400000) the problem is the most relevant result for "godfather" is shown at 19th position. All the top results are junk. How can I order or sort my results using Django-sphinx. Rather, what can I do to make the results more relevant using this setup. NOTE: I am using python 2.6.x + django 1.2.x + sphinx 0.99 + django-sphinx 2.3.3 + mysql Also, the data i custom made & is only about 100 rows with only one field name searchable. There is one more fields rating (which is what you see in brackets). rating field is an attribute (non searchable). A: As far as i can tell, there are two ways of going about this. Firstly, there are sort modes SPH_SORT_RELEVANCE, SPH_SORT_ATTR_DESC, SPH_SORT_ATTR_ASC, SPH_SORT_TIME_SEGMENTS, SPH_SORT_EXTENDED. I assume that keyword in the SphinxSearch constructor would be sortmode, but I couldn't find the docs. search = SphinxSearch( index = 'trial_data trial_datastemmed', weights = {'name': 100,}, mode = 'SPH_MATCH_ALL', rankmode = 'SPH_RANK_BM25', sortmode = 'SPH_SORT_RELEVANCE', # this was added ) Secondly, you can specify at time of query the sort mode: res = trial_data.search.query('godfather').order_by('@relevance') Both of these answers are guesses from looking at http://djangosnippets.org/snippets/231/. Let us know if it worked for you.
Search app in Django
I am building search app using django & sphinx. I got the setup working but when I search I get irrelevant results. Here is what I do - # this is in my trial_data Model search = SphinxSearch( index = 'trial_data trial_datastemmed', weights = {'name': 100,}, mode = 'SPH_MATCH_ALL', rankmode = 'SPH_RANK_BM25', ) When I search I get this (from my trial data) - from trial.models import * res = trial_data.search.query('godfather') for i in res: print i 3 Godfathers (7.000000) Bonanno: A Godfather's Story (1999) (6.400000) Disco Godfather (4.300000) Godfather (6.100000) Godfather: The Legend Continues (0.000000) Herschell Gordon Lewis: The Godfather of Gore (2010) (6.900000) Mafia: Farewell to the Godfather (0.000000) Mumbai Godfather (2.600000) Russian Godfathers (2005) (7.000000) Stan Tracey: The Godfather of British Jazz (2003) (6.200000) The Black Godfather (3.500000) The Burglar's Godfather (0.000000) The Fairy Godfather (0.000000) The Fairy Godfather (0.000000) The Godfather (9.200000) The Godfather (1991) (6.400000) the problem is the most relevant result for "godfather" is shown at 19th position. All the top results are junk. How can I order or sort my results using Django-sphinx. Rather, what can I do to make the results more relevant using this setup. NOTE: I am using python 2.6.x + django 1.2.x + sphinx 0.99 + django-sphinx 2.3.3 + mysql Also, the data i custom made & is only about 100 rows with only one field name searchable. There is one more fields rating (which is what you see in brackets). rating field is an attribute (non searchable).
[ "As far as i can tell, there are two ways of going about this.\nFirstly, there are sort modes SPH_SORT_RELEVANCE, SPH_SORT_ATTR_DESC, SPH_SORT_ATTR_ASC, SPH_SORT_TIME_SEGMENTS, SPH_SORT_EXTENDED. I assume that keyword in the SphinxSearch constructor would be sortmode, but I couldn't find the docs.\nsearch = Sp...
[ 2 ]
[]
[]
[ "django", "django_sphinx", "python", "search", "sphinx" ]
stackoverflow_0004036936_django_django_sphinx_python_search_sphinx.txt
Q: A good way to make Django geolocation aware? - Django/Geolocation I would like to be able to associate various models (Venues, places, landmarks) with a City/Country. But I am not sure what some good ways of implementing this would be. I'm following a simple route, I have implemented a Country and City model. Whenever a new city or country is mentioned it is automatically created. Unfortunately I have various problems: The database can easily be polluted Django has no real knowledge of what those City/Countries really are Any tips or ideas? Thanks! :) A: A good starting places would be to get a location dataset from a service like Geonames. There is also GeoDjango which came up in this question. As you encounter new location names, check them against your larger dataset before adding them. For your 2nd point, you'll need to design this into your object model and write your code accordingly. Here are some other things you may want to consider: Aliases & Abbreviations These come up more than you would think. People often use the names of suburbs or neighbourhoods that aren't official towns. You can also consider ones like LA -> Los Angeles MTL for Montreal, MT. Forest -> Mount Forest, Saint vs (ST st. ST-), etc. Fuzzy Search Looking up city names is much easier when differences in spelling are accounted for. This also helps reduce the number of duplicate names for the same place. You can do this by pre-computing the Soundex or Double Metaphone values for the cities in your data set. When performing a lookup, compute the value for the search term and compare against the pre-computed values. This will work best for English, but you may have success with other romance language derivatives (unsure what your options are beyond these). Location Equivalence/Inclusion Be able to determine that Brooklyn is a borough of New York City. At the end of the day, this is a hard problem, but applying these suggestions should greatly reduce the amount of data corruption and other headaches you have to deal with. A: Geocoding datasets from yahoo and google can be a good starting poing, Also take a look at geopy library in django.
A good way to make Django geolocation aware? - Django/Geolocation
I would like to be able to associate various models (Venues, places, landmarks) with a City/Country. But I am not sure what some good ways of implementing this would be. I'm following a simple route, I have implemented a Country and City model. Whenever a new city or country is mentioned it is automatically created. Unfortunately I have various problems: The database can easily be polluted Django has no real knowledge of what those City/Countries really are Any tips or ideas? Thanks! :)
[ "A good starting places would be to get a location dataset from a service like Geonames. There is also GeoDjango which came up in this question.\nAs you encounter new location names, check them against your larger dataset before adding them. For your 2nd point, you'll need to design this into your object model and ...
[ 7, 0 ]
[]
[]
[ "django", "geolocation", "python" ]
stackoverflow_0004035195_django_geolocation_python.txt
Q: how to reference compiled python code in IronPython? we need to reference .py code from C#. This was solved using IronPython 2.6 The issue arises from the fact that .py code uses 'import customlib' which is a library compiled into customlib.pyc IronPython gives error: IronPython.Runtime.Exceptions.ImportException: No module named customlib attempted solution: in python code add reference like this: import sys sys.path.append('c:\path to customlib') that seems to work for other .py files but not for .pyc Questions: 1) how do you reference .pyc in IronPython? 2) If its not possible, what are the alternatives to use .py and .pyc in C#.Net ? (obviously we don't have .py source code form customlib.pyc) C# code that works for .py but not if .py imports .pyc: ScriptEngine engine = Python.CreateEngine(); ScriptScope pyScope = null; ScriptSource ss = null; ... pyScope = engine.CreateScope(); ss = engine.CreateScriptSourceFromFile(@"C:\test.py"); ss.Execute(pyScope); ... int result = (int)engine.Operations.InvokeMember(pyScope, "funcName") thanks! A: *.pyc files are CPython specific. You'll have to decompile them or invoke CPython. For decompiling try: http://sourceforge.net/projects/unpyc/ Free Python decompiler that is not an online service?
how to reference compiled python code in IronPython?
we need to reference .py code from C#. This was solved using IronPython 2.6 The issue arises from the fact that .py code uses 'import customlib' which is a library compiled into customlib.pyc IronPython gives error: IronPython.Runtime.Exceptions.ImportException: No module named customlib attempted solution: in python code add reference like this: import sys sys.path.append('c:\path to customlib') that seems to work for other .py files but not for .pyc Questions: 1) how do you reference .pyc in IronPython? 2) If its not possible, what are the alternatives to use .py and .pyc in C#.Net ? (obviously we don't have .py source code form customlib.pyc) C# code that works for .py but not if .py imports .pyc: ScriptEngine engine = Python.CreateEngine(); ScriptScope pyScope = null; ScriptSource ss = null; ... pyScope = engine.CreateScope(); ss = engine.CreateScriptSourceFromFile(@"C:\test.py"); ss.Execute(pyScope); ... int result = (int)engine.Operations.InvokeMember(pyScope, "funcName") thanks!
[ "*.pyc files are CPython specific. You'll have to decompile them or invoke CPython.\nFor decompiling try:\n\nhttp://sourceforge.net/projects/unpyc/\nFree Python decompiler that is not an online service?\n\n" ]
[ 2 ]
[]
[]
[ "c#", "ironpython", "python" ]
stackoverflow_0004037133_c#_ironpython_python.txt
Q: Google app engine regular expression I'm working on a Google appengine project and I've encountered a quandary. The following should (if the regex's are normal) redirect everything which does not contain the word "test" to the MainPage class, and the rest to the TestPage class. application = webapp.WSGIApplication( [ ('[^(test)]*', MainPage), ('.+', TestPage) ], debug=True) Instead, I find that the regular expression is being interpreted: ('[^tes]*', MainPage) This means that anything which includes a t, e, or s will NOT direct to MainPage (in this case, it will direct to TestPage). Obviously, the workaround is to re-write the TestPage regex, but I don't want to have to make a work around. This should work without being re-written. Am I missing some library somewhere? Is this a configuration issue? I have far less issue with calling a function or setting a property before running run_wsgi_app, but this looks inconsistent as is. UPDATE It turns out that the culprit was two things. First it was a mistake on my part in the syntax (Mea culpa). Second, the tool I had used to confirm the regular expression said that the expression would not match "test " but it would match "t est ". A: Actually, it's being interpreted as identical to any rearrangement of the characters aside from the leading caret within the square brackets, such as [^est()]. Standard regular expression syntax includes no straightforward way to specify the complement of the language matched by a particular regex. In this case, you don't need to worry about that. Follow Erik Noren's advice and change the order of the matching expressions like so: application = webapp.WSGIApplication( [ ('test', TestPage) ('.+', MainPage), ], debug=True) This straightforwardly accomplishes the same result. A: Why not just invert it? Instead of checking for [not 'test'] the check for test is simpler. Route that match to TestPage and the rest to MainPage. The difference of (not working): '[^(test)]*' and 'test' Unless I'm completely mistaken. A: The square-bracket notation in regex is a set of characters, and parens have no special meaning within them. So [^(test)] matches any character other than 't', 'e', 's', '(', or ')'
Google app engine regular expression
I'm working on a Google appengine project and I've encountered a quandary. The following should (if the regex's are normal) redirect everything which does not contain the word "test" to the MainPage class, and the rest to the TestPage class. application = webapp.WSGIApplication( [ ('[^(test)]*', MainPage), ('.+', TestPage) ], debug=True) Instead, I find that the regular expression is being interpreted: ('[^tes]*', MainPage) This means that anything which includes a t, e, or s will NOT direct to MainPage (in this case, it will direct to TestPage). Obviously, the workaround is to re-write the TestPage regex, but I don't want to have to make a work around. This should work without being re-written. Am I missing some library somewhere? Is this a configuration issue? I have far less issue with calling a function or setting a property before running run_wsgi_app, but this looks inconsistent as is. UPDATE It turns out that the culprit was two things. First it was a mistake on my part in the syntax (Mea culpa). Second, the tool I had used to confirm the regular expression said that the expression would not match "test " but it would match "t est ".
[ "Actually, it's being interpreted as identical to any rearrangement of the characters aside from the leading caret within the square brackets, such as [^est()]. Standard regular expression syntax includes no straightforward way to specify the complement of the language matched by a particular regex.\nIn this case, ...
[ 7, 3, 3 ]
[]
[]
[ "google_app_engine", "python", "regex" ]
stackoverflow_0004037484_google_app_engine_python_regex.txt
Q: Add a python script at runtime I am beginning python and working on a project, and one thing I would like to be able to do is download and run a script dynamically at runtime. The general idea is to be able to connect to a server, download a python script on demand, and run that script that was just downloaded without having to restart the program or hard code that specific script in to the program. The program I'm working with uses Python for scripting and execution, and C++ for the other code such as rendering and math. I would like to be able to use python to run scripts that have been downloaded from a server (for things such as user generated content). I was wondering if that was possible, or if I should use another scripting language (possibly LUA) for that situation? Thanks, Th3flyboy A: You can definitely do this. Use urllib to download or generate the script, then import it. It'll work like a charm every time, as long as you download the script to your PYTHONPATH. For example: from urllib import urlretrieve urlretrieve('http://www.mysite.com/myscript.py', '/home/me/script.py') import script You can also generate the script yourself from a template, pulling data from online (perhaps in xml or from a database) and using Python's text processing capabilities to make the necessary adjustments. A: This is quite possible, though hugely insecure. You need to download using urllib2.urlopen and then executing the result using exec. I am reluctant to explain further because of the security implications. Edit: An explanation about the security issues. In Python (CPython) currently there is no way to have a sandbox. The result is any untrusted code has access to all the capabilities Python has on your machine (for the specific user). This can be partially solved by using a specialised user, and better operating system level solutions. They are complicated, however. An example of sandboxing is the way Java restrict applets from having total access to the machine. Lua is frequently used in games programming. The famous example is World of Warcraft. One of the main reasons is that it can be sandboxed. Deciding the capabilities to allow the untrusted code is not simple, but at least it can be secured much easier than Python. A: Any programming language that allows to run an external script should be able to do your job. That practically means all languages. Almost all dynamic languages will do. With python, there are multitude of ways to connect to a server and fetch the url. For execution, you could use subprocess module https://stackoverflow.com/questions/tagged/urllib2 https://stackoverflow.com/questions/tagged/subprocess
Add a python script at runtime
I am beginning python and working on a project, and one thing I would like to be able to do is download and run a script dynamically at runtime. The general idea is to be able to connect to a server, download a python script on demand, and run that script that was just downloaded without having to restart the program or hard code that specific script in to the program. The program I'm working with uses Python for scripting and execution, and C++ for the other code such as rendering and math. I would like to be able to use python to run scripts that have been downloaded from a server (for things such as user generated content). I was wondering if that was possible, or if I should use another scripting language (possibly LUA) for that situation? Thanks, Th3flyboy
[ "You can definitely do this. Use urllib to download or generate the script, then import it. It'll work like a charm every time, as long as you download the script to your PYTHONPATH.\nFor example:\nfrom urllib import urlretrieve\nurlretrieve('http://www.mysite.com/myscript.py', '/home/me/script.py')\nimport script\...
[ 1, 1, 0 ]
[]
[]
[ "dynamic", "python", "runtime" ]
stackoverflow_0004037913_dynamic_python_runtime.txt
Q: Using multiple memcache servers in a pool I'm going through the documentation and I'm a little confused as to how memcache does internal load-balancing if multiple servers are specified. For example: import memcache mc.set_servers(['127.0.0.1:11211','127.0.0.1:11212',]) mc.set("some_key", "Some value") print mc.get("some_key") Will the setting and retrieval of key "some_key" always hit the same server? Will the setting and retrieval of alternate keys, such as "some_key_2" or "some_key_3," automatically be distributed amongst the pool of servers? What happens if a server is added or deleted? Similarly, what happens with get_multi: import memcache mc.set_servers(['127.0.0.1:11211','127.0.0.1:11212',]) mc.set_multi({42: 'adams', 46 : 'and of me'}) print mc.get_multi([46, 42]) Will this automatically set and retrieve each key from the right server? Is it necessary to write a wrapper class? Thanks. A: memcached places keys on servers based on a hash of the key. As long as your server setup doesn't change, then a given key will always land on a given server.
Using multiple memcache servers in a pool
I'm going through the documentation and I'm a little confused as to how memcache does internal load-balancing if multiple servers are specified. For example: import memcache mc.set_servers(['127.0.0.1:11211','127.0.0.1:11212',]) mc.set("some_key", "Some value") print mc.get("some_key") Will the setting and retrieval of key "some_key" always hit the same server? Will the setting and retrieval of alternate keys, such as "some_key_2" or "some_key_3," automatically be distributed amongst the pool of servers? What happens if a server is added or deleted? Similarly, what happens with get_multi: import memcache mc.set_servers(['127.0.0.1:11211','127.0.0.1:11212',]) mc.set_multi({42: 'adams', 46 : 'and of me'}) print mc.get_multi([46, 42]) Will this automatically set and retrieve each key from the right server? Is it necessary to write a wrapper class? Thanks.
[ "memcached places keys on servers based on a hash of the key. As long as your server setup doesn't change, then a given key will always land on a given server. \n" ]
[ 12 ]
[]
[]
[ "memcached", "python" ]
stackoverflow_0004038094_memcached_python.txt
Q: How to store a return value in a variable and use print to display the value returned Modify the main function to call getAction right after the win.getMouse() call inside of the while loop. Store the return value in a variable named action, and use print to display the value returned. This is my code so far. What I'm having trouble with is how to return the value in a variable named action, and then use print to display the value returned. ACTION_PET = 1 ACTION_FEED = 2 ACTION_PLAY = 3 ACTION_IGNORE = 4 ACTION_ERROR = 5 def getAction(): win = GraphWin("CS1400 - Pet Dog", 610, 500) clear_screen(win) rec1, rec2, rec3, rec4= draw_buttons(win) while True: mouseClick = win.getMouse() if inBox(rec1, mouseClick): ACTION_PET(win) elif inBox(rec2, mouseClick): ACTION_FEED(win) elif inBox(rec3, mouseClick): ACTION_PLAY(win) elif inBox(rec4, mouseClick): ACTION_IGNORE(win) else: ACTION_ERROR(win) break # main program def main(): """dog drawing program""" win = GraphWin("CS1400 - Pet Dog", 610, 500) # create graphics window clear_screen(win) # start with a clear screen rec1, rec2, rec3, rec4= draw_buttons(win) # create user buttons # loop forever until cat is dead while True: mouseClick = win.getMouse() # get mouse click if inBox(rec1, mouseClick): drawHappy(win) # draw happy dog elif inBox(rec2, mouseClick): drawAngry(win) # draw angry dog elif inBox(rec3, mouseClick): drawSleeping(win) # draw sleeping dog elif inBox(rec4, mouseClick): drawBored(win) # draw bored dog break # wait for user to click one more time before ending the program msg_location = Point(305, 430) msg = Text(msg_location, "Click anywhere to quit.") msg.setTextColor("red") msg.draw(win) # draw message win.close() return A: You have lots of things (apparently) wrong with your code. ACTION_PET(win) will give you a TypeError: 'int' object is not callable return the value in a variable named action What value? if inBox(rec1, mouseClick): Where is inBox() defined? if inBox(rec1, mouseClick): drawHappy(win) # draw happy dog elif inBox(rec2, mouseClick): drawAngry(win) # draw angry dog elif inBox(rec3, mouseClick): drawSleeping(win) # draw sleeping dog elif inBox(rec4, mouseClick): drawBored(win) None of those are defined either.
How to store a return value in a variable and use print to display the value returned
Modify the main function to call getAction right after the win.getMouse() call inside of the while loop. Store the return value in a variable named action, and use print to display the value returned. This is my code so far. What I'm having trouble with is how to return the value in a variable named action, and then use print to display the value returned. ACTION_PET = 1 ACTION_FEED = 2 ACTION_PLAY = 3 ACTION_IGNORE = 4 ACTION_ERROR = 5 def getAction(): win = GraphWin("CS1400 - Pet Dog", 610, 500) clear_screen(win) rec1, rec2, rec3, rec4= draw_buttons(win) while True: mouseClick = win.getMouse() if inBox(rec1, mouseClick): ACTION_PET(win) elif inBox(rec2, mouseClick): ACTION_FEED(win) elif inBox(rec3, mouseClick): ACTION_PLAY(win) elif inBox(rec4, mouseClick): ACTION_IGNORE(win) else: ACTION_ERROR(win) break # main program def main(): """dog drawing program""" win = GraphWin("CS1400 - Pet Dog", 610, 500) # create graphics window clear_screen(win) # start with a clear screen rec1, rec2, rec3, rec4= draw_buttons(win) # create user buttons # loop forever until cat is dead while True: mouseClick = win.getMouse() # get mouse click if inBox(rec1, mouseClick): drawHappy(win) # draw happy dog elif inBox(rec2, mouseClick): drawAngry(win) # draw angry dog elif inBox(rec3, mouseClick): drawSleeping(win) # draw sleeping dog elif inBox(rec4, mouseClick): drawBored(win) # draw bored dog break # wait for user to click one more time before ending the program msg_location = Point(305, 430) msg = Text(msg_location, "Click anywhere to quit.") msg.setTextColor("red") msg.draw(win) # draw message win.close() return
[ "You have lots of things (apparently) wrong with your code.\nACTION_PET(win) will give you a TypeError: 'int' object is not callable\nreturn the value in a variable named action What value?\nif inBox(rec1, mouseClick): Where is inBox() defined?\n\nif inBox(rec1, mouseClick):\n drawHappy(win) ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004038018_python.txt
Q: Using the ALT key with PyGame I'm looking to detect the Alt key in PyGame, but every time I press it, it will bring up the menu that you normally get if you click the icon at the upper left of the window (Restore, Maximize, etc). How do I get PyGame to recognise the keypress, rather than the window? many thanks A: The only solution i could think of is pygame.event.set_grab(True) to grab all input. http://www.pygame.org/docs/ref/event.html (Check the comments for the keycodes) I don’t know if this blocks alt+tab and/or multimedia buttons, too, so you should preoceed with caution.
Using the ALT key with PyGame
I'm looking to detect the Alt key in PyGame, but every time I press it, it will bring up the menu that you normally get if you click the icon at the upper left of the window (Restore, Maximize, etc). How do I get PyGame to recognise the keypress, rather than the window? many thanks
[ "The only solution i could think of is pygame.event.set_grab(True) to grab all input.\nhttp://www.pygame.org/docs/ref/event.html (Check the comments for the keycodes)\nI don’t know if this blocks alt+tab and/or multimedia buttons, too, so you should preoceed with caution.\n" ]
[ 0 ]
[]
[]
[ "pygame", "python", "windows" ]
stackoverflow_0004031941_pygame_python_windows.txt
Q: wxPython CheckListBox with HTML I'm using wxPython to create a GUI app. Right now I'm using a wx.CheckListBox to display options with check boxes, but I'd like the text in the CheckListBox to be formatted using HTML. What's the best way to go about this? A: Replace wxCheckListBox with wxHtmlWindow and use wxpTag for the check boxes. Here is some code to get you started. import wx import wx.lib.wxpTag class HtmlCheckListBox(wx.html.HtmlWindow): def __init__(self, parent, choices=None): wx.html.HtmlWindow.__init__(self, parent) check_box = """ <wxp module="wx" class="CheckBox"> <param name="id" value="%d"> </wxp> """ self._ids = dict() if choices: items = list() for c, choice in enumerate(choices): i = wx.NewId() self._ids[i] = c items.append((check_box % i) + choice) self.SetPage("<hr>".join(items)) self.Bind(wx.EVT_CHECKBOX, self.OnCheck) def OnCheck(self, event): print "item:", self._ids[event.Id], "checked:", event.Checked() class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.options = HtmlCheckListBox( self, [ "<i>one</i>", "<b>two</b>", "<u>three</u>" ] ) app = wx.PySimpleApp() app.TopWindow = TestFrame() app.TopWindow.Show() app.MainLoop()
wxPython CheckListBox with HTML
I'm using wxPython to create a GUI app. Right now I'm using a wx.CheckListBox to display options with check boxes, but I'd like the text in the CheckListBox to be formatted using HTML. What's the best way to go about this?
[ "Replace wxCheckListBox with wxHtmlWindow and use wxpTag for the check boxes.\nHere is some code to get you started.\nimport wx\nimport wx.lib.wxpTag\n\n\nclass HtmlCheckListBox(wx.html.HtmlWindow):\n def __init__(self, parent, choices=None):\n wx.html.HtmlWindow.__init__(self, parent)\n\n check_bo...
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004037076_python_wxpython.txt
Q: Python - How to use underlying object's constructor as class method? Please forgive the bad title - I had a hard time trying to think of a concise way to explain this. I have a Python class that will have some underlying objects of other classes. I want to be able to create these underlying objects via a method of the original object. Let me try to explain better with an example: class Foo: def __init__(self): self.bars = [] def Bar(self, a, b, c): self.bars.append(Bar(a, b, c)) class Bar: def __init__(self, a, b, c): self.a = a self.b = b self.c = c I would use the above as such: f = Foo() f.Bar(1, 2, 3) So this works how I want but is kind of crappy with respect to maintenance. Is there a nice "Pythonic" way to do this that would make maintaining this easy? For instance, let's say I changed the constructor of Bar to: __init__(self, a, b, c, d): would there be a way to define all of this so I don't have to update the argument list in 3 places? A: Sure, no problem: Just pass *args and **kwargs on to Bar: class Foo: def __init__(self): self.bars = [] def append_bar(self, *args, **kwargs): self.bars.append(Bar(*args, **kwargs)) class Bar: def __init__(self, a, b, c, d): self.a = a self.b = b self.c = c self.d = d f=Foo() f.append_bar(1,2,3,4) PS. I changed the name of the method to append_bar because the usual convention in Python is to use lowercase names for methods, and I think methods whose names are verbs help describe what the method does.
Python - How to use underlying object's constructor as class method?
Please forgive the bad title - I had a hard time trying to think of a concise way to explain this. I have a Python class that will have some underlying objects of other classes. I want to be able to create these underlying objects via a method of the original object. Let me try to explain better with an example: class Foo: def __init__(self): self.bars = [] def Bar(self, a, b, c): self.bars.append(Bar(a, b, c)) class Bar: def __init__(self, a, b, c): self.a = a self.b = b self.c = c I would use the above as such: f = Foo() f.Bar(1, 2, 3) So this works how I want but is kind of crappy with respect to maintenance. Is there a nice "Pythonic" way to do this that would make maintaining this easy? For instance, let's say I changed the constructor of Bar to: __init__(self, a, b, c, d): would there be a way to define all of this so I don't have to update the argument list in 3 places?
[ "Sure, no problem: Just pass *args and **kwargs on to Bar:\nclass Foo:\n def __init__(self):\n self.bars = []\n\n def append_bar(self, *args, **kwargs):\n self.bars.append(Bar(*args, **kwargs))\n\nclass Bar:\n def __init__(self, a, b, c, d):\n self.a = a\n self.b = b\n se...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0004038258_python.txt
Q: Add new keys to a dictionary while incrementing existing values I am processing a CSV file and counting the unique values of column 4. So far I have coded this three ways. One uses "if key in dictionary", the second traps the KeyError and the third uses "DefaultDictionary". For example (where x[3] is the value from the file and "a" is a dictionary): First way: if x[3] in a: a[x[3]] += 1 else: a[x[3]] = 1 Second way: try: b[x[3]] += 1 except KeyError: b[x[3]] = 1 Third way: from collections import defaultdict c = defaultdict(int) c[x[3]] += 1 My question is: which way is more efficient... cleaner... better... etc. Or is there a better way. Both ways work and give the same answer, but I thought I would tap the hive mind as a learning case. Thanks - A: Use collections.Counter. Counter is syntactic sugar for defaultdict(int), but what's cool about it is that it accepts an iterable in the constructor, thus saving an extra step (I assume all of your examples above are wrapped in a for-loop.) from collections import Counter count = Counter(x[3] for x in my_csv_reader) Prior to the introduction of collections.Counter, collections.defaultdict was the most idiomatic for this task, so for users < 2.7, use defaultdict. from collections import defaultdict count = defaultdict(int) for x in my_csv_reader: count[x[3]] += 1 A: You asked which was more efficient. Assuming that you are talking about execution speed: If your data is small, it doesn't matter. If it is large and typical, the "already exists" case will happen much more often than the "not in dict" case. This observation explains some of the results. Below is some code which can be used with the timeit module to explore speed without file-reading overhead. I have taken the liberty of adding a 5th method, which is not uncompetetive and will run on any Python from at least 1.5.2 [tested] onwards. from collections import defaultdict, Counter def tally0(iterable): # DOESN'T WORK -- common base case for timing d = {} for item in iterable: d[item] = 1 return d def tally1(iterable): d = {} for item in iterable: if item in d: d[item] += 1 else: d[item] = 1 return d def tally2(iterable): d = {} for item in iterable: try: d[item] += 1 except KeyError: d[item] = 1 return d def tally3(iterable): d = defaultdict(int) for item in iterable: d[item] += 1 def tally4(iterable): d = Counter() for item in iterable: d[item] += 1 def tally5(iterable): d = {} dg = d.get for item in iterable: d[item] = dg(item, 0) + 1 return d Typical run (in Windows XP "Command Prompt" window): prompt>\python27\python -mtimeit -s"t=1000*'now is the winter of our discontent made glorious summer by this son of york';import tally_bench as tb" "tb.tally1(t)" 10 loops, best of 3: 29.5 msec per loop Here are the results (msec per loop): 0 base case 13.6 1 if k in d 29.5 2 try/except 26.1 3 defaultdict 23.4 4 Counter 79.4 5 d.get(k, 0) 29.2 Another timing trial: prompt>\python27\python -mtimeit -s"from collections import defaultdict;d=defaultdict(int)" "d[1]+=1" 1000000 loops, best of 3: 0.309 usec per loop prompt>\python27\python -mtimeit -s"from collections import Counter;d=Counter()" "d[1]+=1" 1000000 loops, best of 3: 1.02 usec per loop The speed of Counter is possibly due to it being implemented partly in Python code whereas defaultdict is entirely in C (in 2.7, at least). Note that Counter() is NOT just "syntactic sugar" for defaultdict(int) -- it implements a full bag aka multiset object -- see the docs for details; they may save you from reinventing the wheel if you need some fancy post-processing. If all you want to do is count things, use defaultdict. Update in response to a question from @Steven Rumbalski: """ I'm curious, what happens if you move the iterable into the Counter constructor: d = Counter(iterable)? (I have python 2.6 and cannot test it.) """ tally6: just does d = Count(iterable); return d, takes 60.0 msecs You could look at the source (collections.py in the SVN repository) ... here's what my Python27\Lib\collections.py does when iterable is not a Mapping instance: self_get = self.get for elem in iterable: self[elem] = self_get(elem, 0) + 1 Seen that code anywhere before? There's a whole lot of carry-on just to call code that's runnable in Python 1.5.2 :-O A: from collections import Counter Counter(a) A: Since you don't have access to Counter, your best bet is your third approach. It's much cleaner and easier to read. In addition, it doesn't have the perpetual testing (and branching) that the first two approaches have, which makes it more efficient. A: Use setdefault. a[x[3]] = a.setdefault(x[3], 0) + 1 setdefault gets the value of the specified key (x[3] in this case), or if it does not exist, the specified value (0 in this case).
Add new keys to a dictionary while incrementing existing values
I am processing a CSV file and counting the unique values of column 4. So far I have coded this three ways. One uses "if key in dictionary", the second traps the KeyError and the third uses "DefaultDictionary". For example (where x[3] is the value from the file and "a" is a dictionary): First way: if x[3] in a: a[x[3]] += 1 else: a[x[3]] = 1 Second way: try: b[x[3]] += 1 except KeyError: b[x[3]] = 1 Third way: from collections import defaultdict c = defaultdict(int) c[x[3]] += 1 My question is: which way is more efficient... cleaner... better... etc. Or is there a better way. Both ways work and give the same answer, but I thought I would tap the hive mind as a learning case. Thanks -
[ "Use collections.Counter. Counter is syntactic sugar for defaultdict(int), but what's cool about it is that it accepts an iterable in the constructor, thus saving an extra step (I assume all of your examples above are wrapped in a for-loop.)\nfrom collections import Counter\ncount = Counter(x[3] for x in my_csv_rea...
[ 6, 6, 1, 0, 0 ]
[]
[]
[ "dictionary", "python", "unique_key" ]
stackoverflow_0004036474_dictionary_python_unique_key.txt
Q: How to iterate over two lists? I am trying to do something in pyGTk where I build a list of HBoxes: self.keyvalueboxes = [] for keyval in range(1,self.keyvaluelen): self.keyvalueboxes.append(gtk.HBox(False, 5)) But I then want to run over the list and assign A text entry & a label into each one both of which are stored in a list. A: If your list are of equal length use zip >>> x = ['a', 'b', 'c', 'd'] >>> y = [1, 2, 3, 4] >>> z = zip(x,y) >>> z [('a', 1), ('b', 2), ('c', 3), ('d', 4)] >>> for l in z: print l[0], l[1] ... a 1 b 2 c 3 d 4 >>> A: Check out http://docs.python.org/library/functions.html#zip. It lets you iterate over two lists at the same time.
How to iterate over two lists?
I am trying to do something in pyGTk where I build a list of HBoxes: self.keyvalueboxes = [] for keyval in range(1,self.keyvaluelen): self.keyvalueboxes.append(gtk.HBox(False, 5)) But I then want to run over the list and assign A text entry & a label into each one both of which are stored in a list.
[ "If your list are of equal length use zip\n>>> x = ['a', 'b', 'c', 'd']\n>>> y = [1, 2, 3, 4]\n>>> z = zip(x,y)\n>>> z\n[('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n>>> for l in z: print l[0], l[1]\n... \na 1\nb 2\nc 3\nd 4\n>>> \n\n", "Check out http://docs.python.org/library/functions.html#zip. It lets you iterate...
[ 4, 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0004038481_gtk_pygtk_python.txt
Q: Search range of int values using djapian I'm using djapian as my search backend, and I'm looking to search for a range of values. For example: query = 'comments:(0..10)' Post.indexer.search(query) would search for Posts with between 0 and 10 comments. I cannot find a way to do this in djapian, though I have found this issue, and patch to implement some kind of date range searching. I also found this page from the xapian official docs describing some kind of range query. However, I lack the knowledge to either formulate my own raw xapian query, and/or feed a raw xapian query into djapian. So help me SO, how can I query a djapian index for a range of int values. Thanks, Laurie A: Ok, I worked it out. I'll leave the answer here for posterity. The first thing to do is to attach a NumberValueRangeProcessor to the QueryParser. You can do this by extending the djapian Indexer._get_query_parser. Note the leading underscore. Below is a code snippet showing how I did it. from djapian import Indexer from xapian import NumberValueRangeProcessor class RangeIndexer(Indexer) def _get_query_parser(self, *args, **kwargs): query_parser = Indexer._get_query_parser(self, *args, **kwargs) valno = self.free_values_start_number + 0 nvrp = NumberValueRangeProcessor(valno, 'value_range:', True) query_parser.add_valuerangeprocessor(nvrp) return query_parser Lines to note: valno = self.free_values_start_number + 0 The self.free_values_start_number is an int, and used as the value no, it is the index of the first column where fields start being defined. I added 0 to this, to indicate that you should add the index of the field you want the range search to be for. nvrp = NumberValueRangeProcessor(valno, 'value_range:', True) We send valno to tell the processor what field to deal with. The 'value_range:' indicates the prefix for the processor, so we can search by saying 'value_range:(0..100)'. The True simply indicates that the 'value_range:' should be treated as a prefix not a suffix. query_parser.add_valuerangeprocessor(nvrp) This simply adds the NumberValueRangeProcessor to the QueryParser. Hope that helps anyone who has any problems with this matter. Note that you will need to add a new NumberValueRangeProcessor for each field you want to be able to range search.
Search range of int values using djapian
I'm using djapian as my search backend, and I'm looking to search for a range of values. For example: query = 'comments:(0..10)' Post.indexer.search(query) would search for Posts with between 0 and 10 comments. I cannot find a way to do this in djapian, though I have found this issue, and patch to implement some kind of date range searching. I also found this page from the xapian official docs describing some kind of range query. However, I lack the knowledge to either formulate my own raw xapian query, and/or feed a raw xapian query into djapian. So help me SO, how can I query a djapian index for a range of int values. Thanks, Laurie
[ "Ok, I worked it out. I'll leave the answer here for posterity.\nThe first thing to do is to attach a NumberValueRangeProcessor to the QueryParser. You can do this by extending the djapian Indexer._get_query_parser. Note the leading underscore. Below is a code snippet showing how I did it.\nfrom djapian import Inde...
[ 0 ]
[]
[]
[ "django", "python", "search", "xapian" ]
stackoverflow_0004006502_django_python_search_xapian.txt
Q: What's wrong with float("1,000")? Very rusty with my Python. I have a list of Cost as strings. I'm trying to convert them to floats but when the cost is above $1000, the value is represented with a comma. float("1,000") returns an error: Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> decimal("1,000") TypeError: 'module' object is not callable I know it's probably trivial but do you have a solution? A: decimal is not float. decimal is a module. That is the reason for the error you get. As for the commas, drop them first: s = "1,000" float(s.replace(",", "")) # = 1000.0 A: Use re to remove any "," formatting before you convert to float. >>> import re >>> re.sub(",", "", "1000,00,00") '10000000' >>> A: The error that raise is because you are trying to call the module like this: >>> import decimal >>> decimal("") TypeError: 'module' object is not callable you should rather do: >>> import locale >>> import decimal >>> locale.setlocale(locale.LC_ALL, '') >>> decimal.Decimal(locale.atoi("1,000")) Decimal('1000') so you can just do it like this
What's wrong with float("1,000")?
Very rusty with my Python. I have a list of Cost as strings. I'm trying to convert them to floats but when the cost is above $1000, the value is represented with a comma. float("1,000") returns an error: Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> decimal("1,000") TypeError: 'module' object is not callable I know it's probably trivial but do you have a solution?
[ "decimal is not float. decimal is a module. That is the reason for the error you get.\nAs for the commas, drop them first:\ns = \"1,000\"\nfloat(s.replace(\",\", \"\")) # = 1000.0\n\n", "Use re to remove any \",\" formatting before you convert to float.\n>>> import re\n>>> re.sub(\",\", \"\", \"1000,00,00\")\n'10...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004038719_python.txt
Q: html 1.13 package installation I downloaded html 1.13 package from Python site and as per instructions I doubleclicked on install.bat and installed it. I also added the directory C:\Python26\HTML.py-0.04 to PYTHONPATH. But when I try to import the module with >>> from html import HTML I still get ImportError: No module named html Can someone help me understand what I am doing wrong? Thanks. A: Usual installation issues. Issue you don't need to add it to PYTHONPATH if it is installed into standard directory site-packages and it would already be in the path. check out there should be a html.. folder in default search path : lib\site-packages C:\Python26\lib\site-packages\ If you find the folder then your import should work automatically. If you do not find it, that means it did not install properly. To see your issues, run install.bat from command line and check out the errors. About PYTHONPATH It augments the default search path for module files. This is usually when, you do not want to install and simply point to custom directory so that python can import modules from there. Read http://docs.python.org/install/ http://docs.python.org/tutorial/modules.html
html 1.13 package installation
I downloaded html 1.13 package from Python site and as per instructions I doubleclicked on install.bat and installed it. I also added the directory C:\Python26\HTML.py-0.04 to PYTHONPATH. But when I try to import the module with >>> from html import HTML I still get ImportError: No module named html Can someone help me understand what I am doing wrong? Thanks.
[ "Usual installation issues.\n\nIssue\n\nyou don't need to add it to PYTHONPATH if it is installed into standard directory site-packages and it would already be in the path.\ncheck out there should be a html.. folder in default search path : lib\\site-packages\nC:\\Python26\\lib\\site-packages\\\nIf you find the fol...
[ 1 ]
[]
[]
[ "html", "python", "python_module", "pythonpath" ]
stackoverflow_0004038772_html_python_python_module_pythonpath.txt
Q: How do I parse timezones from dates in python Here's what I have tried so far. I'm just not too sure as to why it outputs as PST instead of GMT. I'm not sure if that's not the correct way to parse it, or to output it. Something seems to be wrong somewhere. >>> x = time.strptime('Wed, 27 Oct 2010 22:17:00 GMT', '%a, %d %b %Y %H:%M:%S %Z') >>> time.strftime('%a, %d %b %Y %H:%M:%S %Z', x) 'Wed, 27 Oct 2010 22:17:00 PST' Appreciate any help, A: First of all i recommend that you use dateutil >>> import dateutil.parser >>> x = dateutil.parser.parse('Wed, 27 Oct 2010 22:17:00 GMT') datetime.datetime(2010, 10, 27, 22, 17, tzinfo=tzutc()) >>> str(x) '2010-10-27 22:17:00+00:00' >>> x.strftime('%a, %d %b %Y %H:%M:%S %Z') 'Wed, 27 Oct 2010 22:17:00 UTC' A: See the docs on strftime behavior: %Z If tzname() returns None, %Z is replaced by an empty string. Otherwise %Z is replaced by the returned value, which must be a string. The dateutil may be used for parsing timezones. Also see the pytz library if you're going to be working with timezones, though it may not be necessary for what you're doing.
How do I parse timezones from dates in python
Here's what I have tried so far. I'm just not too sure as to why it outputs as PST instead of GMT. I'm not sure if that's not the correct way to parse it, or to output it. Something seems to be wrong somewhere. >>> x = time.strptime('Wed, 27 Oct 2010 22:17:00 GMT', '%a, %d %b %Y %H:%M:%S %Z') >>> time.strftime('%a, %d %b %Y %H:%M:%S %Z', x) 'Wed, 27 Oct 2010 22:17:00 PST' Appreciate any help,
[ "First of all i recommend that you use dateutil\n>>> import dateutil.parser\n\n>>> x = dateutil.parser.parse('Wed, 27 Oct 2010 22:17:00 GMT')\ndatetime.datetime(2010, 10, 27, 22, 17, tzinfo=tzutc())\n>>> str(x)\n'2010-10-27 22:17:00+00:00'\n>>> x.strftime('%a, %d %b %Y %H:%M:%S %Z')\n'Wed, 27 Oct 2010 22:17:00 UTC'...
[ 2, 1 ]
[]
[]
[ "date", "python", "timezone" ]
stackoverflow_0004038797_date_python_timezone.txt
Q: MySQL syntax error using python to add column to a table The code i have is: for key in keys: cursor.execute(""" ALTER TABLE segment_table ADD %s VARCHAR(40) """, key) I get a error telling me my syntax is wrong. When I replace the %s with a actual string the syntax error goes away. for key in keys: cursor.execute(""" ALTER TABLE segment_table ADD myColumn VARCHAR(40) """) Any help is appreciated. A: There is a bit of confusion going here, for several reasons: (1) mySQL uses the % as a parameter marker -- easily confused with the % in Python's string % (data1, data2, etc) (2) some people seem not to be aware that parameter markers can be used only where an expression can be used in SQL syntax -- this excludes table names, column names, function names, keywords, etc (3) code-golf onelinerism Required SQL: ALTER TABLE segment_table ADD myColumn VARCHAR(40) Using a parameter doesn't work: key = "myColumn" sql = "ALTER TABLE segment_table ADD %s VARCHAR(40)" # col name not OK as parm cursor.execute(sql, (key, )) You need to build an acceptable SQL statement, using e.g. Python string formatting: key = "myColumn" sql = "ALTER TABLE segment_table ADD %s VARCHAR(40)" % key cursor.execute(sql) A: Shouldn't you do the replacement before feeding it? query = "ALTER TABLE segment_table ADD %s VARCHAR(40)" % (key) cursor.execute( query ) A: when cursor.execute() replace %s in a query string it adds ' ' to the argument values supplied...so when you do key = 'abc' cursor.execute(""" ALTER TABLE segment_table ADD %s VARCHAR(40) """, key) the query executed is ALTER TABLE segment_table ADD 'abc' VARCHAR(40) to which mysql will throw a syntax error coz the column names, table names can be in `` but not ' ' so this will work query = "ALTER TABLE segment_table ADD %s VARCHAR(40)" % (key)
MySQL syntax error using python to add column to a table
The code i have is: for key in keys: cursor.execute(""" ALTER TABLE segment_table ADD %s VARCHAR(40) """, key) I get a error telling me my syntax is wrong. When I replace the %s with a actual string the syntax error goes away. for key in keys: cursor.execute(""" ALTER TABLE segment_table ADD myColumn VARCHAR(40) """) Any help is appreciated.
[ "There is a bit of confusion going here, for several reasons:\n(1) mySQL uses the % as a parameter marker -- easily confused with the % in Python's string % (data1, data2, etc)\n(2) some people seem not to be aware that parameter markers can be used only where an expression can be used in SQL syntax -- this exclude...
[ 5, 3, 2 ]
[]
[]
[ "mysql", "python", "syntax_error" ]
stackoverflow_0004036067_mysql_python_syntax_error.txt
Q: How does logging handler become a str? I have a logger that functions properly at the start of a script, then breaks in the middle. It looks like its handler is getting overwritten by a str, but I can't figure out where. At the start of the script, I'm printing the handler and its level. The following code: print 'Array of handlers', logger.handlers for h in logger.handlers: print 'Handler', h print 'Handler level', h.level produces this: Array of handlers [<logging.FileHandler instance at 0x19ef320>] Handler <logging.FileHandler instance at 0x19ef320> Handler level 0 Now in the middle of execution, you'll see that the logger's handler (hdlr) is interpreted as a str. Started from <class 'mymodule.ext.freebase.HTTPMetawebSession'>. Traceback (most recent call last): File "hadoop/get_web_data.py", line 144, in <module> main() File "hadoop/get_web_data.py", line 121, in main for count, performer in enumerate(results): File "/home/wraith/dev/modules/mymodule/ext/freebase.py", line 126, in mqlreaditer r = self._httpreq_json(service, 'POST', form=dict(query=qstr)) File "/home/wraith/dev/modules/mymodule/contrib/freebase/api/session.py", line 369, in _httpreq_json resp, body = self._httpreq(*args, **kws) File "/home/wraith/dev/modules/mymodule/contrib/freebase/api/session.py", line 346, in _httpreq self.log.info('%s %s%s%s', method, url, formstr, headerstr) File "/usr/lib/python2.5/logging/__init__.py", line 985, in info apply(self._log, (INFO, msg, args), kwargs) File "/usr/lib/python2.5/logging/__init__.py", line 1101, in _log self.handle(record) File "/usr/lib/python2.5/logging/__init__.py", line 1111, in handle self.callHandlers(record) File "/usr/lib/python2.5/logging/__init__.py", line 1147, in callHandlers if record.levelno >= hdlr.level: AttributeError: 'str' object has no attribute 'level' In the last 2 lines, hdlr.level blows up because hdlr is not a str. if record.levelno >= hdlr.level: AttributeError: 'str' object has no attribute 'level' After setting the handler at the beginning, which is fine, I do not add another handler or alter the existing in any way. The only command I call on logger is logger.info('event to log'). What would alter the logger's handler in this way? A: The contents of the string might give you a clue as to how and why it is going wrong. I suggest putting print(repr(self.log.handlers)) right before your call to info: self.log.info('%s %s%s%s', method, url, formstr, headerstr)
How does logging handler become a str?
I have a logger that functions properly at the start of a script, then breaks in the middle. It looks like its handler is getting overwritten by a str, but I can't figure out where. At the start of the script, I'm printing the handler and its level. The following code: print 'Array of handlers', logger.handlers for h in logger.handlers: print 'Handler', h print 'Handler level', h.level produces this: Array of handlers [<logging.FileHandler instance at 0x19ef320>] Handler <logging.FileHandler instance at 0x19ef320> Handler level 0 Now in the middle of execution, you'll see that the logger's handler (hdlr) is interpreted as a str. Started from <class 'mymodule.ext.freebase.HTTPMetawebSession'>. Traceback (most recent call last): File "hadoop/get_web_data.py", line 144, in <module> main() File "hadoop/get_web_data.py", line 121, in main for count, performer in enumerate(results): File "/home/wraith/dev/modules/mymodule/ext/freebase.py", line 126, in mqlreaditer r = self._httpreq_json(service, 'POST', form=dict(query=qstr)) File "/home/wraith/dev/modules/mymodule/contrib/freebase/api/session.py", line 369, in _httpreq_json resp, body = self._httpreq(*args, **kws) File "/home/wraith/dev/modules/mymodule/contrib/freebase/api/session.py", line 346, in _httpreq self.log.info('%s %s%s%s', method, url, formstr, headerstr) File "/usr/lib/python2.5/logging/__init__.py", line 985, in info apply(self._log, (INFO, msg, args), kwargs) File "/usr/lib/python2.5/logging/__init__.py", line 1101, in _log self.handle(record) File "/usr/lib/python2.5/logging/__init__.py", line 1111, in handle self.callHandlers(record) File "/usr/lib/python2.5/logging/__init__.py", line 1147, in callHandlers if record.levelno >= hdlr.level: AttributeError: 'str' object has no attribute 'level' In the last 2 lines, hdlr.level blows up because hdlr is not a str. if record.levelno >= hdlr.level: AttributeError: 'str' object has no attribute 'level' After setting the handler at the beginning, which is fine, I do not add another handler or alter the existing in any way. The only command I call on logger is logger.info('event to log'). What would alter the logger's handler in this way?
[ "The contents of the string might give you a clue as to how and why it is going wrong.\nI suggest putting\nprint(repr(self.log.handlers))\n\nright before your call to info:\nself.log.info('%s %s%s%s', method, url, formstr, headerstr)\n\n" ]
[ 0 ]
[]
[]
[ "freebase", "handler", "logging", "python" ]
stackoverflow_0004039021_freebase_handler_logging_python.txt
Q: How to compare parts of flat files? I have some simple data stored in series of text files. Once line per record, but number and type of fields can vary per record. The files contain almost the same data. The exists an "ideal" data file to which these must be compared. Some fields can vary, but some need to match. I also need to now if any records are missing / added compared to the master. What would be a good approach to take? Thank you A: I modified the following to simply iterate over every combination of lines from file1 and file2. I think the for, else construction works well here. def comparefiles(file1, file2): for row in file1: for row in file2: #check all of your lines, break if condition is met else: #no matches A: I completely agree with unutbu, you should use difflib for that. difflib.SequenceMatcher(None, file1.read(), file2.read())
How to compare parts of flat files?
I have some simple data stored in series of text files. Once line per record, but number and type of fields can vary per record. The files contain almost the same data. The exists an "ideal" data file to which these must be compared. Some fields can vary, but some need to match. I also need to now if any records are missing / added compared to the master. What would be a good approach to take? Thank you
[ "I modified the following to simply iterate over every combination of lines from file1 and file2.\nI think the for, else construction works well here.\ndef comparefiles(file1, file2):\n for row in file1:\n for row in file2:\n #check all of your lines, break if condition is met\n else:\n...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004039099_python.txt
Q: using `map` to construct multiple named tuples Suppose I have a namedtuple like >>> Point = namedtuple('Point','x y') Why is it that I construct a single object via >>> Point(3,4) yet when I want to apply Point via map, I have to call >>> map(Point._make,[(3,4),(5,6)]) I suspect this has something to do with classmethods, perhaps, and am hoping that in figuring this out I'll learn more about them as well. Thanks in advance. A: Point._make takes a tuple as its sole argument. Your map call is equivalent to [Point._make((3, 4)), Point._make((5, 6))]. Using a list comprehension makes this more obvious: [Point(*t) for t in [(3, 4), (5, 6)]] achieves the same effect.
using `map` to construct multiple named tuples
Suppose I have a namedtuple like >>> Point = namedtuple('Point','x y') Why is it that I construct a single object via >>> Point(3,4) yet when I want to apply Point via map, I have to call >>> map(Point._make,[(3,4),(5,6)]) I suspect this has something to do with classmethods, perhaps, and am hoping that in figuring this out I'll learn more about them as well. Thanks in advance.
[ "Point._make takes a tuple as its sole argument. Your map call is equivalent to [Point._make((3, 4)), Point._make((5, 6))].\nUsing a list comprehension makes this more obvious: [Point(*t) for t in [(3, 4), (5, 6)]] achieves the same effect.\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0004039245_python.txt
Q: Django: Include related models in JSON string? Building on this question, now I have another problem. Given this, shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \ .annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount')) \ .select_related('pickup_address','dropoff_address','billing_address') return HttpResponse(simplejson.dumps(list(shipments.values()), ensure_ascii=False, default=json_formatter), mimetype='application/json') It doesn't actually include the pickup_address, etc. in the JSON. How can I get it to include the related fields? A: You can use a list comprehension full of shipment dicts with the related objects filled in. This API gives the client an explicit name for each address. Positional notation makes it too easy to ship to the billing address. Josh Block's "How to Design a Good API and Why it Matters" is worth reading. shipments = [{ 'shipment':s, 'pickup_address': s.pickup_address, 'dropoff_address': s.dropoff_address, 'billing_address': s.billing_address, } for s in shipments] return HttpResponse(simplejson.dumps(shipments, ensure_ascii=False, default=json_formatter), mimetype='application/json')
Django: Include related models in JSON string?
Building on this question, now I have another problem. Given this, shipments = Shipment.objects.filter(filter).exclude(**exclude).order_by(order) \ .annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount')) \ .select_related('pickup_address','dropoff_address','billing_address') return HttpResponse(simplejson.dumps(list(shipments.values()), ensure_ascii=False, default=json_formatter), mimetype='application/json') It doesn't actually include the pickup_address, etc. in the JSON. How can I get it to include the related fields?
[ "You can use a list comprehension full of shipment dicts with the related objects filled in. This API gives the client an explicit name for each address. Positional notation makes it too easy to ship to the billing address. Josh Block's \"How to Design a Good API and Why it Matters\" is worth reading.\nshipments = ...
[ 1 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0004039019_django_json_python.txt
Q: Is it possible to write one-liners in Python? I was going through the code golf question here on Stack Overflow and saw many Perl one-liner solutions. Is something like that possible in Python? A: python -c 'print("Yes.")' A: It's possible to write one liners in Python but it's awkward (Python encourages well indented code which is somewhat at odds with the "one-liner" concept). It's a bit easier in Python 3 because print() is a function and not a statement. Here's one: python -c "fact = lambda x: x * fact(x-1) if x > 1 else 1; print(fact(5))" Here's how you could write a grep like function (this example prints lines from input containing "foo"): python -c "for s in __import__('fileinput').input(): __import__('sys').stdout.write(s) if 'foo' in s else None" A: I end up wanting to do this fairly often when doing stuff from the shell. It doesn't end up being more compact, and in many cases it's easier to just write a multi-line shell command than to write everything as a lambda. You pretty much can't use any Python statement that ends with a colon. So you end up having to write any for-like code as a genexp or list comprehension. I Do this anyway for most stuff, but it's annoying to have to import sys and push everything to sys.stdout.writelines in cases where you could otherwise just for tree in forest: print tree write lambdas instead of function definitions. This is often workable and has the useful side effect of forcing you to write very directed functions that really only do one thing. However, it's not particularly convenient, and doesn't work for anything that mutates a value (e.g., dict.update) and then returns some element. Do not bother doing things properly with context managers Do not do any exception handling. Use a dictionary of lambdas instead of any if/else sections. Use type(name, bases, dict) to declare any classes. This is pretty fun but only works if you happen to be declaring a class whose methods can all be expressed as lambdas. So for some things it works out but generally it's a big hassle, because you end up having to use a functional style that Python doesn't really support. Most of the time I just write multiline shell commands like python -c $' import some_module for v in some_module.whatever(): print "Whatever: \'{0}\'".format(v) ' The $' is a bash quoting syntax, an alternative to its '...' and "..." quoting constructs. It's useful, because it works like '...', but let’s you escape contained ' characters with \'. You can also embed newlines, so the above code could also be written as python -c $'import some_module\nfor v in some_module.whatever():\n print "Whatever: \'{0}\'".format(v)'. However, this is something of an acquired taste. One annoying thing about writing multiline commands in bash is that HOME and END go to the beginning of the command rather than the beginning of the line. There may be a better way to do this, but I usually just scan back and forth by holding down CTRL and the left/right arrow keys. Some Emacs user could probably set me straight here, since that's where bash's normal key bindings come from. If you want to insert a line break while editing a multiline command, you can do this with ^V-^J. That will put in a line break in such a way that you can still scan back to the previous lines, rather than using the $ first line of the command > second line > third line setup that you get otherwise, where you can't get back to the previous lines. The trick with ^V-^J works in IPython too, making it useful for editing class or function definitions. It may also work in the basic Python REPL (probably); I just don't know, because I nearly always use IPython. A: In Bourne shell you can use something called heredoc to get around Python's dependency on indents: python << 'EOF' > for i in range(3): > print i > EOF 0 1 2 A: A really nice Python one-liner (as in "quite useful"): python -c 'import SimpleHTTPServer as foo; foo.test()' 23433 It creates an instant basic web server in the current directory. (I was just introduced to this today, and it is very handy.) A: Here is my trick to run multiple statements: [stmt1, stmt2, expr1][2] if requires lazy evaluation: [lambda(): stmt1; lambda(): stmt2][not not boolExpr]() A: exec("if 6 * 9 == int('42', 13):\n\tprint('Yes!')") With this approach, every Python program can be written as a one-liner :)
Is it possible to write one-liners in Python?
I was going through the code golf question here on Stack Overflow and saw many Perl one-liner solutions. Is something like that possible in Python?
[ "python -c 'print(\"Yes.\")'\n", "It's possible to write one liners in Python but it's awkward (Python encourages well indented code which is somewhat at odds with the \"one-liner\" concept). It's a bit easier in Python 3 because print() is a function and not a statement. Here's one:\npython -c \"fact = lambda x:...
[ 23, 17, 10, 4, 2, 0, 0 ]
[ "Yes, actually it is very common. I use one-liners when I need to write quick code. It just depends on what you want to do. Here is a small line I just used this evening. It is the creation of a Tkinter button in a single line.\na = Button(root, text=\"Button\", command=com1).pack()\n\n" ]
[ -2 ]
[ "python" ]
stackoverflow_0004005952_python.txt
Q: Are boolean instance variables prepended with "is" in Python? Is it standard practice or convention in Python to prepend boolean instance variables with is? For example: "options.isVerbose" A: Mixed-case is less common than underscores: is_verbose, and actually, the is- prefix isn't all that common. I guess there isn't a strong convention one way or the other.
Are boolean instance variables prepended with "is" in Python?
Is it standard practice or convention in Python to prepend boolean instance variables with is? For example: "options.isVerbose"
[ "Mixed-case is less common than underscores: is_verbose, and actually, the is- prefix isn't all that common. I guess there isn't a strong convention one way or the other.\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0004039354_python.txt
Q: Django, Python: How do I know if users have closed their browser without click logout? Django, Python: How do I know if users have closed their browser without click logout? Really seriously question, because I need to analyse the user activities. A: HTTP is a stateless protocol: you can't know at the server if the user has simply closed their browser without informing you. A: it something to not do , but you can do something similar to Gmail (the way that they track if a user is still connected or not) you can do an AJAX request each 10 second or so (max time that will take a page to be loaded so that you don't mistake changing page to disconnection) , this Ajax request is like a "i'm still here" when it's received by the view it reset a timer ( this timer have been initialized for each user from the beginning ) to 0 otherwise if this timer exceed 10 s , you can say that the user "is gone without disconnecting". you can pull also another way using comet (reverse Ajax) lcheck Orbited. by the way disconnecting can me more than one thing : click on a disconnect link, remove session cookies , close page ... A: It's not pretty, but you could fire off ajax requests with the user's session info (or some cookie, or any way of identifying the user) every x seconds with javascript and if you haven't received anything from that user in 2*x seconds, then they're likely to have left the page/site.
Django, Python: How do I know if users have closed their browser without click logout?
Django, Python: How do I know if users have closed their browser without click logout? Really seriously question, because I need to analyse the user activities.
[ "HTTP is a stateless protocol: you can't know at the server if the user has simply closed their browser without informing you.\n", "it something to not do , but you can do something similar to Gmail (the way that they track if a user is still connected or not) you can do an AJAX request each 10 second or so (max ...
[ 4, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004039278_django_python.txt
Q: PHP front-end for installing Django A simple question: Is this possible? Is it worth the time looking into it? A: You should probably bundle Django with your project - or the parts of it that are needed. Users of your product will need to have python and the necessary libs installed. That is not something that you can do via PHP. Well, you could, but that would be like Webmin. When making a product for sale or for users to install, this is always something to think about before starting. In fact, at times, this very restriction is the most important deciding factor when choosing a technology and designing the system. Why is XYZ popular in the first place?
PHP front-end for installing Django
A simple question: Is this possible? Is it worth the time looking into it?
[ "You should probably bundle Django with your project - or the parts of it that are needed. Users of your product will need to have python and the necessary libs installed. That is not something that you can do via PHP. Well, you could, but that would be like Webmin. When making a product for sale or for users to in...
[ 1 ]
[]
[]
[ "django", "php", "python" ]
stackoverflow_0004033492_django_php_python.txt
Q: Live video stream on server (PC) from images sent by robot through UDP Hmm. I found this which seems promising: http://sourceforge.net/projects/mjpg-streamer/ Ok. I will try to explain what I am trying to do clearly and in much detail. I have a small humanoid robot with camera and wifi stick (this is the robot). The robot's wifi stick average wifi transfer rate is 1769KB/s. The robot has 500Mhz CPU and 256MB RAM so it is not enough for any serious computations (moreover there are already couple modules running on the robot for motion, vision, sonar, speech etc). I have a PC from which I control the robot. I am trying to have the robot walk around the room and see a live stream video of what the robot sees in the PC. What I already have working. The robot is walking as I want him to do and taking images with the camera. The images are being sent through UDP protocol to the PC where I am receiving them (I have verified this by saving the incoming images on the disk). The camera returns images which are 640 x 480 px in YUV442 colorspace. I am sending the images with lossy compression (JPEG) because I am trying to get the best possible FPS on the PC. I am doing the compression to JPEG on the robot with PIL library. My questions: Could somebody please give me some ideas about how to convert the incoming JPEG images to a live video stream? I understand that I will need some video encoder for that. Which video encoder do you recommend? FFMPEG or something else? I am very new to video streaming so I want to know what is best for this task. I'd prefer to use Python to write this so I would prefer some video encoder or library which has Python API. But I guess if the library has some good command line API it doesn't have to be in Python. What is the best FPS I could get out from this? Given the 1769KB/s average wifi transfer rate and the dimensions of the images? Should I use different compression than JPEG? I will be happy to see any code examples. Links to articles explaining how to do this would be fine, too. Some code samples. Here is how I am sending JPEG images from robot to the PC (shortened simplified snippet). This runs on the robot: # lots of code here UDPSock = socket(AF_INET,SOCK_DGRAM) while 1: image = camProxy.getImageLocal(nameId) size = (image[0], image[1]) data = image[6] im = Image.fromstring("YCbCr", size, data) s = StringIO.StringIO() im.save(s, "JPEG") UDPSock.sendto(s.getvalue(), addr) camProxy.releaseImage(nameId) UDPSock.close() # lots of code here Here is how I am receiving the images on the PC. This runs on the PC: # lots of code here UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) while 1: data, addr = UDPSock.recvfrom(buf) # here I need to create a stream from the data # which contains JPEG image UDPSock.close() # lots of code here A: Checking out your first question. Though the solution here uses a non-streaming set of pictures. It might help. The example uses pyMedia. http://pymedia.org/tut/src/make_video.py.html Some along the lines of what you want. http://code.google.com/p/mjpeg-stream-client/ If you have a need to edit a binary stream: http://bitbucket.org/haypo/hachoir/wiki/hachoir-parser A: Try pyffmpeg and test each available codec for the best performance. You probably need a very lightweight codec like Smoke or low profile H263 or x264, and you probably need to drop the resolution to 320x240. You have a trade off between latency of the video encoding and decoding and the bandwidth used, you might find dropping down to 160x120 with raw packets for a quick scene analysis and only periodically transmitting a full frame. You could also mix a raw, low latency, low resolution, high update feed with a high compressed, high latency, high resolution, low update feed.
Live video stream on server (PC) from images sent by robot through UDP
Hmm. I found this which seems promising: http://sourceforge.net/projects/mjpg-streamer/ Ok. I will try to explain what I am trying to do clearly and in much detail. I have a small humanoid robot with camera and wifi stick (this is the robot). The robot's wifi stick average wifi transfer rate is 1769KB/s. The robot has 500Mhz CPU and 256MB RAM so it is not enough for any serious computations (moreover there are already couple modules running on the robot for motion, vision, sonar, speech etc). I have a PC from which I control the robot. I am trying to have the robot walk around the room and see a live stream video of what the robot sees in the PC. What I already have working. The robot is walking as I want him to do and taking images with the camera. The images are being sent through UDP protocol to the PC where I am receiving them (I have verified this by saving the incoming images on the disk). The camera returns images which are 640 x 480 px in YUV442 colorspace. I am sending the images with lossy compression (JPEG) because I am trying to get the best possible FPS on the PC. I am doing the compression to JPEG on the robot with PIL library. My questions: Could somebody please give me some ideas about how to convert the incoming JPEG images to a live video stream? I understand that I will need some video encoder for that. Which video encoder do you recommend? FFMPEG or something else? I am very new to video streaming so I want to know what is best for this task. I'd prefer to use Python to write this so I would prefer some video encoder or library which has Python API. But I guess if the library has some good command line API it doesn't have to be in Python. What is the best FPS I could get out from this? Given the 1769KB/s average wifi transfer rate and the dimensions of the images? Should I use different compression than JPEG? I will be happy to see any code examples. Links to articles explaining how to do this would be fine, too. Some code samples. Here is how I am sending JPEG images from robot to the PC (shortened simplified snippet). This runs on the robot: # lots of code here UDPSock = socket(AF_INET,SOCK_DGRAM) while 1: image = camProxy.getImageLocal(nameId) size = (image[0], image[1]) data = image[6] im = Image.fromstring("YCbCr", size, data) s = StringIO.StringIO() im.save(s, "JPEG") UDPSock.sendto(s.getvalue(), addr) camProxy.releaseImage(nameId) UDPSock.close() # lots of code here Here is how I am receiving the images on the PC. This runs on the PC: # lots of code here UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) while 1: data, addr = UDPSock.recvfrom(buf) # here I need to create a stream from the data # which contains JPEG image UDPSock.close() # lots of code here
[ "Checking out your first question. Though the solution here uses a non-streaming set of pictures. It might help. The example uses pyMedia.\n\nhttp://pymedia.org/tut/src/make_video.py.html\n\nSome along the lines of what you want. \n\nhttp://code.google.com/p/mjpeg-stream-client/\n\nIf you have a need to edit a bina...
[ 1, 1 ]
[]
[]
[ "ffmpeg", "python", "udp", "video", "video_streaming" ]
stackoverflow_0004035365_ffmpeg_python_udp_video_video_streaming.txt
Q: Is it possible to open up certain web addresses using the default internet browser with python? I want python to open up a certain address using the computers default web browser. Is this possible? A: Absolutely, use the webbrowser module.
Is it possible to open up certain web addresses using the default internet browser with python?
I want python to open up a certain address using the computers default web browser. Is this possible?
[ "Absolutely, use the webbrowser module.\n" ]
[ 8 ]
[]
[]
[ "python", "webaddress" ]
stackoverflow_0004039924_python_webaddress.txt
Q: Convert CURL command line to Python script Having way too much trouble making this cmd line curl statement work in python script...help! Attempting to use URLLIB. curl -X POST "http://api.postmarkapp.com/email" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "X-Postmark-Server-Token: abcdef-1234-46cc-b2ab-38e3a208ab2b" \ -v \ -d "{From: 'sender@email.com', To: 'recipient@email.com', Subject: 'Postmark test', HtmlBody: 'Hello dear Postmark user.'}" A: Ok so you should probably user urllib2 to submit the actual request but here is the code: import urllib import urllib2 url = "http://api.postmarkapp.com/email" data = "{From: 'sender@email.com', To: 'recipient@email.com', Subject: 'Postmark test', HtmlBody: 'Hello dear Postmark user.'}" headers = { "Accept" : "application/json", "Conthent-Type": "application/json", "X-Postmark-Server-Token": "abcdef-1234-46cc-b2ab-38e3a208ab2b"} req = urllib2.Request(url, data, headers) response = urllib2.urlopen(req) the_page = response.read() Check out: urllib2 the unwritten manual I get a 401 unauthorized response so I guess it works :)
Convert CURL command line to Python script
Having way too much trouble making this cmd line curl statement work in python script...help! Attempting to use URLLIB. curl -X POST "http://api.postmarkapp.com/email" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "X-Postmark-Server-Token: abcdef-1234-46cc-b2ab-38e3a208ab2b" \ -v \ -d "{From: 'sender@email.com', To: 'recipient@email.com', Subject: 'Postmark test', HtmlBody: 'Hello dear Postmark user.'}"
[ "Ok so you should probably user urllib2 to submit the actual request but here is the code:\nimport urllib\nimport urllib2\n\nurl = \"http://api.postmarkapp.com/email\"\ndata = \"{From: 'sender@email.com', To: 'recipient@email.com', Subject: 'Postmark test', HtmlBody: 'Hello dear Postmark user.'}\"\nheaders = { \"...
[ 6 ]
[]
[]
[ "curl", "python" ]
stackoverflow_0004039884_curl_python.txt
Q: Conditional statements with Python lists I am trying to learn Python lists. In this code I am trying to add a string s coming from a form to table row as long as the string is the same. When the string is different; the new string is written to the next column. I could write the string from column 0 to column 1 but I had problems adding the same string on column 1 correctly. The way it is; the script works only up to placing the different string to the next column. I realize that this is not the right way of doing this. I would appreciate any help. Thank you. I include the template too. EDIT2 @JerseyMike: Thanks for your answer. I don't yet understand how AddString(str) works but trying it in IDLE I noticed that instead of adding the new string it replaces it with the new string. As I said, I have not yet studied how it works; but here is the result (I changed str to str1): >>> def AddString(str1): try: idx = map(lambda (s, v): ('N', 'Y')[s == str1], L).index('Y') except: L.append((str1, 1)) else: L[idx] = (str1, L[idx][1] + 1) >>> L = [] >>> str1 = 'hello' >>> AddString(str1) >>> L [('hello', 1)] >>> AddString(str1) >>> L [('hello', 2)] >>> EDIT @JerseyMike: Thanks, I am sorry, I realized the question was not clear. In this app; the user types in the same sentence; like practicing foreign language. So the input will be Hello world Hello world Hello world and if the user types in next "Hello universe" that will go to the next column: Hello world Hello Universe Hello world Hello world and if the user keeps typing "Hello Universe" they should go under the same column Hello world Hello Universe Hello world Hello Universe Hello world Hello Universe Hello Universe Hello Universe The list L containing this looks like this: L = [ ['Hello world', 'Hello Universe'], ['Hello world', 'Hello Universe'], ['Hello world', 'Hello Universe'], ['', 'Hello Universe'], ['', 'Hello Universe'] ] Initially the list is empty and I add the string s with L.append(s). L = [ ['Hello world'], ['Hello world'], ['Hello world'], ] If the last string s does not match the new input I create the new column with L[0].insert(1,s). L = [ ['Hello world', 'Hello Universe'], ['Hello world'], ['Hello world'], ] Now I need to write under 'Hello Universe' This turned out to be difficult for me to figure out for several reasons. But now I think it may be better to append the new string s to the list before checking if it is same as the previous string. To simplify the list, assume L is like this: L = [['A'], ['A'], ['A'], ['B']] Now ['B'] needs to be inserted into L[0]. To do this I search the list to the left to find the last sub-list with 1 element (or something like this). I have not looked into how to search lists yet. Thanks again for the help. END EDİT class Test(webapp.RequestHandler): myList = [] def get(self): # del self.myList[:] s = [self.request.get('sentence')] r = len(self.myList) if r == 0: self.myList.append(s) htmlcode1 = HTML.table(self.myList) lastItem = s else: if len(self.myList[0]) == 1: lastItem = self.myList[r-1] if s == lastItem: self.myList.append(s) htmlcode1 = HTML.table(self.myList) else: s = self.request.get('sentence') self.myList[0].insert(1,s) htmlcode1 = HTML.table(self.myList) if len(self.myList[0]) == 2: self.myList[1].insert(1,s) htmlcode1 = HTML.table(self.myList) elif len(self.myList[1]) == 2: self.myList[2].insert(1,s) htmlcode1 = HTML.table(self.myList) template_values = {'htmlcode1': htmlcode1, 's': s, 'r': r, 'myList': self.myList, # 'myListLen': myListLen, 'lastItem': lastItem, } path = os.path.join(os.path.dirname(__file__), 'test.mako') templ = Template(filename=path) self.response.out.write(templ.render(**template_values)) Template <html> <head> </head> <body> <p>| <a href="/delete">CLEAR</a> |</p> <form action="/test" method="get"> <input name="sentence" type="text" size="30"><br /> <input type="submit" value="Enter"> </form> <p>${htmlcode1}</p> <p>s: ${s}</p> <p>r: ${r}</p> <p>myList: ${myList}</p> <p>lastItem: ${lastItem}</p> </html> </body> A: If the order of the strings is important, a dictionary will be a problem. You are on the right path using lists, but I think you need more than just that. Honestly, I'm not clear on what your output will look like for different data sets. If I read your question correctly, is the following true? Input: Sentence 1 Sentence 3 Sentence 1 Sentence 1 Sentence 2 Sentence 2 Output after last line: Sentence 1 | Sentence 3 | Sentence 2 Sentence 1 | | Sentence 2 Sentence 1 | | If not, please rephrase your expected output with an example. Ok, so it looks like my take on your problem was correct. That's a good start. ;) I think we need to look at this from a different perspective. Currently, you are looking at this as a big list of all the data and maybe that's too much. What I see here is a list of tuples, where each tuple represents a column (string, count). The tuple will be what string should be in this column and how many of them should be there. So your example would end up looking like: L = [("Hello World", 3), ("Hello Universe", 5)] I know this isn't obvious as to how to deal with this data, but I think it's the right way to represent it internally. I'll give you some sample code to do some basic manipulations of this data type (others may have more efficient ways of doing the same thing). Add a new String: def AddString(str): try: idx = map(lambda (s, v): ('N', 'Y')[s == str], L).index('Y') except: L.append( (str, 1) ) else: L[idx] = (str, L[idx][1] + 1) Print the inside of an HTML table: def PrintChart(): try: max = reduce(lambda x, y: [x, y][x[1] < y[1]], L)[1] except: print "<td></td>" else: for i in range(max): print "<tr>" for (s, c) in L: if i+1 <= c: print " <td" + s + "</td>" else: print " <td></td>" print "</tr>" So anyway, that is the way I'd do it. A: If I were you, I wouldn't use nested lists. Instead, use a dictionary. What you can do with a dictionary is map keys (the strings you want one row each for) to values (in this case, however many times that string occurs, or the number of columns in that row of the table). So, you could do something a bit like this: def add_item(item, dict): if item in dict: dict[item] += 1 else: dict[item] = 1 You can reference individual strings or rows in the table by using dict[string] and see how many columns that row has. Also, using a dictionary is far more concise, memory efficient, and fast than using nested lists. If you REALLY have to do this with nested lists, let me know and I'll try and help with that. A: Looks to me like you're trying to shoehorn everything into the one list, which is going to make your code hard to write. Something to note is that you're adding blank strings ('') to your list to pad it out, which is a bit of a warning sign that your data structure is wrong. Rather than do that, I'd use a dictionary keyed off either an id or the original text, store the user input as a list after that, then sort out how to display this in the display part of your code. Something like: typing = { 'Hello World': ['Hello World', 'Hello World', 'Hello World'] 'Hello Universe': ['Hello Universe', 'Hello Universe', 'Hello Universe', ...] } Bear in mind that dictionaries are unordered though, so you might need to either use a list to order them, or use sorteddict from the collections library.
Conditional statements with Python lists
I am trying to learn Python lists. In this code I am trying to add a string s coming from a form to table row as long as the string is the same. When the string is different; the new string is written to the next column. I could write the string from column 0 to column 1 but I had problems adding the same string on column 1 correctly. The way it is; the script works only up to placing the different string to the next column. I realize that this is not the right way of doing this. I would appreciate any help. Thank you. I include the template too. EDIT2 @JerseyMike: Thanks for your answer. I don't yet understand how AddString(str) works but trying it in IDLE I noticed that instead of adding the new string it replaces it with the new string. As I said, I have not yet studied how it works; but here is the result (I changed str to str1): >>> def AddString(str1): try: idx = map(lambda (s, v): ('N', 'Y')[s == str1], L).index('Y') except: L.append((str1, 1)) else: L[idx] = (str1, L[idx][1] + 1) >>> L = [] >>> str1 = 'hello' >>> AddString(str1) >>> L [('hello', 1)] >>> AddString(str1) >>> L [('hello', 2)] >>> EDIT @JerseyMike: Thanks, I am sorry, I realized the question was not clear. In this app; the user types in the same sentence; like practicing foreign language. So the input will be Hello world Hello world Hello world and if the user types in next "Hello universe" that will go to the next column: Hello world Hello Universe Hello world Hello world and if the user keeps typing "Hello Universe" they should go under the same column Hello world Hello Universe Hello world Hello Universe Hello world Hello Universe Hello Universe Hello Universe The list L containing this looks like this: L = [ ['Hello world', 'Hello Universe'], ['Hello world', 'Hello Universe'], ['Hello world', 'Hello Universe'], ['', 'Hello Universe'], ['', 'Hello Universe'] ] Initially the list is empty and I add the string s with L.append(s). L = [ ['Hello world'], ['Hello world'], ['Hello world'], ] If the last string s does not match the new input I create the new column with L[0].insert(1,s). L = [ ['Hello world', 'Hello Universe'], ['Hello world'], ['Hello world'], ] Now I need to write under 'Hello Universe' This turned out to be difficult for me to figure out for several reasons. But now I think it may be better to append the new string s to the list before checking if it is same as the previous string. To simplify the list, assume L is like this: L = [['A'], ['A'], ['A'], ['B']] Now ['B'] needs to be inserted into L[0]. To do this I search the list to the left to find the last sub-list with 1 element (or something like this). I have not looked into how to search lists yet. Thanks again for the help. END EDİT class Test(webapp.RequestHandler): myList = [] def get(self): # del self.myList[:] s = [self.request.get('sentence')] r = len(self.myList) if r == 0: self.myList.append(s) htmlcode1 = HTML.table(self.myList) lastItem = s else: if len(self.myList[0]) == 1: lastItem = self.myList[r-1] if s == lastItem: self.myList.append(s) htmlcode1 = HTML.table(self.myList) else: s = self.request.get('sentence') self.myList[0].insert(1,s) htmlcode1 = HTML.table(self.myList) if len(self.myList[0]) == 2: self.myList[1].insert(1,s) htmlcode1 = HTML.table(self.myList) elif len(self.myList[1]) == 2: self.myList[2].insert(1,s) htmlcode1 = HTML.table(self.myList) template_values = {'htmlcode1': htmlcode1, 's': s, 'r': r, 'myList': self.myList, # 'myListLen': myListLen, 'lastItem': lastItem, } path = os.path.join(os.path.dirname(__file__), 'test.mako') templ = Template(filename=path) self.response.out.write(templ.render(**template_values)) Template <html> <head> </head> <body> <p>| <a href="/delete">CLEAR</a> |</p> <form action="/test" method="get"> <input name="sentence" type="text" size="30"><br /> <input type="submit" value="Enter"> </form> <p>${htmlcode1}</p> <p>s: ${s}</p> <p>r: ${r}</p> <p>myList: ${myList}</p> <p>lastItem: ${lastItem}</p> </html> </body>
[ "If the order of the strings is important, a dictionary will be a problem. You are on the right path using lists, but I think you need more than just that. Honestly, I'm not clear on what your output will look like for different data sets. If I read your question correctly, is the following true?\nInput:\nSenten...
[ 2, 0, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0004011728_if_statement_python.txt
Q: Compatibility layer above AWS & GAE? Has anyone developed an abstraction layer above Amazon Web Services and the Google App Engine? It would be nice to be able to develop a system that could be migrated between either of those two platforms. I am interested in Python. A: Look at TyphoonAE or AppScale. Both projects provide an App Engine like environment. I have successfully ran Python applications, with no modifications, built using webapp on TyphoonAE. You can also look at django-nonrel or web2py for frameworks with features designed to make moving between GAE + bigtable and other datastores easy. A: You are talking about an infrastructure service (IaaS - ec2) and platform service (PaaS - GAE) - the latter is built on something like the former (but obviously GAE doesn't run on ec2). To get the portability you want - you would need to build in something that runs nicely on GAE - and then work out how to rebuild that platform infrastructure underneath on EC2 (probably not a trivial task). Given that GAE for python is very close to django, for simple apps, carefully written, you may be able to achieve this somewhat by using some django images on AWS/ec2 (obviously a sys admin burden now rests with you whereas it did not with GAE). Hope that helps !
Compatibility layer above AWS & GAE?
Has anyone developed an abstraction layer above Amazon Web Services and the Google App Engine? It would be nice to be able to develop a system that could be migrated between either of those two platforms. I am interested in Python.
[ "Look at TyphoonAE or AppScale. Both projects provide an App Engine like environment. I have successfully ran Python applications, with no modifications, built using webapp on TyphoonAE.\nYou can also look at django-nonrel or web2py for frameworks with features designed to make moving between GAE + bigtable and o...
[ 4, 1 ]
[]
[]
[ "amazon_web_services", "google_app_engine", "python" ]
stackoverflow_0004039685_amazon_web_services_google_app_engine_python.txt
Q: How to make Xcode Python friendly? I have started using Xcode as my main code editor. How might I make Xcode do things like using # instead of // for comments, and otherwise making the IDE friendlier? A: From what I can see it already gets the syntax highlighting right, so I think you're talking about the Cmd-/ script that comments a region out. If you select the Edit User Scripts option from the scripts menu you'll set that it's just a perl script. Find the line that tests the shebang in the file for what comment type and make it look for python too: if ($fileString =~ m!^($perlCmt|$cCmt)?#\!\s*.*?/perl|^($perlCmt|$cCmt)?#\!\s*.*?/sh|^($perlCmt|$cCmt)?#\!\s*.*?/python!) Note that you'll need to add the python shebang to files you want this to work with.
How to make Xcode Python friendly?
I have started using Xcode as my main code editor. How might I make Xcode do things like using # instead of // for comments, and otherwise making the IDE friendlier?
[ "From what I can see it already gets the syntax highlighting right, so I think you're talking about the Cmd-/ script that comments a region out. If you select the Edit User Scripts option from the scripts menu you'll set that it's just a perl script. Find the line that tests the shebang in the file for what comment...
[ 2 ]
[]
[]
[ "python", "xcode" ]
stackoverflow_0004040060_python_xcode.txt
Q: How to create a form in django using ChoiceField in foms.py I have to build a form where I want a drop down menu list, what will be the procedure. If u can then plz do tell me the stepwise procedur coz I am a beginner in python. example, what code to be written in views.py, forms.py and urls.py etc. Thanks in advance................Byeee A: Choices are easy to specify manually (or, for that matter, programatically) in Django. This depicts a model, which will in turn have a dropdown selector in a ModelForm: http://docs.djangoproject.com/en/dev/ref/models/fields/#choices You can do the same thing in a regular form.
How to create a form in django using ChoiceField in foms.py
I have to build a form where I want a drop down menu list, what will be the procedure. If u can then plz do tell me the stepwise procedur coz I am a beginner in python. example, what code to be written in views.py, forms.py and urls.py etc. Thanks in advance................Byeee
[ "Choices are easy to specify manually (or, for that matter, programatically) in Django.\nThis depicts a model, which will in turn have a dropdown selector in a ModelForm:\nhttp://docs.djangoproject.com/en/dev/ref/models/fields/#choices\nYou can do the same thing in a regular form.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004039897_django_python.txt
Q: Cant determine whats causing an regex error, and would like some input on the efficiency of my program Nearing what I would like to think is completion on a tool I've been working on. What I've got going on is some code that does essentially this: open several files and urls which consist of known malware/phishing related websites/domains and create a list for each, Parse the html of a url passed when the method is called, pulling out all the a href links and placing them in a separate list, for every link that was placed in the new list, create a regex for every item thats in the malware and phishing lists, and then compare against to determine if any of the links parsed from the URL passed when the method was called are malicious. The problem I've ran into is in iterating over the items of all 3 lists, obviously I'm doing it wrong since its throwing this error at me: File "./test.py", line 95, in <module> main() File "./test.py", line 92, in main crawler.crawl(url) File "./test.py", line 41, in crawl self.reg1 = re.compile(link1) File "/usr/lib/python2.6/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.6/re.py", line 245, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat The following is the segment of code I'm having problems with, with the malware related list create omitted as that part is working fine for me: def crawl(self, url): try: doc = parse("http://" + url).getroot() doc.make_links_absolute("http://" + url, resolve_base_href=True) for tag in doc.xpath("//a[@href]"): old = tag.get('href') fixed = urllib.unquote(old) self.links.append(fixed) except urllib.error.URLERROR as err: print(err) for tgt in self.links: for link in self.mal_list: self.reg = re.compile(link) for link1 in self.phish_list: self.reg1 = re.compile(link1) found = self.reg.search(tgt) if found: print(found.group()) else: print("No matches found...") Can anyone spot what I've done wrong with the for loops and list iteration that would be causing that regex error? How might I fix it? And probably most importantly is the way I'm going about doing this 'pythonic' or even efficient? Considering what I'm trying to do here, is there a better way of doing it? A: It seems like your problem is that some of the URLs contain special regex characters, such as ? and +; for instance, the string ++ is really quite likely. The other problem is that you keep overwriting the regex you're using to test. If you just need to check if one string is contained in another, there's no need for a regex; just use for tgt in self.links: for link in (self.mal_list + self.phish_list): if link in tgt: print link And if you're just comparing for equality, you can use == instead of in.
Cant determine whats causing an regex error, and would like some input on the efficiency of my program
Nearing what I would like to think is completion on a tool I've been working on. What I've got going on is some code that does essentially this: open several files and urls which consist of known malware/phishing related websites/domains and create a list for each, Parse the html of a url passed when the method is called, pulling out all the a href links and placing them in a separate list, for every link that was placed in the new list, create a regex for every item thats in the malware and phishing lists, and then compare against to determine if any of the links parsed from the URL passed when the method was called are malicious. The problem I've ran into is in iterating over the items of all 3 lists, obviously I'm doing it wrong since its throwing this error at me: File "./test.py", line 95, in <module> main() File "./test.py", line 92, in main crawler.crawl(url) File "./test.py", line 41, in crawl self.reg1 = re.compile(link1) File "/usr/lib/python2.6/re.py", line 190, in compile return _compile(pattern, flags) File "/usr/lib/python2.6/re.py", line 245, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat The following is the segment of code I'm having problems with, with the malware related list create omitted as that part is working fine for me: def crawl(self, url): try: doc = parse("http://" + url).getroot() doc.make_links_absolute("http://" + url, resolve_base_href=True) for tag in doc.xpath("//a[@href]"): old = tag.get('href') fixed = urllib.unquote(old) self.links.append(fixed) except urllib.error.URLERROR as err: print(err) for tgt in self.links: for link in self.mal_list: self.reg = re.compile(link) for link1 in self.phish_list: self.reg1 = re.compile(link1) found = self.reg.search(tgt) if found: print(found.group()) else: print("No matches found...") Can anyone spot what I've done wrong with the for loops and list iteration that would be causing that regex error? How might I fix it? And probably most importantly is the way I'm going about doing this 'pythonic' or even efficient? Considering what I'm trying to do here, is there a better way of doing it?
[ "It seems like your problem is that some of the URLs contain special regex characters, such as ? and +; for instance, the string ++ is really quite likely. The other problem is that you keep overwriting the regex you're using to test. If you just need to check if one string is contained in another, there's no nee...
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004040147_python_regex.txt
Q: Help with a Python Sudoku Verifier with Loops Im working on a a sudoku program for python and i need some help. The program will ask input from the user for 9 rows of numbers that hopefully contain the digits 1-9. Once they input all 9 rows the program should then go through each row and verify and see if it satisfies the conditions of a sudoku game. If it doesnt it will return a error message and display which row has an error. Now what i need help in is how to best check the rows without writing 9 different if statements. I need to incorporate a loop. How would i do this? My progress in code so far is below: from a5_import import * import sys sep = "-.-.-.-.-.-.-.-.-.-.-.-.-.-.-." print sep print " Sudoku Verifier! " print sep row_0=int(raw_input("Enter Row 0: ")) row_1=int(raw_input("Enter Row 1: ")) row_2=int(raw_input("Enter Row 2: ")) row_3=int(raw_input("Enter Row 3: ")) row_4=int(raw_input("Enter Row 4: ")) row_5=int(raw_input("Enter Row 5: ")) row_6=int(raw_input("Enter Row 6: ")) row_7=int(raw_input("Enter Row 7: ")) row_8=int(raw_input("Enter Row 8: ")) if not check9(row0): print "Error: row 0 is invalid." if not check9(row1): print "Error: row 1 is invalid." if not check9(row2): print "Error: row 2 is invalid." if not check9(row3): print "Error: row 3 is invalid." if not check9(row4): print "Error: row 4 is invalid." if not check9(row5): print "Error: row 5 is invalid." if not check9(row6): print "Error: row 6 is invalid." if not check9(row7): print "Error: row 7 is invalid." if not check9(row8): print "Error: row 8 is invalid." print sep Again the requirements are i need the following three things to be accomplished: The program produces the correct output The program uses a loop correctly to check the columns of the input. The program uses a loop correctly to check the boxes of the input. Thanks for your help with the verifier loops. A: You can check the rows by converting them to sets if set(row) == set(range(1,10)): # ok ... you'll need to convert the row to a str first though A: Ok, I can see room for two loops in this scenario. LoopA a loop that gets the input and LoopB a loop that checks the output an example here: from a5_import import * import sys sep = "-.-.-.-.-.-.-.-.-.-.-.-.-.-.-." print sep print " Sudoku Verifier! " print sep rows = [] for rowNum in range(1, 9): rowInput = int(raw_input("Enter Row %s: "% rowNum)) ## This is the same as int(raw_input("Enter Row +rowNum+": ")) rows.append(rowInput) ##add the input to the list of rows for row in rows: if not check9(row): print "Row %s is not valid"% rows[rows.index(row)] ##Prints the row position number print sep The use of a list of rows would be the best bet for validation. A: I would recommend looking at using arrays instead of doing row_0, row_1, row_2 etc. Try something more like this: row = [] for count in range (0, 9): answer = int(raw_input("Enter Row %s: " % count)) if answer in row: PROBLEM? else: row.append (answer)
Help with a Python Sudoku Verifier with Loops
Im working on a a sudoku program for python and i need some help. The program will ask input from the user for 9 rows of numbers that hopefully contain the digits 1-9. Once they input all 9 rows the program should then go through each row and verify and see if it satisfies the conditions of a sudoku game. If it doesnt it will return a error message and display which row has an error. Now what i need help in is how to best check the rows without writing 9 different if statements. I need to incorporate a loop. How would i do this? My progress in code so far is below: from a5_import import * import sys sep = "-.-.-.-.-.-.-.-.-.-.-.-.-.-.-." print sep print " Sudoku Verifier! " print sep row_0=int(raw_input("Enter Row 0: ")) row_1=int(raw_input("Enter Row 1: ")) row_2=int(raw_input("Enter Row 2: ")) row_3=int(raw_input("Enter Row 3: ")) row_4=int(raw_input("Enter Row 4: ")) row_5=int(raw_input("Enter Row 5: ")) row_6=int(raw_input("Enter Row 6: ")) row_7=int(raw_input("Enter Row 7: ")) row_8=int(raw_input("Enter Row 8: ")) if not check9(row0): print "Error: row 0 is invalid." if not check9(row1): print "Error: row 1 is invalid." if not check9(row2): print "Error: row 2 is invalid." if not check9(row3): print "Error: row 3 is invalid." if not check9(row4): print "Error: row 4 is invalid." if not check9(row5): print "Error: row 5 is invalid." if not check9(row6): print "Error: row 6 is invalid." if not check9(row7): print "Error: row 7 is invalid." if not check9(row8): print "Error: row 8 is invalid." print sep Again the requirements are i need the following three things to be accomplished: The program produces the correct output The program uses a loop correctly to check the columns of the input. The program uses a loop correctly to check the boxes of the input. Thanks for your help with the verifier loops.
[ "You can check the rows by converting them to sets\nif set(row) == set(range(1,10)):\n # ok\n ...\n\nyou'll need to convert the row to a str first though\n", "Ok, I can see room for two loops in this scenario.\nLoopA a loop that gets the input and LoopB a loop that checks the output an example here:\nfrom a...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004040304_python.txt
Q: Python OLS calculation Is there any good library to calculate linear least squares OLS (Ordinary Least Squares) in python? Thanks. Edit: Thanks for the SciKits and Scipy. @ars: Can X be a matrix? An example: y(1) = a(1)*x(11) + a(2)*x(12) + a(3)*x(13) y(2) = a(1)*x(21) + a(2)*x(22) + a(3)*x(23) ........................................... y(n) = a(1)*x(n1) = a(2)*x(n2) + a(3)*x(n3) Then how do I pass the parameters for Y and X matrices in your example? Also, I don't have much background in algebra, I would appreciate if you guys can let me know a good tutorial for that kind of problems. Thanks much. A: Try the statsmodels package. Here's a quick example: import pylab import numpy as np import statsmodels.api as sm x = np.arange(-10, 10) y = 2*x + np.random.normal(size=len(x)) # model matrix with intercept X = sm.add_constant(x) # least squares fit model = sm.OLS(y, X) fit = model.fit() print fit.summary() pylab.scatter(x, y) pylab.plot(x, fit.fittedvalues) Update In response to the updated question, yes it works with matrices. Note that the code above has the x data in array form, but we build a matrix X (capital X) to pass to OLS. The add_constant function simply builds the matrix with a first column initialized to ones for the intercept. In your case, you would simply pass your X matrix without needing that intermediate step and it would work. A: Have you looked at SciPy? I don't know if it does that, but I would imagine it will.
Python OLS calculation
Is there any good library to calculate linear least squares OLS (Ordinary Least Squares) in python? Thanks. Edit: Thanks for the SciKits and Scipy. @ars: Can X be a matrix? An example: y(1) = a(1)*x(11) + a(2)*x(12) + a(3)*x(13) y(2) = a(1)*x(21) + a(2)*x(22) + a(3)*x(23) ........................................... y(n) = a(1)*x(n1) = a(2)*x(n2) + a(3)*x(n3) Then how do I pass the parameters for Y and X matrices in your example? Also, I don't have much background in algebra, I would appreciate if you guys can let me know a good tutorial for that kind of problems. Thanks much.
[ "Try the statsmodels package. Here's a quick example:\nimport pylab\nimport numpy as np\nimport statsmodels.api as sm\n\nx = np.arange(-10, 10)\ny = 2*x + np.random.normal(size=len(x))\n\n# model matrix with intercept\nX = sm.add_constant(x)\n\n# least squares fit\nmodel = sm.OLS(y, X)\nfit = model.fit()\n\nprint ...
[ 9, 4 ]
[]
[]
[ "python" ]
stackoverflow_0004040322_python.txt
Q: wxPython and StaticBox(Sizer) issue Recently I've been having an issue with the code shown below and it's been bugging me for a while now. I don't know why it's happening, the only thing I know is that the python code brings up a segfault on the line noted and gdb brings up something about memory. Am I doing something wrong or is this a bug? I'd really like to get this working, so if you can help I'd greatly appreciate it. C++ code: static int win_width = 364; static int win_height = 478; netlist = new wxDialog(NULL, wxID_ANY, "Network List", wxDefaultPosition, wxSize(win_width-8, win_height-8), wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER); wxBoxSizer *hszr = new wxBoxSizer(wxHORIZONTAL), *vszr = new wxBoxSizer(wxVERTICAL), *vszr2 = new wxBoxSizer(wxVERTICAL); wxStaticBoxSizer* sszr = new wxStaticBoxSizer(wxVERTICAL, netlist, "User Information"); wxFlexGridSizer* fgszr = new wxFlexGridSizer(2); fgszr->Add(new wxStaticText(sszr->GetStaticBox(), wxID_ANY, "Nick Name: ")); Python code: win_width = 364 win_height = 478 netlist = wx.Dialog(None, wx.ID_ANY, "Network List", wx.DefaultPosition, wx.Size(win_width-8, win_height-8), wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) hszr = wx.BoxSizer(wx.HORIZONTAL) vszr = wx.BoxSizer(wx.VERTICAL) vszr2 = wx.BoxSizer(wx.VERTICAL) sszr = wx.StaticBoxSizer(wx.StaticBox(netlist, wx.ID_ANY, "User Information"), orient=wx.VERTICAL) fgszr = wx.FlexGridSizer(2) fgszr.Add(wx.StaticText(sszr.GetStaticBox(), wx.ID_ANY, "Nick Name: ")) # Segmentation Fault A: On the python side, the Add method has the following arguments: Add(self, item, int proportion=0, int flag=0, int border=0, userData=None) proportion is not an id (but that silently passes because they are both integers) and flag is not a string. Compared to the C++ version a working line would be: fgszr.Add(wx.StaticText(sszr.GetStaticBox(), wx.ID_ANY, "Nick Name: ")) UPDATE: The following code successfully executed on windows using wxPython 2.9.1.1 import wx app = wx.PySimpleApp() win_width = 364 win_height = 478 netlist = wx.Dialog(None, wx.ID_ANY, "Network List", wx.DefaultPosition, wx.Size(win_width-8, win_height-8), wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) hszr = wx.BoxSizer(wx.HORIZONTAL) vszr = wx.BoxSizer(wx.VERTICAL) vszr2 = wx.BoxSizer(wx.VERTICAL) sszr = wx.StaticBoxSizer(wx.StaticBox(netlist, wx.ID_ANY, "User Information"), orient=wx.VERTICAL) fgszr = wx.FlexGridSizer(2) fgszr.Add(wx.StaticText(sszr.GetStaticBox(), wx.ID_ANY, "Nick Name: ")) # Segmentation Fault netlist.ShowModal()
wxPython and StaticBox(Sizer) issue
Recently I've been having an issue with the code shown below and it's been bugging me for a while now. I don't know why it's happening, the only thing I know is that the python code brings up a segfault on the line noted and gdb brings up something about memory. Am I doing something wrong or is this a bug? I'd really like to get this working, so if you can help I'd greatly appreciate it. C++ code: static int win_width = 364; static int win_height = 478; netlist = new wxDialog(NULL, wxID_ANY, "Network List", wxDefaultPosition, wxSize(win_width-8, win_height-8), wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER); wxBoxSizer *hszr = new wxBoxSizer(wxHORIZONTAL), *vszr = new wxBoxSizer(wxVERTICAL), *vszr2 = new wxBoxSizer(wxVERTICAL); wxStaticBoxSizer* sszr = new wxStaticBoxSizer(wxVERTICAL, netlist, "User Information"); wxFlexGridSizer* fgszr = new wxFlexGridSizer(2); fgszr->Add(new wxStaticText(sszr->GetStaticBox(), wxID_ANY, "Nick Name: ")); Python code: win_width = 364 win_height = 478 netlist = wx.Dialog(None, wx.ID_ANY, "Network List", wx.DefaultPosition, wx.Size(win_width-8, win_height-8), wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) hszr = wx.BoxSizer(wx.HORIZONTAL) vszr = wx.BoxSizer(wx.VERTICAL) vszr2 = wx.BoxSizer(wx.VERTICAL) sszr = wx.StaticBoxSizer(wx.StaticBox(netlist, wx.ID_ANY, "User Information"), orient=wx.VERTICAL) fgszr = wx.FlexGridSizer(2) fgszr.Add(wx.StaticText(sszr.GetStaticBox(), wx.ID_ANY, "Nick Name: ")) # Segmentation Fault
[ "On the python side, the Add method has the following arguments:\nAdd(self, item, int proportion=0, int flag=0, int border=0, userData=None)\n\nproportion is not an id (but that silently passes because they are both integers) and flag is not a string.\nCompared to the C++ version a working line would be:\nfgszr.Add...
[ 0 ]
[]
[]
[ "c++", "python", "wxpython", "wxwidgets" ]
stackoverflow_0004039372_c++_python_wxpython_wxwidgets.txt
Q: Why does this SQLAlchemy example commit changes to the DB? This example illustrates a mystery I encountered in an application I am building. The application needs to support an option allowing the user to exercise the code without actually committing changes to the DB. However, when I added this option, I discovered that changes were persisted to the DB even when I did not call the commit() method. My specific question can be found in the code comments. The underlying goal is to have a clearer understanding of when and why SQLAlchemy will commit to the DB. My broader question is whether my application should (a) use a global Session instance, or (b) use a global Session class, from which particular instances would be instantiated. Based on this example, I'm starting to think that the correct answer is (b). Is that right? Edit: this SQLAlchemy documentation suggests that (b) is recommended. import sys from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key = True) name = Column(String) age = Column(Integer) def __init__(self, name, age = 0): self.name = name self.age = 0 def __repr__(self): return "<User(name='{0}', age={1})>".format(self.name, self.age) engine = create_engine('sqlite://', echo = False) Base.metadata.create_all(engine) Session = sessionmaker() Session.configure(bind=engine) global_session = Session() # A global Session instance. commit_ages = False # Whether to commit in modify_ages(). use_global = True # If True, modify_ages() will commit, regardless # of the value of commit_ages. Why? def get_session(): return global_session if use_global else Session() def add_users(names): s = get_session() s.add_all(User(nm) for nm in names) s.commit() def list_users(): s = get_session() for u in s.query(User): print ' ', u def modify_ages(): s = get_session() n = 0 for u in s.query(User): n += 10 u.age = n if commit_ages: s.commit() add_users(('A', 'B', 'C')) print '\nBefore:' list_users() modify_ages() print '\nAfter:' list_users() A: tl;dr - The updates are not actually committed to the database-- they are part of an uncommitted transaction in progress. I made 2 separate changes to your call to create_engine(). (Other than this one line, I'm using your code exactly as posted.) The first was engine = create_engine('sqlite://', echo = True) This provides some useful information. I'm not going to post the entire output here, but notice that no SQL update commands are issued until after the second call to list_users() is made: ... After: xxxx-xx-xx xx:xx:xx,xxx INFO sqlalchemy.engine.base.Engine.0x...d3d0 UPDATE users SET age=? WHERE users.id = ? xxxx-xx-xx xx:xx:xx,xxx INFO sqlalchemy.engine.base.Engine.0x...d3d0 (10, 1) ... This is a clue that the data is not persisted, but kept around in the session object. The second change I made was to persist the database to a file with engine = create_engine('sqlite:///db.sqlite', echo = True) Running the script again provides the same output as before for the second call to list_users(): <User(name='A', age=10)> <User(name='B', age=20)> <User(name='C', age=30)> However, if you now open the db we just created and query it's contents, you can see that the added users were persisted to the database, but the age modifications were not: $ sqlite3 db.sqlite "select * from users" 1|A|0 2|B|0 3|C|0 So, the second call to list_users() is getting its values from the session object, not from the database, because there is a transaction in progress that hasn't been committed yet. To prove this, add the following lines to the end of your script: s = get_session() s.rollback() print '\nAfter rollback:' list_users() A: Since you state you are actually using MySQL on the system you are seeing the problem, check the engine type the table was created with. The default is MyISAM, which does not support ACID transactions. Make sure you are using the InnoDB engine, which does do ACID transactions. You can see which engine a table is using with show create table users; You can change the db engine for a table with alter table: alter table users engine="InnoDB"; A: 1. the example: Just to make sure that (or check if) the session does not commit the changes, it is enough to call expunge_all on the session object. This will most probably prove that the changes are not actually committed: .... print '\nAfter:' get_session().expunge_all() list_users() 2. mysql: As you already mentioned, the sqlite example might not reflect what you actually see when using mysql. As documented in sqlalchemy - MySQL - Storage Engines, the most likely reason for your problem is the usage of non-transactional storage engines (like MyISAM), which results in an autocommit mode of execution. 3. session scope: Although having one global session sounds like a quest for a problem, using new session for every tiny little request is also not a great idea. You should think of a session as a transaction/unit-of-work. I find the usage of the contextual sessions the best of two worlds, where you do not have to pass the session object in the hierarchy of method calls, and at the same time you are given a pretty good safety in the multi-threaded environment. I do use the local session once in a while where I know I do not want to interact with the currently running transaction (session). A: Note that the defaults of create_session() are the opposite of that of sessionmaker(): autoflush and expire_on_commit are False, autocommit is True. A: global_session is already instantiated when you call modify_ages() and you've already committed to the database. If you re-instantiate global_session after you commit, it should start a new transaction. My guess is since you've already committed and are re-using the same object, each additional modification is automatically committed.
Why does this SQLAlchemy example commit changes to the DB?
This example illustrates a mystery I encountered in an application I am building. The application needs to support an option allowing the user to exercise the code without actually committing changes to the DB. However, when I added this option, I discovered that changes were persisted to the DB even when I did not call the commit() method. My specific question can be found in the code comments. The underlying goal is to have a clearer understanding of when and why SQLAlchemy will commit to the DB. My broader question is whether my application should (a) use a global Session instance, or (b) use a global Session class, from which particular instances would be instantiated. Based on this example, I'm starting to think that the correct answer is (b). Is that right? Edit: this SQLAlchemy documentation suggests that (b) is recommended. import sys from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key = True) name = Column(String) age = Column(Integer) def __init__(self, name, age = 0): self.name = name self.age = 0 def __repr__(self): return "<User(name='{0}', age={1})>".format(self.name, self.age) engine = create_engine('sqlite://', echo = False) Base.metadata.create_all(engine) Session = sessionmaker() Session.configure(bind=engine) global_session = Session() # A global Session instance. commit_ages = False # Whether to commit in modify_ages(). use_global = True # If True, modify_ages() will commit, regardless # of the value of commit_ages. Why? def get_session(): return global_session if use_global else Session() def add_users(names): s = get_session() s.add_all(User(nm) for nm in names) s.commit() def list_users(): s = get_session() for u in s.query(User): print ' ', u def modify_ages(): s = get_session() n = 0 for u in s.query(User): n += 10 u.age = n if commit_ages: s.commit() add_users(('A', 'B', 'C')) print '\nBefore:' list_users() modify_ages() print '\nAfter:' list_users()
[ "tl;dr - The updates are not actually committed to the database-- they are part of an uncommitted transaction in progress.\n\nI made 2 separate changes to your call to create_engine(). (Other than this one line, I'm using your code exactly as posted.)\nThe first was \nengine = create_engine('sqlite://', echo = True...
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "commit", "python", "session", "sqlalchemy" ]
stackoverflow_0003998546_commit_python_session_sqlalchemy.txt
Q: wx.ProgressDialog using a counter instead of a timer I need to include a progress bar in my wxpython application, but the examples I found use a timer counting down from a fixed time length. Since I have no idea how long it will take a given computer to run my process, I want the progress bar to simply update whenever each specific step is completed. I modified some sample code to accomplish this, but it throws the following error: path/ProgressDialog.py", line 31, in OnTimer (keepGoing, skip) = self.dialog.Update(self.count) File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 2971, in Update return _windows_.ProgressDialog_Update(*args, **kwargs) PyAssertionError: C++ assertion "value <= m_maximum" failed at ..\..\src\generic\progdlgg.cpp(337) in wxProgressDialog::Update(): invalid progress value When I add the try...except statement in the code below, it does not throw the error, but I am thinking that there must be a better way of doing this than simply drawing a fig leaf over the error message. Can anyone show me how to fix my code? My code is as follows, including the try...except statement that "removes" the error: import wx import time class Frame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, title="ProgressDialog sample") self.progressMax = 7 self.count = 0 self.dialog = None #self.timer = wx.Timer(self) #self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) #self.timer.Start(1000) self.OnTimer(self.count) def OnTimer(self, evt): try: if not self.dialog: self.dialog = wx.ProgressDialog("A progress box", "Time remaining", self.progressMax, style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_ESTIMATED_TIME | wx.PD_AUTO_HIDE) while self.count < 8: self.count += 1 if wx.VERSION < (2,7,1,1): keepGoing = self.dialog.Update(self.count) else: (keepGoing, skip) = self.dialog.Update(self.count) time.sleep(2) if not keepGoing or self.count == self.progressMax: self.dialog.Destroy() #self.timer.Stop() except: pass if __name__ == "__main__": app = wx.PySimpleApp() frame = Frame(None) frame.Show() app.MainLoop() Note: I am using a while loop to simulate stepping through process steps while I am testing this code. But in the actual implementation, I will have a specific process step occur before each time that self.count is increased by 1. A: Your progressMax is 7 and the loop loops while count is less than 8, but you increment count on the first line of the loop so you have an iteration where count is 8 and that is an illegal value for the progress bar. Either change the while condition to count < 7 (conveniently count < progressMax) or move the count increment to the end of the loop.
wx.ProgressDialog using a counter instead of a timer
I need to include a progress bar in my wxpython application, but the examples I found use a timer counting down from a fixed time length. Since I have no idea how long it will take a given computer to run my process, I want the progress bar to simply update whenever each specific step is completed. I modified some sample code to accomplish this, but it throws the following error: path/ProgressDialog.py", line 31, in OnTimer (keepGoing, skip) = self.dialog.Update(self.count) File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 2971, in Update return _windows_.ProgressDialog_Update(*args, **kwargs) PyAssertionError: C++ assertion "value <= m_maximum" failed at ..\..\src\generic\progdlgg.cpp(337) in wxProgressDialog::Update(): invalid progress value When I add the try...except statement in the code below, it does not throw the error, but I am thinking that there must be a better way of doing this than simply drawing a fig leaf over the error message. Can anyone show me how to fix my code? My code is as follows, including the try...except statement that "removes" the error: import wx import time class Frame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, title="ProgressDialog sample") self.progressMax = 7 self.count = 0 self.dialog = None #self.timer = wx.Timer(self) #self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) #self.timer.Start(1000) self.OnTimer(self.count) def OnTimer(self, evt): try: if not self.dialog: self.dialog = wx.ProgressDialog("A progress box", "Time remaining", self.progressMax, style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_ESTIMATED_TIME | wx.PD_AUTO_HIDE) while self.count < 8: self.count += 1 if wx.VERSION < (2,7,1,1): keepGoing = self.dialog.Update(self.count) else: (keepGoing, skip) = self.dialog.Update(self.count) time.sleep(2) if not keepGoing or self.count == self.progressMax: self.dialog.Destroy() #self.timer.Stop() except: pass if __name__ == "__main__": app = wx.PySimpleApp() frame = Frame(None) frame.Show() app.MainLoop() Note: I am using a while loop to simulate stepping through process steps while I am testing this code. But in the actual implementation, I will have a specific process step occur before each time that self.count is increased by 1.
[ "Your progressMax is 7 and the loop loops while count is less than 8, but you increment count on the first line of the loop so you have an iteration where count is 8 and that is an illegal value for the progress bar.\nEither change the while condition to count < 7 (conveniently count < progressMax) or move the coun...
[ 1 ]
[]
[]
[ "progress_bar", "progressdialog", "python", "wxpython" ]
stackoverflow_0004038281_progress_bar_progressdialog_python_wxpython.txt
Q: Django: tracking all the database changes with values I have to implement an application in django which will track all the changes in the database with the previous values,current value,action,date,time, user(who performed the changes) etc. Is there any application/module available in python or django which can perform these actions with may be after some changes. I have seen "fullhistory" app in Django but it does not fits into the requirement. Please suggest. Thanks in advance A: Django-reversion http://github.com/etianen/django-reversion could be an alternative. A: fullhistory seems to do most of what you want - what part of the requirement does it not fulfil? It might be easier to enhance fullhistory. Another option is to do it at the database level, if your database supports logging at that level.
Django: tracking all the database changes with values
I have to implement an application in django which will track all the changes in the database with the previous values,current value,action,date,time, user(who performed the changes) etc. Is there any application/module available in python or django which can perform these actions with may be after some changes. I have seen "fullhistory" app in Django but it does not fits into the requirement. Please suggest. Thanks in advance
[ "Django-reversion http://github.com/etianen/django-reversion could be an alternative.\n", "fullhistory seems to do most of what you want - what part of the requirement does it not fulfil? It might be easier to enhance fullhistory.\nAnother option is to do it at the database level, if your database supports loggin...
[ 4, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004040656_django_django_models_python.txt
Q: signed bitwise arithmetic in Python I got stuck with the following Python code >>> a = 0xff >>> b = 1 << 8 >>> ~a & ~b -512 Why is it -512? In binary notation it should look like this: a 0 1111 1111 -> 255 b 01 0000 0000 -> 256 ~a 1 0000 0000 -> -256 ~b 10 1111 1111 -> -257 ~a&~b 00 0000 0000 -> 0 I expected 0 as with signed int in C: signed int a = 0xff; signed int b = 1 << 8; signed int k = ~a & ~b; Any help? A: Assuming 16-bit integers for convenience (the principle doesn't change for 32 or 64 bit): a = 0xff = 0000 0000 1111 1111 ~a = -256 = 1111 1111 0000 0000 b = 1<<8 = 0000 0001 0000 0000 ~b = -257 = 1111 1110 1111 1111 -256 = 1111 1111 0000 0000 -257 = 1111 1110 1111 1111 -------------------------- & -512 = 1111 1110 0000 0000
signed bitwise arithmetic in Python
I got stuck with the following Python code >>> a = 0xff >>> b = 1 << 8 >>> ~a & ~b -512 Why is it -512? In binary notation it should look like this: a 0 1111 1111 -> 255 b 01 0000 0000 -> 256 ~a 1 0000 0000 -> -256 ~b 10 1111 1111 -> -257 ~a&~b 00 0000 0000 -> 0 I expected 0 as with signed int in C: signed int a = 0xff; signed int b = 1 << 8; signed int k = ~a & ~b; Any help?
[ "Assuming 16-bit integers for convenience (the principle doesn't change for 32 or 64 bit):\na = 0xff = 0000 0000 1111 1111\n~a = -256 = 1111 1111 0000 0000\n\nb = 1<<8 = 0000 0001 0000 0000\n~b = -257 = 1111 1110 1111 1111\n\n-256 = 1111 1111 0000 0000\n-257 = 1111 1110 1111 1111\n-------------------------- &\n-...
[ 4 ]
[]
[]
[ "bit_manipulation", "math", "python" ]
stackoverflow_0004041170_bit_manipulation_math_python.txt
Q: A question about Django and Google Apps Just wondering about this, is it possible to use Django with the Google Apps API's? I have a small organization that uses Google Apps Education Edition. I was thinking about making a small intranet using Django, and I would love if the first page they saw when they logged in had a few widgets with their email, calendar, maybe docs. I looked over some of the api's, and it seemed that getting the data was possible using the gdata library; but when I looked into using Django, all the search results returned pages about running Django on the app engine, nothing about Google Apps. Just looking for a little guidance, if anyone knew a page or a tutorial where someone had done this. Thanks! A: Yes, it is possible. This is not a question about Django and GAE in particular; you may have more luck searching for tutorials on using Django with generic web APIs. Here's one I found almost immediately; it uses the del.icio.us API but the idea is the same. A: Yes, it is. See this help topic.
A question about Django and Google Apps
Just wondering about this, is it possible to use Django with the Google Apps API's? I have a small organization that uses Google Apps Education Edition. I was thinking about making a small intranet using Django, and I would love if the first page they saw when they logged in had a few widgets with their email, calendar, maybe docs. I looked over some of the api's, and it seemed that getting the data was possible using the gdata library; but when I looked into using Django, all the search results returned pages about running Django on the app engine, nothing about Google Apps. Just looking for a little guidance, if anyone knew a page or a tutorial where someone had done this. Thanks!
[ "Yes, it is possible. This is not a question about Django and GAE in particular; you may have more luck searching for tutorials on using Django with generic web APIs.\nHere's one I found almost immediately; it uses the del.icio.us API but the idea is the same.\n", "Yes, it is. See this help topic.\n" ]
[ 0, 0 ]
[]
[]
[ "django", "google_apps", "python" ]
stackoverflow_0004036321_django_google_apps_python.txt
Q: BeautifulSoup is too slow. Can lxml do this? I've got the following BeautifulSoup code, a bit simplified. soup = BeautifulSoup(html) for item in soup.findAll('div',id=compile('^result_')): q = item.find('a',{'class':'title'}) if q: ... q = item.find('div',{'class':['one','two']}) if q: ... I profiled it, and it's quite slow. I want to try lxml instead but it seems to be a bit unintuitive, compared to BeautifulSoup at least, and I'm not sure it can handle more complex cases. Can the above code be converted to libxml? I don't want code, just confirmation will do. Thanks. A: Since lxml supports XPath, I would argue: yes, this is definitely possible.
BeautifulSoup is too slow. Can lxml do this?
I've got the following BeautifulSoup code, a bit simplified. soup = BeautifulSoup(html) for item in soup.findAll('div',id=compile('^result_')): q = item.find('a',{'class':'title'}) if q: ... q = item.find('div',{'class':['one','two']}) if q: ... I profiled it, and it's quite slow. I want to try lxml instead but it seems to be a bit unintuitive, compared to BeautifulSoup at least, and I'm not sure it can handle more complex cases. Can the above code be converted to libxml? I don't want code, just confirmation will do. Thanks.
[ "Since lxml supports XPath, I would argue: yes, this is definitely possible.\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "lxml", "python" ]
stackoverflow_0004041404_beautifulsoup_lxml_python.txt
Q: Python verify url goes to a page I have a list of urls (1000+) which have been stored for over a year now. I want to run through and verify them all to see if they still exist. What is the best / quickest way to check them all and return a list of ones which do not return a site? A: this is kind of slow but you can use something like this to check if url is a live import urllib2 try: urllib2.urlopen(url) return True # URL Exist except ValueError, ex: return False # URL not well formatted except urllib2.URLError, ex: return False # URL don't seem to be alive more quick than urllib2 you can use httplib import httplib try: a = httplib.HTTPConnection('google.com') a.connect() except httplib.HTTPException as ex: print "not connected" you can also do a DNS checkout (it's not very convenient to check if a website don't exist): import socket try: socket.gethostbyname('www.google.com') except socket.gaierror as ex: print "not existe" A: Check this: Ping in python End then: import ping, socket try: result = ping.do_one('http://stackoverflow.com/', timeout=2) except socket.error, e: # url cannot be reached print "Error:", e
Python verify url goes to a page
I have a list of urls (1000+) which have been stored for over a year now. I want to run through and verify them all to see if they still exist. What is the best / quickest way to check them all and return a list of ones which do not return a site?
[ "this is kind of slow but you can use something like this to check if url is a live\nimport urllib2\n\ntry:\n urllib2.urlopen(url)\n return True # URL Exist\nexcept ValueError, ex:\n return False # URL not well formatted\nexcept urllib2.URLError, ex:\n return False # URL don't seem...
[ 11, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004041443_python.txt
Q: Cython problem in Windows XP: "error: Unable to find vcvarsall.bat" Cython version is 0.13, Python 3.1 I have tried all "solutions" in Cython FAQ, but to no avail. My version of Visual Studio is 7.1 and its directory doesn't contain vcvarsall.bat. Is this problem have a solution? A: SO search and you will find ample discussion on this. https://stackoverflow.com/search?q=vcvarsall.bat [Edit: based on comment below] When you run setup.py install on windows, distutils looks for vcvarsall.bat to run. About vcvarsall.bat VCVarsall.bat is Visual Studio Command Prompt tool in Visual Studio. It allows you to set various options for the integrated development environment (IDE) as well as build, debug, and deploy projects from the command line. What if it does not find this file Solution 1: Hunt the file distutils has an hardcoded path to vcvarsall.bat. find the file starting with vc*.bat or vc*.cmd. The file which sets up command line environment for MS compiler tool chain. The location is inconsistent for different versions of visual studio setup. If you are running 32 bit version then you should be able to find vcvars32.bat. drop it in the directory distutils expect it to be.
Cython problem in Windows XP: "error: Unable to find vcvarsall.bat"
Cython version is 0.13, Python 3.1 I have tried all "solutions" in Cython FAQ, but to no avail. My version of Visual Studio is 7.1 and its directory doesn't contain vcvarsall.bat. Is this problem have a solution?
[ "SO search and you will find ample discussion on this.\n\nhttps://stackoverflow.com/search?q=vcvarsall.bat\n\n[Edit: based on comment below]\nWhen you run setup.py install on windows, distutils looks for vcvarsall.bat to run.\nAbout vcvarsall.bat\nVCVarsall.bat is Visual Studio Command Prompt tool in Visual Studio....
[ 2 ]
[]
[]
[ "cython", "mingw", "python" ]
stackoverflow_0004041607_cython_mingw_python.txt
Q: Why use def main()? I've seen some code samples and tutorials that use def main(): # my code here if __name__ == "__main__": main() But why? Is there any reason not do define your functions at the top of the file, then just write code under it? ie def my_function() # my code here def my_function_two() # my code here # some code # call function # print(something) I just wonder if there is any rhyme to the main? A: Without the main sentinel, the code would be executed even if the script were imported as a module. A: Everyone else has already answered it, but I think I still have something else to add. Reasons to have that if statement calling main() (in no particular order): Other languages (like C and Java) have a main() function that is called when the program is executed. Using this if, we can make Python behave like them, which feels more familiar for many people. Code will be cleaner, easier to read, and better organized. (yeah, I know this is subjective) It will be possible to import that python code as a module without nasty side-effects. This means it will be possible to run tests against that code. This means we can import that code into an interactive python shell and test/debug/run it. Variables inside def main are local, while those outside it are global. This may introduce a few bugs and unexpected behaviors. But, you are not required to write a main() function and call it inside an if statement. I myself usually start writing small throwaway scripts without any kind of function. If the script grows big enough, or if I feel putting all that code inside a function will benefit me, then I refactor the code and do it. This also happens when I write bash scripts. Even if you put code inside the main function, you are not required to write it exactly like that. A neat variation could be: import sys def main(argv): # My code here pass if __name__ == "__main__": main(sys.argv) This means you can call main() from other scripts (or interactive shell) passing custom parameters. This might be useful in unit tests, or when batch-processing. But remember that the code above will require parsing of argv, thus maybe it would be better to use a different call that pass parameters already parsed. In an object-oriented application I've written, the code looked like this: class MyApplication(something): # My code here if __name__ == "__main__": app = MyApplication() app.run() So, feel free to write the code that better suits you. :) A: if the content of foo.py print __name__ if __name__ == '__main__': print 'XXXX' A file foo.py can be used in two ways. imported in another file : import foo In this case __name__ is foo, the code section does not get executed and does not print XXXX. executed directly : python foo.py When it is executed directly, __name__ is same as __main__ and the code in that section is executed and prints XXXX One of the use of this functionality to write various kind of unit tests within the same module. A: "What does if __name__==“__main__”: do?" has already been answered. Having a main() function allows you to call its functionality if you import the module. The main (no pun intended) benefit of this (IMHO) is that you can unit test it. A: Consider the second script. If you import it in another one, the instructions, as at "global level", will be executed.
Why use def main()?
I've seen some code samples and tutorials that use def main(): # my code here if __name__ == "__main__": main() But why? Is there any reason not do define your functions at the top of the file, then just write code under it? ie def my_function() # my code here def my_function_two() # my code here # some code # call function # print(something) I just wonder if there is any rhyme to the main?
[ "Without the main sentinel, the code would be executed even if the script were imported as a module.\n", "Everyone else has already answered it, but I think I still have something else to add.\nReasons to have that if statement calling main() (in no particular order):\n\nOther languages (like C and Java) have a m...
[ 668, 265, 93, 23, 8 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0004041238_coding_style_python.txt
Q: Auto increment of Concatenated alpha-numeric. (Python) I have defined a function that generates ID. I need to increment the numbers every time I call the function. So I used max() function to find the last largest value stored in the list. According to the requirements my ID should also consist of a string in front of the integers. So I have concatenated a string with some numbers which have been stored in a list. Now my max() does not work,because after concatenating its converted into a alpha-numeric.Please help.I tried splitting the ID but that splits each character. Following is the function I defined: #!/usr/bin/python from DB import * def Sid(): idlist = [] for key in Accounts: if Accounts[key]['Acctype'] == 'Savings': idlist.append(Accounts[key]['Accno']) if len(idlist) == 0: return 1001 else: abc = max(idlist) return abc + 1 EDIT 1: Here is how I have called the function: accno = Sid() AppendRecord(Accno="SA"+str(accno)) A: You can strip off the numeric suffix from the string to get a number to increment: import re def number_suffix(s): """Return the number from the end of the string. """ match = re.search(r"\d+$", s) if match: num = int(match.group(0)) else: num = 0 return num print number_suffix("AS1001") # 1001 print number_suffix("AS1") # 1 print number_suffix("AS") # 0 then change your function: idlist.append(number_suffix(Accounts[key]['Accno']))
Auto increment of Concatenated alpha-numeric. (Python)
I have defined a function that generates ID. I need to increment the numbers every time I call the function. So I used max() function to find the last largest value stored in the list. According to the requirements my ID should also consist of a string in front of the integers. So I have concatenated a string with some numbers which have been stored in a list. Now my max() does not work,because after concatenating its converted into a alpha-numeric.Please help.I tried splitting the ID but that splits each character. Following is the function I defined: #!/usr/bin/python from DB import * def Sid(): idlist = [] for key in Accounts: if Accounts[key]['Acctype'] == 'Savings': idlist.append(Accounts[key]['Accno']) if len(idlist) == 0: return 1001 else: abc = max(idlist) return abc + 1 EDIT 1: Here is how I have called the function: accno = Sid() AppendRecord(Accno="SA"+str(accno))
[ "You can strip off the numeric suffix from the string to get a number to increment:\nimport re\n\ndef number_suffix(s):\n \"\"\"Return the number from the end of the string. \"\"\"\n match = re.search(r\"\\d+$\", s)\n if match:\n num = int(match.group(0))\n else:\n num = 0\n return num\...
[ 2 ]
[]
[]
[ "auto_increment", "python" ]
stackoverflow_0004041623_auto_increment_python.txt
Q: Django: If I added new tables to database, how can I query them? Django: If I added new tables to database, how can I query them? Do I need to create the relevant models first? Or django creates it by itself? More specifically, I installed another django app, it created several database tables in database, and now I want to get some specific data from them? What are the correct approaches? Thank you very much! A: I suppose another django app has all model files needed to access those tables, you should just try importing those packages and use this app's models. A: Django doen't follow convention over configuration philosophy. you have to explicitly create the backing model for the table and in the meta tell it about the table name...
Django: If I added new tables to database, how can I query them?
Django: If I added new tables to database, how can I query them? Do I need to create the relevant models first? Or django creates it by itself? More specifically, I installed another django app, it created several database tables in database, and now I want to get some specific data from them? What are the correct approaches? Thank you very much!
[ "I suppose another django app has all model files needed to access those tables, you should just try importing those packages and use this app's models.\n", "Django doen't follow convention over configuration philosophy. you have to explicitly create the backing model for the table and in the meta tell it about ...
[ 1, 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0004042286_django_django_admin_django_models_python.txt
Q: Django : ORM objects come with nothing in _meta.local_fields [python 2.6 - django 1.1.1] Hello. I'm writing a custom serializer for my django application. All the objects that I use are proxy objects derived from django model classes and implement special members that I must serialize (hence the custom serializer). So I've begun to implement a new abstract serializer that inherits django.core.serialiazer.base.Serializer and redifines the serialize(...) method. I've also begun a python concrete serializer (child-class of my own base Serializer), needed for custom construction of the dict. Problem is, when my queryset comes into the serialize() method, each individual obj in it has an empty list ([]) for obj._meta.local_fields. As a consequence, my serialized python dicts are almost empty (apart from primary key & model), because I rely on this list. I can't seem to find where this field is inited. I don't understand, also, why _meta.local_fields is inconsistent when I use my serializer and not when I use django's serializer (i pass the same querysets of proxy objects). Thanks. EDIT: i thought maybe some __init__ code somewhere in the django packages had an effect, but I can't find anything in that direction, either. A: It seems that proxy objects don't have local_fields set, which would be logical. I've just found something in the existing code (exploiting the django python serializer) that works around the lack of local_fields... I think my question is void :-/
Django : ORM objects come with nothing in _meta.local_fields
[python 2.6 - django 1.1.1] Hello. I'm writing a custom serializer for my django application. All the objects that I use are proxy objects derived from django model classes and implement special members that I must serialize (hence the custom serializer). So I've begun to implement a new abstract serializer that inherits django.core.serialiazer.base.Serializer and redifines the serialize(...) method. I've also begun a python concrete serializer (child-class of my own base Serializer), needed for custom construction of the dict. Problem is, when my queryset comes into the serialize() method, each individual obj in it has an empty list ([]) for obj._meta.local_fields. As a consequence, my serialized python dicts are almost empty (apart from primary key & model), because I rely on this list. I can't seem to find where this field is inited. I don't understand, also, why _meta.local_fields is inconsistent when I use my serializer and not when I use django's serializer (i pass the same querysets of proxy objects). Thanks. EDIT: i thought maybe some __init__ code somewhere in the django packages had an effect, but I can't find anything in that direction, either.
[ "It seems that proxy objects don't have local_fields set, which would be logical. I've just found something in the existing code (exploiting the django python serializer) that works around the lack of local_fields...\nI think my question is void :-/\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004041543_django_python.txt
Q: Why can't nosetests find one the elements in sys.path? I have a series of unit tests that I'm running with nose. For some of my tests, I'd like to remove a module's path from the sys.path so there is no conflict with what I am testing. sys.path.remove('/path/to/remove/from/sys/path') If I run the Python interpreter and call sys.path, the '/path/to/remove/from/sys/path' is there in the list. However, once nosetests is called, the above code cannot find it and gives me a "not found in list" error. Why is nose not able to find the path in sys.path? A: Didn't you mean this? sys.path.remove('/path/to/remove/from/sys/path') If nose can't find it in sys.path then it wasn't there... nose does lots of diddling with sys.path on its own. Why not print sys.path and see what it actually is when run under nose A: Create a script, get_mod_py_path.py, to set the PYTHONPATH. In this case, it is dropping the conflicted path. import os import sys # Remove the global Python modules from the PYTHONPATH. path = os.environ['PYTHONPATH'].split(os.pathsep) if os.environ['GLOB_PY_MODULES'] in path: path.remove(os.environ['GLOB_PY_MODULES']) # Construct the new path and print it. path = ':'.join(path) print path Then use it in a bash that calls nosetests. PYTHONPATH=`python get_mod_py_path.py` nosetests --verbosity=1 --with-gae --where="../tests/unit" --gae-application="../app"
Why can't nosetests find one the elements in sys.path?
I have a series of unit tests that I'm running with nose. For some of my tests, I'd like to remove a module's path from the sys.path so there is no conflict with what I am testing. sys.path.remove('/path/to/remove/from/sys/path') If I run the Python interpreter and call sys.path, the '/path/to/remove/from/sys/path' is there in the list. However, once nosetests is called, the above code cannot find it and gives me a "not found in list" error. Why is nose not able to find the path in sys.path?
[ "Didn't you mean this?\nsys.path.remove('/path/to/remove/from/sys/path')\n\nIf nose can't find it in sys.path then it wasn't there... nose does lots of diddling with sys.path on its own. Why not print sys.path and see what it actually is when run under nose\n", "Create a script, get_mod_py_path.py, to set the P...
[ 1, 0 ]
[]
[]
[ "nose", "nosetests", "python", "pythonpath" ]
stackoverflow_0003947464_nose_nosetests_python_pythonpath.txt
Q: Where does Python root logger store a log? I'm using the Freebase Python library. It creates a log before executing: self.log = logging.getLogger("freebase") Where is this log in the file system? It's not in the executing directory or tmp. A: That call does not store anything. It merely creates a logger object which can be bound and configured however you would like. So if in your Python code, you were to add logging.basicConfig(level=logging.WARNING) All warnings and errors would be logged to the standard output (that's what basicConfig does), including the calls that Freebase makes. If you want to log to the filesystem or other target, you'll want to reference the logging module documentation for more information. You may also wish to reference the Logging HOWTO.
Where does Python root logger store a log?
I'm using the Freebase Python library. It creates a log before executing: self.log = logging.getLogger("freebase") Where is this log in the file system? It's not in the executing directory or tmp.
[ "That call does not store anything. It merely creates a logger object which can be bound and configured however you would like.\nSo if in your Python code, you were to add\nlogging.basicConfig(level=logging.WARNING)\n\nAll warnings and errors would be logged to the standard output (that's what basicConfig does), in...
[ 30 ]
[]
[]
[ "freebase", "logging", "python" ]
stackoverflow_0004042615_freebase_logging_python.txt
Q: How can I return the odd numbers of a list, using only recursion in Python? I do not want to use while or for loops, just want to use recursion to return the odd numbers in a given list. Thanks! A: def find_odds(numbers): if not numbers: return [] if numbers[0] % 2 == 1: return [numbers[0]] + find_odds(numbers[1:]) return find_odds(numbers[1:]) No extra variables or parameters needed. A: def only_odd(L): return L[0:L[0]&1]+only_odd(L[1:]) if L else L This version is much faster as it avoids making copies of L def only_odd_no_copy(L, i=0): return L[i:i+(L[i]&1)]+only_odd_no_copy(L, i+1) if i<len(L) else [] This one only uses O(log n) stack space def only_odd_logn(L): x=len(L)/2+1 return L[:L[0]&1] + only_odd2(L[1:x]) + only_odd_logn(L[x:]) if L else L A: def find_odds(numbers, odds): if len(numbers) == 0: return v = numbers.pop() if v % 2 == 1: odds.append(v) find_odds(numbers, odds) odds = [] numbers = [1,2,3,4,5,6,7] find_odds(numbers,odds) # Now odds has the odd numbers print odds Here's a test output of what I get when I run this [7, 5, 3, 1] A: Considering the default stack depth limit of 1000 in python, I would really not use recursion for this. I know there are a lot of recursive implementations above so here's a non-recursive one that is doing it the python way: print filter(lambda x: x % 2, range(0, 10)) And for the sake of completeness; if you really really must use recursion here's my go at it. This is very similar to the version by Josh Matthews. def rec_foo(list): if not list: return [] return ([list[0]] if list[0] % 2 else []) + rec_foo(list[1:]) print rec_foo(range(1, 10)) A: Here's another way of doing it which returns the list of odd numbers rather than modifying the list passed in. Very similar to that provided by GWW but I thought I'd add it for completeness. def find_odds(numbers, odds): if len(numbers) == 0: return odds if numbers[0] % 2 == 1: odds.append(numbers[0]) return find_odds(numbers[1:],odds) print find_odds([1,2,3,4,5,6,7,8,9],[]) Output is: [1, 3, 5, 7, 9] A: Since it's a party, I just thought I'd chime in with a nice, sensible, Real ProgrammerTM solution. It's written in emacs and inspired by gnibbler's answer. Like his, it uses &1 instead of % 2 (adding 2 into co_consts is pure decadence if 1 is already there) and uses that nifty trick for getting the first element only if it's odd, but shaves some cycles off for a time savings of around 5% (on my machine, running 2.6.5 compiled with GCC 4.4.3 on a linux2 kernel). from opcode import opmap import types opcodes = [opmap['LOAD_FAST'], 0,0, # L opmap['JUMP_IF_FALSE'], 24,0, opmap['DUP_TOP'], opmap['LOAD_CONST'], 0,0, # 0 opmap['BINARY_SUBSCR'], opmap['LOAD_CONST'], 1,0, # 1 opmap['BINARY_AND'], opmap['SLICE+2'], opmap['LOAD_GLOBAL'], 0,0, # odds opmap['LOAD_FAST'], 0,0, opmap['LOAD_CONST'], 1,0, opmap['SLICE+1'], opmap['CALL_FUNCTION'], 1,0, opmap['BINARY_ADD'], opmap['RETURN_VALUE']] code_str = ''.join(chr(byte) for byte in opcodes) code = types.CodeType(1, 1, 4, 0x1 | 0x2 | 0x40, code_str, (0, 1), ('odds',), ('L',), '<nowhere>', 'odds', 0, '') odds = types.FunctionType(code, globals()) A: odds = [] def findOdds(listOfNumbers): if listOfNumbers[0] % 2 == 1: odds.append(listOfNumbers[0]) if len(listOfNumbers) > 1: findOdds(listOfNumbers[1:]) findOdds(range(0,10)) print odds # returns [1,3,5,7,9] A: >>> def fodds(alist, odds=None): ... if odds is None: odds = [] ... if not alist: return odds ... x = alist[0] # doesn't destroy the input sequence ... if x % 2: odds.append(x) ... return fodds(alist[1:], odds) ... >>> fodds(range(10)) # only one arg needs to be supplied [1, 3, 5, 7, 9] # same order as input >>> This one avoids the list copying overhead, at the cost of getting the answer backwards and a big increase in the ugliness factor: >>> def fo(aseq, pos=None, odds=None): ... if odds is None: odds = [] ... if pos is None: pos = len(aseq) - 1 ... if pos < 0: return odds ... x = aseq[pos] ... if x % 2: odds.append(x) ... return fo(aseq, pos - 1, odds) ... >>> fo(range(10)) [9, 7, 5, 3, 1] >>> A: def odds(L): if L == []: return [] else: if L[0]%2: B = odds(L[1:]) B.append(L[0]) return B else: return odds(L[1:]) A: Well, there are a bunch of other answers but I think mine's the cleanest: def odds(L): if not L: return [] return [L[0]] * (L[0] % 2) + odds(L[1:]) Fun exercise but just to reiterate, don't ever do this recursively in practice. A: well since we're all contributing: def odds(aList): from operator import lshift as l if aList and not aList[1:]: return aList if aList[-1] - l(aList[0]>>1, 1) else list() return odds(aList[:len(aList)/3+1]) + odds(aList \ [len(aList)/3+1:]) if aList else []
How can I return the odd numbers of a list, using only recursion in Python?
I do not want to use while or for loops, just want to use recursion to return the odd numbers in a given list. Thanks!
[ "def find_odds(numbers):\n if not numbers:\n return []\n if numbers[0] % 2 == 1:\n return [numbers[0]] + find_odds(numbers[1:])\n return find_odds(numbers[1:])\n\nNo extra variables or parameters needed.\n", "def only_odd(L):\n return L[0:L[0]&1]+only_odd(L[1:]) if L else L\n\nThis version is much fas...
[ 11, 7, 3, 3, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0004039374_python_recursion.txt
Q: How can I get title & scripts inside a webpage using webkit + gtk? Here 's my code snippet import gtk, webkit window = gtk.Window() browser = webkit.WebView() url = "www.google.com" browser.open(url) Now I wanna get the web page title, script tags inside. So how can I do that ? The documentation is not clear at these points and I only found documentation for Objective-C and I am trying to find my way there. Please if you know where can I get a better reference not necessarily for Python. C, C++ would be fine also. Thanks A: I think the following should work (I can't try it out right now): def title_changed(widget, frame, title): print title browser.connect('title-changed', title_changed) There is some documentation here and here and two examples in the demo directory from the source tarball. A: It is not bound to the technology used to retrieve the html. Once browser has opened it, just parse the html with beautiful soup or anything that supports XPath for example.
How can I get title & scripts inside a webpage using webkit + gtk?
Here 's my code snippet import gtk, webkit window = gtk.Window() browser = webkit.WebView() url = "www.google.com" browser.open(url) Now I wanna get the web page title, script tags inside. So how can I do that ? The documentation is not clear at these points and I only found documentation for Objective-C and I am trying to find my way there. Please if you know where can I get a better reference not necessarily for Python. C, C++ would be fine also. Thanks
[ "I think the following should work (I can't try it out right now):\ndef title_changed(widget, frame, title):\n print title\n\nbrowser.connect('title-changed', title_changed)\n\nThere is some documentation here and here and two examples in the demo directory from the source tarball.\n", "It is not bound to the ...
[ 1, 0 ]
[]
[]
[ "gtk", "python", "webkit" ]
stackoverflow_0004038739_gtk_python_webkit.txt
Q: Python equivalent to C#'s using statement Possible Duplicate: What is the equivalent of the C# “using” block in IronPython? I'm writing some IronPython using some disposable .NET objects, and wondering whether there is a nice "pythonic" way of doing this. Currently I have a bunch of finally statements (and I suppose there should be checks for None in each of them too - or will the variable not even exist if the constructor fails?) def Save(self): filename = "record.txt" data = "{0}:{1}".format(self.Level,self.Name) isf = IsolatedStorageFile.GetUserStoreForApplication() try: isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf) try: sw = StreamWriter(isfs) try: sw.Write(data) finally: sw.Dispose() finally: isfs.Dispose() finally: isf.Dispose() A: Python 2.6 introduced the with statement, which provides for automatic clean up of objects when they leave the with statement. I don't know if the IronPython libraries support it, but it would be a natural fit. Dup question with authoritative answer: What is the equivalent of the C# "using" block in IronPython? A: I think you are looking for the with statement. More info here. A: If I understand correctly, it looks like the equivalent is the with statement. If your classes define context managers, they will be called automatically after the with block. A: Your code with some comments : def Save(self): filename = "record.txt" data = "{0}:{1}".format(self.Level,self.Name) isf = IsolatedStorageFile.GetUserStoreForApplication() try: isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf) try: # These try is useless.... sw = StreamWriter(isfs) try: sw.Write(data) finally: sw.Dispose() finally: # Because next finally statement (isfs.Dispose) will be always executed isfs.Dispose() finally: isf.Dispose() For StreamWrite, you can use a with statment (if your object as __enter__ and _exit__ methods) then your code will looks like : def Save(self): filename = "record.txt" data = "{0}:{1}".format(self.Level,self.Name) isf = IsolatedStorageFile.GetUserStoreForApplication() try: isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf) with StreamWriter(isfs) as sw: sw.Write(data) finally: isf.Dispose() and StreamWriter in his __exit__ method has sw.Dispose()
Python equivalent to C#'s using statement
Possible Duplicate: What is the equivalent of the C# “using” block in IronPython? I'm writing some IronPython using some disposable .NET objects, and wondering whether there is a nice "pythonic" way of doing this. Currently I have a bunch of finally statements (and I suppose there should be checks for None in each of them too - or will the variable not even exist if the constructor fails?) def Save(self): filename = "record.txt" data = "{0}:{1}".format(self.Level,self.Name) isf = IsolatedStorageFile.GetUserStoreForApplication() try: isfs = IsolatedStorageFileStream(filename, FileMode.Create, isf) try: sw = StreamWriter(isfs) try: sw.Write(data) finally: sw.Dispose() finally: isfs.Dispose() finally: isf.Dispose()
[ "Python 2.6 introduced the with statement, which provides for automatic clean up of objects when they leave the with statement. I don't know if the IronPython libraries support it, but it would be a natural fit.\nDup question with authoritative answer: What is the equivalent of the C# \"using\" block in IronPython...
[ 9, 2, 0, 0 ]
[]
[]
[ "ironpython", "python", "using" ]
stackoverflow_0004042995_ironpython_python_using.txt
Q: How to interrupt python multithreaded app? I'm trying to run the following code (it i simplified a bit): def RunTests(self): from threading import Thread import signal global keep_running keep_running = True signal.signal( signal.SIGINT, stop_running ) for i in range(0, NumThreads): thread = Thread(target = foo) self._threads.append(thread) thread.start() # wait for all threads to finish for t in self._threads: t.join() def stop_running(signl, frme): global keep_testing keep_testing = False print "Interrupted by the Master. Good by!" return 0 def foo(self): global keep_testing while keep_testing: DO_SOME_WORK(); I expect that the user presses Ctrl+C the program will print the good by message and interrupt. However it doesn't work. Where is the problem? Thanks A: Unlike regular processes, Python doesn't appear to handle signals in a truly asynchronous manner. The 'join()' call is somehow blocking the main thread in a manner that prevents it from responding to the signal. I'm a bit surprised by this since I don't see anything in the documentation indicating that this can/should happen. The solution, however, is simple. In your main thread, add the following loop prior to calling 'join()' on the threads: while keep_testing: signal.pause() A: From the threading docs: A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property. You could try setting thread.daemon = True before calling start() and see if that solves your problem.
How to interrupt python multithreaded app?
I'm trying to run the following code (it i simplified a bit): def RunTests(self): from threading import Thread import signal global keep_running keep_running = True signal.signal( signal.SIGINT, stop_running ) for i in range(0, NumThreads): thread = Thread(target = foo) self._threads.append(thread) thread.start() # wait for all threads to finish for t in self._threads: t.join() def stop_running(signl, frme): global keep_testing keep_testing = False print "Interrupted by the Master. Good by!" return 0 def foo(self): global keep_testing while keep_testing: DO_SOME_WORK(); I expect that the user presses Ctrl+C the program will print the good by message and interrupt. However it doesn't work. Where is the problem? Thanks
[ "Unlike regular processes, Python doesn't appear to handle signals in a truly asynchronous manner. The 'join()' call is somehow blocking the main thread in a manner that prevents it from responding to the signal. I'm a bit surprised by this since I don't see anything in the documentation indicating that this can/sh...
[ 3, 0 ]
[]
[]
[ "multithreading", "python", "signals" ]
stackoverflow_0004042158_multithreading_python_signals.txt
Q: Tkinter window events and properties I've been searching for information on the following Tkinter window features without success. Platform is Windows, Python 2.7. At the end of this post is code that can be used to explore Tkinter window events. How can one detect window minimize/maximize events? The event object returned by binding to a window's <Configure> event does contain any information about these events. I've searched for protocols (like WM_DELETE_WINDOW) that might expose these events without success. How can one determine window frame border sizes (not Tkinter frames, the frame the OS places around the container where Tkinter places its widgets)? Is there a non-platform specific way to discover these windows properties or do I need to use platform specific solutions like the win32 api under Windows? How can one determine a window's visibility, eg. whether a window is invisible or not as set by .withdraw()? Is it possible to cancel a window event, eg. if one wanted to constrain a window to a certain location on a user's desktop? Returning 'break' from a window's <Configure> event does not cancel window move or resize events. Here's sample code for experimenting with Tkinter window events. from __future__ import print_function try: import Tkinter as tk except ImportError: import tkinter as tk def onFormEvent(event): for key in dir(event): if not key.startswith('_'): print('%s=%s' % (key, getattr(event, key))) print() root = tk.Tk() root.geometry('150x50') lblText = tk.Label(root, text='Form event tester') lblText.pack() root.bind('<Configure>', onFormEvent) root.mainloop() Updat:e Here's what I learned about the following events: event.type == 22 (one or more of following changed: width, height, x, y) event.type == 18 (minimized) event.widget.winfo_viewable() = 0 (invisible) event.type == 19 (restore after minimized) event.type == 2 (maximize) event.type == 22 (restore after maximized due to change in width and height) A: Determining window visibility is done with a .winfo_viewable() call. Returns 1 if visible, 0 if not. If you want to prevent the window from resizing, set up your window the way you want, then use self.root.minsize(self.root.winfo_reqwidth(), self.root.winfo_reqheight()) self.root.maxsize(self.root.winfo_reqwidth(), self.root.winfo_reqheight()) at the end of your __init__ call. To completely disable the window from being moved, then you probably just want to remove the title bar and frame with self.root.overrideredirect(True).
Tkinter window events and properties
I've been searching for information on the following Tkinter window features without success. Platform is Windows, Python 2.7. At the end of this post is code that can be used to explore Tkinter window events. How can one detect window minimize/maximize events? The event object returned by binding to a window's <Configure> event does contain any information about these events. I've searched for protocols (like WM_DELETE_WINDOW) that might expose these events without success. How can one determine window frame border sizes (not Tkinter frames, the frame the OS places around the container where Tkinter places its widgets)? Is there a non-platform specific way to discover these windows properties or do I need to use platform specific solutions like the win32 api under Windows? How can one determine a window's visibility, eg. whether a window is invisible or not as set by .withdraw()? Is it possible to cancel a window event, eg. if one wanted to constrain a window to a certain location on a user's desktop? Returning 'break' from a window's <Configure> event does not cancel window move or resize events. Here's sample code for experimenting with Tkinter window events. from __future__ import print_function try: import Tkinter as tk except ImportError: import tkinter as tk def onFormEvent(event): for key in dir(event): if not key.startswith('_'): print('%s=%s' % (key, getattr(event, key))) print() root = tk.Tk() root.geometry('150x50') lblText = tk.Label(root, text='Form event tester') lblText.pack() root.bind('<Configure>', onFormEvent) root.mainloop() Updat:e Here's what I learned about the following events: event.type == 22 (one or more of following changed: width, height, x, y) event.type == 18 (minimized) event.widget.winfo_viewable() = 0 (invisible) event.type == 19 (restore after minimized) event.type == 2 (maximize) event.type == 22 (restore after maximized due to change in width and height)
[ "Determining window visibility is done with a .winfo_viewable() call. Returns 1 if visible, 0 if not.\nIf you want to prevent the window from resizing, set up your window the way you want, then use\nself.root.minsize(self.root.winfo_reqwidth(), self.root.winfo_reqheight())\nself.root.maxsize(self.root.winfo_reqwidt...
[ 2 ]
[]
[]
[ "python", "tkinter", "user_interface", "windows" ]
stackoverflow_0004038070_python_tkinter_user_interface_windows.txt
Q: Using Python to convert color formats? I'm working on a Python tool to convert image data into these color formats: RGB565 RGBA5551 RGBA4444. What's the simplest way to achieve this? I've used the Python Imaging Library (PIL) frequently. So I know how to load an image and obtain each pixel value in RGBA8888 format. And I know how to write all the conversion code manually from that point. Is there an easier way? Perhaps some type of 'formatter' plugin for PIL? Does PIL already support some of the formats I'm targeting? I can't ever figure out which formats PIL really supports without digging though all of the source code. Or is there a better library than PIL to accomplish this in Python? Any tips would be appreciated. Thanks! A: Changing something from 8 to 5 bits is trivial. In 8 bits the value is between 0 and 255, in 5 bits it's between 0 and 31, so all you need to do is divide the value with 8. Or 4 in the case for green in RGB565 mode. Or 16 in RGBA4444 mode as it uses 4 bits per channel, etc. Edit: Reading through your question again, I think there is a confusion (either with me or you). RGB555 and RGBA4444 etc are not really formats, like GIF or JPG, they are color spaces. That conversion is trivial (see above). What file format you want to save it in later is another question. Most file formats have limited support for color spaces. I think for example that JPEG always saves it in YCbCr (but I could be mistaken), GIF uses a palette (which in turn always is RGB888, I think) etc. A: There's a module called Python Colormath which provides a lot of different conversions. Highly recommended. A: Numpy is powerful indeed, but to get there and back to PIL requires two memory copies. Have you tried something along the following lines? im = Image.open('yourimage.png') im.putdata([yourfunction(r,g,b) for (r,g,b) in im.getdata()]) This is quite fast (especially when you can use a lookup table). I am not familiar with the colour spaces you mention, but as I understand you know the conversion so implementation of yourfunction(r,g,b) should be straight forward. Also im.convert('RGBA', matrix) might be very powerful as it is super fast in applying a colour transformation through the supplied matrix. However I have never gotten that to do what I wanted it to do... :-/ A: There is also a module named Grapefruit that let you do conversions between quite a lot of color formats. A: I ended up doing the conversions manually as Lennart Regebro suggested. However, pure Python (iterating over each pixel) turned out to be too slow. My final solution used PIL to load the image and numpy to operate on (convert) an array of pixels.
Using Python to convert color formats?
I'm working on a Python tool to convert image data into these color formats: RGB565 RGBA5551 RGBA4444. What's the simplest way to achieve this? I've used the Python Imaging Library (PIL) frequently. So I know how to load an image and obtain each pixel value in RGBA8888 format. And I know how to write all the conversion code manually from that point. Is there an easier way? Perhaps some type of 'formatter' plugin for PIL? Does PIL already support some of the formats I'm targeting? I can't ever figure out which formats PIL really supports without digging though all of the source code. Or is there a better library than PIL to accomplish this in Python? Any tips would be appreciated. Thanks!
[ "Changing something from 8 to 5 bits is trivial. In 8 bits the value is between 0 and 255, in 5 bits it's between 0 and 31, so all you need to do is divide the value with 8. Or 4 in the case for green in RGB565 mode. Or 16 in RGBA4444 mode as it uses 4 bits per channel, etc.\nEdit: Reading through your question aga...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001119754_python.txt
Q: Python How to share a serial port with two different threads (Class A, Class B) I have a single Python process which is using a serial port (unique resource) which is managed using an instance of a class A. There exists two different threads initialized using instances of classes B and C, which are constantly using the serial port resource through the objected already created. import threading Class A(threading.Thread): #Zigbee serial port handler def __init__(self,dev): #something here that initialize serial port def run(): while True: #listening serial interface def pack(self): #something def checksum(self): #something def write(self): #something Class B(threading.Thread): def __init__(self,SerialPortHandler): self.serialporthandler=SerialPortHandler def run(self) while True: #something that uses self.serialporthandler Class C(threading.Thread): def __init__(self,SerialPortHandler): self.serialporthandler=SerialPortHandler def run(self) while True: #something that uses self.serialporthandler def main(): a=A('/dev/ttyUSB1') b=B(a) b.start() c=C(a) c.start() if __name__=='main': while True: main() The problem is that both threads are trying to access the serial resource at the same time. I could use several instances of the same class A, attaching Lock.acquire() and Lock.release() in the sensitive parts. Could some of you point me to the right way? Thank you in advance. A: While you could share the serial port using appropriate locking, I wouldn't recommend it. I've written several multi-threaded applications that communicate on the serial port in Python, and in my experience the following approach is better: Have a single class, in a single thread, manage the actual serial port communication, via a Queue object or two: Stuff read from the port is placed into the queue Commands to send to the port are placed into the queue and the "Serial thread" sends them Have the other threads implement logic by placing things into the queue and taking things out Using Queue objects will greatly simplify your code and make it more robust. This approach opens a lot of possibilities for you in terms of design. You can, for example, register events (callbacks) with the serial thread manager and have it call them (in a synchronized way) when interesting events occur, etc. A: Add a threading.Lock() to class A and make it acquire the lock when using it: def __init__(self,dev): self.lock = threading.Lock() def read(self): self.lock.acquire() data = ? #whatever you need to do here to read self.lock.release() return data def write(self, data): self.lock.acquire() #whatever you need to do to write self.lock.release()
Python How to share a serial port with two different threads (Class A, Class B)
I have a single Python process which is using a serial port (unique resource) which is managed using an instance of a class A. There exists two different threads initialized using instances of classes B and C, which are constantly using the serial port resource through the objected already created. import threading Class A(threading.Thread): #Zigbee serial port handler def __init__(self,dev): #something here that initialize serial port def run(): while True: #listening serial interface def pack(self): #something def checksum(self): #something def write(self): #something Class B(threading.Thread): def __init__(self,SerialPortHandler): self.serialporthandler=SerialPortHandler def run(self) while True: #something that uses self.serialporthandler Class C(threading.Thread): def __init__(self,SerialPortHandler): self.serialporthandler=SerialPortHandler def run(self) while True: #something that uses self.serialporthandler def main(): a=A('/dev/ttyUSB1') b=B(a) b.start() c=C(a) c.start() if __name__=='main': while True: main() The problem is that both threads are trying to access the serial resource at the same time. I could use several instances of the same class A, attaching Lock.acquire() and Lock.release() in the sensitive parts. Could some of you point me to the right way? Thank you in advance.
[ "While you could share the serial port using appropriate locking, I wouldn't recommend it. I've written several multi-threaded applications that communicate on the serial port in Python, and in my experience the following approach is better:\n\nHave a single class, in a single thread, manage the actual serial port ...
[ 13, 0 ]
[]
[]
[ "multithreading", "python", "semaphore" ]
stackoverflow_0004043193_multithreading_python_semaphore.txt
Q: How do I write text in subscript in the axis labels and the legend? I have the following axis labels and legend. plt.ylabel("ratio_2") plt.xlabel("n_1") plt.legend(('alpha_1','alpha_2' ), loc = 'best',shadow = True) A: Put dollar signs around the formula: plt.xlabel("$n_1$") A: The easiest way I know is to enable TeX mode for matplotlib, from http://www.scipy.org/Cookbook/Matplotlib/UsingTex: from matplotlib import rc rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']}) rc('text', usetex=True)
How do I write text in subscript in the axis labels and the legend?
I have the following axis labels and legend. plt.ylabel("ratio_2") plt.xlabel("n_1") plt.legend(('alpha_1','alpha_2' ), loc = 'best',shadow = True)
[ "Put dollar signs around the formula: plt.xlabel(\"$n_1$\")\n", "The easiest way I know is to enable TeX mode for matplotlib,\nfrom http://www.scipy.org/Cookbook/Matplotlib/UsingTex:\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})\nrc('text', usetex=True)\n\n" ]
[ 48, 8 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003985827_matplotlib_python.txt
Q: HTML table with writable cells? I've been trying to build a simple GAE app and to be able to manipulate the position of the text on the screen. I asked the same question on several forums; so far with no solution. I apologize if my question has not been clear. Now I thought of achieving the same functionality with a grid, like a spreadsheet. Do you know how I can simulate a spreadsheet-like table in GAE? Or an html table where you can enter a string in each cell? I feel like I am trying to re-invent the wheel. There must be a simple way to achieve this functionality. I would appreciate any suggestions. Here are the links to previous questions: Stackoverflow comp.lang.python Hacker News Hacker News Thank you! A: There is a jquery plugin called UI Table Edit. That may be a good place to start. Dig around for already implemented grid tools or plugins in javascript that have done most of the work for you. I think Yahoo! has released a nice data grid that allows for editing as well. A: What you are looking for is a data grid -- if you're fine with a client-side solution, and you're up for using jQuery then you might try DataTables. Here is an example of datatables with a pair of plugins to simulate a spreadsheet. A: AbsolutePanel and LayoutPanel are part of GWT and allow you to place any element at arbitrary x- and y-coordinates. I recommend some client-side solution like GWT for any serious application where javascript will be available. If you want to solve this with just GAE and no code on the client side, you could use CSS positioning to achieve your effect. Just generate a top: and left: attribute with position:fixed and you can cause the text to appear anywhere. I'm not sure what you mean by "manipulate the position of text," but I don't think a table will be a good solution if you want pixel-level control.
HTML table with writable cells?
I've been trying to build a simple GAE app and to be able to manipulate the position of the text on the screen. I asked the same question on several forums; so far with no solution. I apologize if my question has not been clear. Now I thought of achieving the same functionality with a grid, like a spreadsheet. Do you know how I can simulate a spreadsheet-like table in GAE? Or an html table where you can enter a string in each cell? I feel like I am trying to re-invent the wheel. There must be a simple way to achieve this functionality. I would appreciate any suggestions. Here are the links to previous questions: Stackoverflow comp.lang.python Hacker News Hacker News Thank you!
[ "There is a jquery plugin called UI Table Edit. That may be a good place to start. Dig around for already implemented grid tools or plugins in javascript that have done most of the work for you. I think Yahoo! has released a nice data grid that allows for editing as well.\n", "What you are looking for is a dat...
[ 2, 1, 0 ]
[]
[]
[ "html_table", "nested_lists", "python" ]
stackoverflow_0004043844_html_table_nested_lists_python.txt
Q: python sockets, what's the best way to handle several connections at once? What's the best way to handle lots of connections at once in python? The first way I think of is threading, which works but at 10MB of RAM per thread that's rather expensive. So what other ways are there to handle lots of connections at once ? The only problem I see without using threads is that using the socket.recv() waits for data from that protocolar client so one thread handling several clients wouldn't work. But that's why I'm asking this question, whats the best way to handle several connections? Thank you! A: A good alternative to threads, if you have a truly large amount of simultaneous connections, is an asychronous/events based approach with callbacks. Python already has a very mature and powerful library/framework for this purpose - Twisted. There's also a simpler solution using the standard library asyncore module. From its docs: This module provides the basic infrastructure for writing asynchronous socket service clients and servers. There are only two ways to have a program on a single processor do “more than one thing at a time.” Multi-threaded programming is the simplest and most popular way to do it, but there is another very different technique, that lets you have nearly all the advantages of multi-threading, without actually using multiple threads. It’s really only practical if your program is largely I/O bound. If your program is processor bound, then pre-emptive scheduled threads are probably what you really need. Network servers are rarely processor bound, however. Generally, asynchronous socket servers is a very hot topic lately (node.js hype as a witness), I'm sure you can find a lot of interesting material online.
python sockets, what's the best way to handle several connections at once?
What's the best way to handle lots of connections at once in python? The first way I think of is threading, which works but at 10MB of RAM per thread that's rather expensive. So what other ways are there to handle lots of connections at once ? The only problem I see without using threads is that using the socket.recv() waits for data from that protocolar client so one thread handling several clients wouldn't work. But that's why I'm asking this question, whats the best way to handle several connections? Thank you!
[ "A good alternative to threads, if you have a truly large amount of simultaneous connections, is an asychronous/events based approach with callbacks.\nPython already has a very mature and powerful library/framework for this purpose - Twisted. There's also a simpler solution using the standard library asyncore modul...
[ 5 ]
[]
[]
[ "networking", "python", "sockets" ]
stackoverflow_0004044074_networking_python_sockets.txt
Q: python: too many parameters provided could anyone please explain what's wrong with it ? am I doing something wrong ? >>> class qw: ... def f2x(par1, par2, par3): ... print par1, par2, par3 ... >>> obj = qw() >>> obj.f2x("123", 13, "wert") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f2x() takes exactly 3 arguments (4 given) >>> if I will define just a function it's all working fine >>> def f2x(par1, par2, par3): ... print par1, par2, par3 ... >>> f2x("1", 2, "too many") 1 2 too many >>> A: You forgot that all member functions get another argument implicitly, which in Python is called self by convention. Try: class qw: def f2x(self, par1, par2, par3): print par1, par2, par3 But still call it as before: obj = qw() obj.f2x("123", 13, "wert") In f2x, self is the object on which the member was called. This is a very fundamental concept of Python you should really learn about. A: You need the self parameter in your class' instance method definition: class qw: def f2x(self, par1, par2, par3): print par1, par2, par3 I'd suggest going through a beginner Python book/tutorial. The standard tutorial is good choice, especially if you already have some experience in another language. Then you call it like so: g = qw() g.f2x('1', '2', '3') A: I guess its because of every method of a python class object implicitly has a first paramter which points to the object itself. try def f2x(self, par1, par2, par3): you still call it with your 3 custom parameters >>> class qw: ... def f2x(self, p1, p2, p3): ... print p1,p2,p3 ... >>> o = qw() >>> o.f2x(1,2,3) 1 2 3
python: too many parameters provided
could anyone please explain what's wrong with it ? am I doing something wrong ? >>> class qw: ... def f2x(par1, par2, par3): ... print par1, par2, par3 ... >>> obj = qw() >>> obj.f2x("123", 13, "wert") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f2x() takes exactly 3 arguments (4 given) >>> if I will define just a function it's all working fine >>> def f2x(par1, par2, par3): ... print par1, par2, par3 ... >>> f2x("1", 2, "too many") 1 2 too many >>>
[ "You forgot that all member functions get another argument implicitly, which in Python is called self by convention.\nTry:\nclass qw:\n def f2x(self, par1, par2, par3):\n print par1, par2, par3\n\nBut still call it as before:\nobj = qw()\nobj.f2x(\"123\", 13, \"wert\")\n\nIn f2x, self is the object on which the...
[ 4, 4, 2 ]
[]
[]
[ "class", "parameter_passing", "python" ]
stackoverflow_0004044750_class_parameter_passing_python.txt
Q: Python: Problem with list editing Simplified version of my code: sequence = [['WT_1', 'AAAAAAAA'], ['WT_2', 'BBBBBBB']] def speciate(sequence): lineage_1 = [] lineage_2 = [] for i in sequence: lineage_1.append(i) for k in sequence: lineage_2.append(k) lineage_1[0][0] = 'L1_A' lineage_1[1][0] = 'L1_B' lineage_2[0][0] = 'L2_A' lineage_2[1][0] = 'L2_B' print lineage_1 print lineage_2 speciate(sequence) outputs: [['L2_A', 'AAAAAAAA'], ['L2_B','BBBBBBB']] [['L2_A','AAAAAAAA'], ['L2_B','BBBBBBB']] when I would expect to get this: [['L1_A', 'AAAAAAAA'], ['L1_B','BBBBBBB']] [['L2_A','AAAAAAAA'], ['L2_B','BBBBBBB']] Does anybody know what the problem is? A: You have to make a deep copy (or shallow copy suffices in this case) when you append. Else lineage_1[0][0] and lineage_2[0][0] reference the same object. from copy import deepcopy for i in sequence: lineage_1.append(deepcopy(i)) for k in sequence: lineage_2.append(deepcopy(k)) See also: http://docs.python.org/library/copy.html A: You are appending list objects in your for-loops -- the same list object (sequence[0]). So when you modify the first element of that list: lineage_1[0][0] = 'L1_A' lineage_1[1][0] = 'L1_B' lineage_2[0][0] = 'L2_A' lineage_2[1][0] = 'L2_B' you're seeing it show up as modified in both the lineage_X lists that contain copies of the list that is in sequence[0]. Do something like: import copy for i in sequence: lineage_1.append(copy.copy(i)) for k in sequence: lineage_2.append(copy.copy(k)) this will make copies of the sublists of sequence so that you don't have this aliasing issue. (If the real code has deeper nesting, you can use copy.deepcopy instead of copy.copy.) A: Consider this simple example: >>> aa = [1, 2, 3] >>> bb = aa >>> bb[0] = 999 >>> aa [999, 2, 3] What happened here? "Names" like aa and bb simply reference the list, the same list. Hence when you change the list through bb, aa sees it as well. Using id shows this in action: >>> id(aa) 32343984 >>> id(bb) 32343984 Now, this is exactly what happens in your code: for i in sequence: lineage_1.append(i) for k in sequence: lineage_2.append(k) You append references to the same lists to lineage_1 and lineage_2.
Python: Problem with list editing
Simplified version of my code: sequence = [['WT_1', 'AAAAAAAA'], ['WT_2', 'BBBBBBB']] def speciate(sequence): lineage_1 = [] lineage_2 = [] for i in sequence: lineage_1.append(i) for k in sequence: lineage_2.append(k) lineage_1[0][0] = 'L1_A' lineage_1[1][0] = 'L1_B' lineage_2[0][0] = 'L2_A' lineage_2[1][0] = 'L2_B' print lineage_1 print lineage_2 speciate(sequence) outputs: [['L2_A', 'AAAAAAAA'], ['L2_B','BBBBBBB']] [['L2_A','AAAAAAAA'], ['L2_B','BBBBBBB']] when I would expect to get this: [['L1_A', 'AAAAAAAA'], ['L1_B','BBBBBBB']] [['L2_A','AAAAAAAA'], ['L2_B','BBBBBBB']] Does anybody know what the problem is?
[ "You have to make a deep copy (or shallow copy suffices in this case) when you append. Else lineage_1[0][0] and lineage_2[0][0] reference the same object.\nfrom copy import deepcopy\nfor i in sequence:\n lineage_1.append(deepcopy(i))\nfor k in sequence:\n lineage_2.append(deepcopy(k))\n\nSee also: http://docs.p...
[ 2, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004044783_list_python.txt
Q: Advice on designing django model with "exclusive" foreign key relationships I want to design a Task model that can be associated to Project Models, another X model, and other Task models. The obvious choice is a foreign key, but I want any particular instance of that Task model to only be associated to only one of those model types, that is, if a Task model has a relationship with a Project model, it cannot have a relationship with another Task model, and so on. Any advice in what would be the best way to represent this? Thanks. A: Have a look at Generic relation. It lets you define a foreign key on multiple models. This way your task is only linked to one of your models. A: What I have done is to inherit from a base class on all my models that will be related to tasks. Task models points to that base class on the ForeignKey with unique=True, and it seems like all subclasses inherit the relationship. Thanks.
Advice on designing django model with "exclusive" foreign key relationships
I want to design a Task model that can be associated to Project Models, another X model, and other Task models. The obvious choice is a foreign key, but I want any particular instance of that Task model to only be associated to only one of those model types, that is, if a Task model has a relationship with a Project model, it cannot have a relationship with another Task model, and so on. Any advice in what would be the best way to represent this? Thanks.
[ "Have a look at Generic relation. It lets you define a foreign key on multiple models. This way your task is only linked to one of your models.\n", "What I have done is to inherit from a base class on all my models that will be related to tasks. Task models points to that base class on the ForeignKey with unique=...
[ 0, 0 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0004035298_django_models_python.txt
Q: Python Noob - Silly Question? Works in Python Interpreter, not from CLI I am hoping this is a simple stupid noob mistake that can be fixed with the addition of a single line of code somewhere. I'm using pySerial to read in serial data from a USB port and print it out to standard output. I'm running Mac OSX 10.6. I open terminal and type "python", then the following: >>> import serial; >>> ser = serial.Serial('/dev/tty.usbserial-XXX', 9600, timeout=1); >>> while True: >>> if ser.inWaiting() > 0: >>> ser.readline(); >>> [done, I hit enter...] This works beautifully. It starts outputting my serial data nicely, exactly as I'd expect it to. Great, I think, let me put this into its own script with command line arguments and then I can call it any time I want to: import sys; import serial; serialPort = sys.argv[1] baudRate = sys.argv[2] ser = serial.Serial(serialPort, baudRate, timeout=1) while True: if ser.inWaiting() > 0: ser.readline() On the command line, I type "python myScript.py [my serial port] 9600" and sit back and wait for a beautiful flow of serial data - but nothing comes out. It just kinda hangs until I kill the process. I thought, well maybe for some reason it's not working - so I put some debugging prints into the code. I update my while loop to look like this: while True: print("looping...") print(ser.inWaiting()); if ser.inWaiting() > 0: ser.readline() I run it again, and I get a repeating output stream of "Looping..." and "0". I think, well maybe there's something wrong with my command line arguments - so I hard-coded the port and the baud rate into the script, same thing. So, why would this be the case? Is my use of while True: somehow blocking the script from accepting serial data? Is there a better way to do this? I'm a complete Python noob. I am writing this script in order to create a faster way to communicate between Adobe AIR and an Arduino board. I'm hoping there's a magic bullet I can drop in here to make it work - is there? A: In your 1st example, baud rate is an integer but in the 2nd, you don't not convert sys.argv[2] from a string. Try this ser = serial.Serial(serialPort, int(baudRate), timeout=1). A: Is it printing anything? I'd assume it would print: looping... <ser.inWaiting() val> And then nothing. Add a print statement so it looks like print ser.readline() and see if that works. I'm guessing that the interpreter is printing the returned strings when you do it as a command, but in a script the returned strings from readline() are getting discarded. A: Is my use of while True: somehow blocking the script from accepting serial data? Nope. This is very standard practice and doesn't affect I/O in any way. while True is very much equivalent to while 1 in C. Is there a better way to do this? I'm concerned about your arguments, like others. This should be more reliable overall: from sys import argv from serial import Serial try: baudRate = int(argv[-1]) serialPort = argv[1:-1] except ValueError: #some nice default baudRate = 9600 serialPort = argv[1:] #support paths with spaces. Windows maybe? serialPort = ' '.join(serialPort) if not serialPort: exit("Please specify a serial port") print( "reading from %r@%i ..." % (serialPort, baudRate) ) ser = Serial(serialPort, baudRate, timeout=1) while True: if ser.inWaiting() > 0: print( ser.readline() ) If that doesn't help you, please check that you are using the same interpreter by running these lines in a script and in the CLI. import sys print("Executable: " + sys.executable) print("Version: " + sys.version)
Python Noob - Silly Question? Works in Python Interpreter, not from CLI
I am hoping this is a simple stupid noob mistake that can be fixed with the addition of a single line of code somewhere. I'm using pySerial to read in serial data from a USB port and print it out to standard output. I'm running Mac OSX 10.6. I open terminal and type "python", then the following: >>> import serial; >>> ser = serial.Serial('/dev/tty.usbserial-XXX', 9600, timeout=1); >>> while True: >>> if ser.inWaiting() > 0: >>> ser.readline(); >>> [done, I hit enter...] This works beautifully. It starts outputting my serial data nicely, exactly as I'd expect it to. Great, I think, let me put this into its own script with command line arguments and then I can call it any time I want to: import sys; import serial; serialPort = sys.argv[1] baudRate = sys.argv[2] ser = serial.Serial(serialPort, baudRate, timeout=1) while True: if ser.inWaiting() > 0: ser.readline() On the command line, I type "python myScript.py [my serial port] 9600" and sit back and wait for a beautiful flow of serial data - but nothing comes out. It just kinda hangs until I kill the process. I thought, well maybe for some reason it's not working - so I put some debugging prints into the code. I update my while loop to look like this: while True: print("looping...") print(ser.inWaiting()); if ser.inWaiting() > 0: ser.readline() I run it again, and I get a repeating output stream of "Looping..." and "0". I think, well maybe there's something wrong with my command line arguments - so I hard-coded the port and the baud rate into the script, same thing. So, why would this be the case? Is my use of while True: somehow blocking the script from accepting serial data? Is there a better way to do this? I'm a complete Python noob. I am writing this script in order to create a faster way to communicate between Adobe AIR and an Arduino board. I'm hoping there's a magic bullet I can drop in here to make it work - is there?
[ "In your 1st example, baud rate is an integer but in the 2nd, you don't not convert sys.argv[2] from a string. Try this ser = serial.Serial(serialPort, int(baudRate), timeout=1).\n", "Is it printing anything? I'd assume it would print:\nlooping...\n<ser.inWaiting() val>\n\nAnd then nothing. Add a print statement...
[ 1, 1, 0 ]
[]
[]
[ "command_line", "loops", "python", "serial_port" ]
stackoverflow_0004044293_command_line_loops_python_serial_port.txt
Q: Get the GMT time given date and UTC offset in python I have a date string of the following format '%Y%m%d%H%M%S' for example '19981024103115' and another string of the UTC local offset for example '+0100' What's the best way in python to convert it to the GMT time So the result will be '1998-10-24 09:31:15' A: You could use dateutil for that: >>> from dateutil.parser import parse >>> dt = parse('19981024103115+0100') >>> dt datetime.datetime(1998, 10, 24, 10, 31, 15, tzinfo=tzoffset(None, 3600)) >>> dt.utctimetuple() time.struct_time(tm_year=1998, tm_mon=10, tm_mday=24, tm_hour=9, tm_min=31, tm_sec=15, tm_wday=5, tm_yday=297, tm_isdst=0) A: As long as you know that the time offset will always be in the 4-digit form, this should work. def MakeTime(date_string, offset_string): offset_hours = int(offset_string[0:3]) offset_minutes = int(offset_string[0] + offset_string[3:5]) gmt_adjust = datetime.timedelta(hours = offset_hours, minutes = offset_minutes) gmt_time = datetime.datetime.strptime(date_string, '%Y%m%d%H%M%S') - gmt_adjust return gmt_time
Get the GMT time given date and UTC offset in python
I have a date string of the following format '%Y%m%d%H%M%S' for example '19981024103115' and another string of the UTC local offset for example '+0100' What's the best way in python to convert it to the GMT time So the result will be '1998-10-24 09:31:15'
[ "You could use dateutil for that:\n>>> from dateutil.parser import parse\n>>> dt = parse('19981024103115+0100')\n>>> dt\ndatetime.datetime(1998, 10, 24, 10, 31, 15, tzinfo=tzoffset(None, 3600))\n>>> dt.utctimetuple()\ntime.struct_time(tm_year=1998, tm_mon=10, tm_mday=24, tm_hour=9, tm_min=31, tm_sec=15, tm_wday=5, ...
[ 4, 0 ]
[]
[]
[ "datetime", "gmt", "python", "utc" ]
stackoverflow_0004044863_datetime_gmt_python_utc.txt
Q: Django - Threading in views without hanging the server One of my applications in my Django project require each request/visitor to that instance to have their own thread. This might sound confusing, so I'll describe what I'm looking to accomplish in a case based scenario, with steps: User visits application Thread starts Until the thread finishes, that user's server instance hangs Once the thread completes, a response is delivered to the user Other visitors to the site should not be affected by any other users using the application How can I accomplish something like this? If possible, I'd like to find a lightweight solution. A: But why you need thread? why can't you just do whatever you want to do in django view? If you are using servers like apache with mod-wsgi you should be able to have good control over number of process and threads , so that part shouldn't be your worry or should not be in django views. A: I dread to think why you'd want to do that. Are you sure you're not looking for session variables?
Django - Threading in views without hanging the server
One of my applications in my Django project require each request/visitor to that instance to have their own thread. This might sound confusing, so I'll describe what I'm looking to accomplish in a case based scenario, with steps: User visits application Thread starts Until the thread finishes, that user's server instance hangs Once the thread completes, a response is delivered to the user Other visitors to the site should not be affected by any other users using the application How can I accomplish something like this? If possible, I'd like to find a lightweight solution.
[ "But why you need thread? why can't you just do whatever you want to do in django view?\nIf you are using servers like apache with mod-wsgi you should be able to have good control over number of process and threads , so that part shouldn't be your worry or should not be in django views.\n", "I dread to think why ...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "multithreading", "python" ]
stackoverflow_0002565484_django_django_models_multithreading_python.txt
Q: How do you run a complex sql script within a python program? I have a large SQL script that creates my database (multiple tables, triggers, and such. Using MySQL), and I need to execute that script from within a python program. My old code did this: sql_file = open(os.path.join(self.path_to_sql, filename), 'r') sql_text = sql_file.read() sql_stmts = sql_text.split(';') for s in sql_stmts: cursor.execute(s) This worked fine until I started including triggers in my sql script. Since I now need to change the delimiter from ; to something else, in order to support triggers with multiple SQL statements in each, my code to split each statement into it's own string no longer works because the "delimiter |" line in my script fails to split properly, and I get a syntax error from cursor.execute(s). So, I need some way to tell mysqldb to execute an entire sql script at once, instead of individual sql statements. I tried this: sql_file = open(os.path.join(self.path_to_sql, filename), 'r') sql_text = sql_file.read() cursor.execute(sql_text) However, I get the following error when I try to run that code: ProgrammingError: (2014, "Commands out of sync; you can't run this command now") My Google-fu tells me that this is because the Python mysqldb package doesn't support complex SQL statements being sent to cursor.execute(). So how can I do this? I'd really like to find a way to do this entirely within Python, so that the code will remain entirely portable. We have several programmers working on this project in Eclipse, some on Windows and some on Mac, and the code needs to work on the Linux production server as well. If I can't use Python code to actually run the SQL, how can I tell Python to launch a separate program to execute it? A: (not a python solution) you can use os.system('mysql < etc') ooh, edit (python solution): if you have the query broken up by line, you can close and reopen the cursor and execute by line. redit: sorry, only skimmed your first paragraph. seems like you were doing this sort of thing at first.
How do you run a complex sql script within a python program?
I have a large SQL script that creates my database (multiple tables, triggers, and such. Using MySQL), and I need to execute that script from within a python program. My old code did this: sql_file = open(os.path.join(self.path_to_sql, filename), 'r') sql_text = sql_file.read() sql_stmts = sql_text.split(';') for s in sql_stmts: cursor.execute(s) This worked fine until I started including triggers in my sql script. Since I now need to change the delimiter from ; to something else, in order to support triggers with multiple SQL statements in each, my code to split each statement into it's own string no longer works because the "delimiter |" line in my script fails to split properly, and I get a syntax error from cursor.execute(s). So, I need some way to tell mysqldb to execute an entire sql script at once, instead of individual sql statements. I tried this: sql_file = open(os.path.join(self.path_to_sql, filename), 'r') sql_text = sql_file.read() cursor.execute(sql_text) However, I get the following error when I try to run that code: ProgrammingError: (2014, "Commands out of sync; you can't run this command now") My Google-fu tells me that this is because the Python mysqldb package doesn't support complex SQL statements being sent to cursor.execute(). So how can I do this? I'd really like to find a way to do this entirely within Python, so that the code will remain entirely portable. We have several programmers working on this project in Eclipse, some on Windows and some on Mac, and the code needs to work on the Linux production server as well. If I can't use Python code to actually run the SQL, how can I tell Python to launch a separate program to execute it?
[ "(not a python solution) you can use \n os.system('mysql < etc')\n\nooh, edit (python solution):\nif you have the query broken up by line, you can close and reopen the cursor and execute by line.\nredit: sorry, only skimmed your first paragraph. seems like you were doing this sort of thing at first.\n" ]
[ 2 ]
[ "This doesn't seem like a very good way to structure a multi-language program. \nBrandon's answer is really the right way to go if all you're doing is just executing a big chunk of sql. \nOn the other hand, if you're doing stuff with the results of queries throughout the process of the job, then you shouldn't try...
[ -1 ]
[ "mysql", "python", "sql" ]
stackoverflow_0004045332_mysql_python_sql.txt
Q: How can I properly read out spin buttons in pyGTK? For a small timer app I want to write a GTK interface where I can set the desired time. Here is a picture of the interface: However, I am having trouble reading out the fields of the spin buttons. My envisaged procedure for this is the following: Read out the buttons using methods for each button Here is one of the methods that does this: # Get the fields of the spinbuttons def get_seconds(self, widget, spin): self.rSeconds = spin.get_value_as_int() It is then called like this: button = gtk.Button("Start") button.connect("clicked", self.get_seconds, spinnerS) Create a timer object with the data from the buttons This is planned to be accomplished using this method: # Create the timer object ... def prepare_timer(self, widget, hours, minutes, seconds, title, text): self.timer = eggTimer(hours, minutes, seconds, title, text) Which is called here: button.connect("clicked", self.prepare_timer, self.rHours, self.rMinutes, self.rSeconds, "some title", "some text") Unfortunately, when running the script I get the following error message: Traceback (most recent call last): File "GTKInterface.py", line 140, in <module> SpinButtonExample() File "GTKInterface.py", line 126, in __init__ button.connect("clicked", self.prepare_timer, self.rHours, self.rMinutes, self.rSeconds, "Title", "Text") AttributeError: SpinButtonExample instance has no attribute 'rSeconds' To check whether there really is no instance of that variable, I programmed a short method to print it: def returnS(self, widget): print self.rSeconds And surprisingly this method can "see" self.rSeconds. This makes me wonder what determines the visibility of the variable. What am I doing wrong to read this out? A: You try to pass the attribute self.rHours to the connect method, but at that point the attribute doesn't exist yet (the clicked handlers haven't executed yet). Note that even if you fill in self.rHours before calling connect, it will pass the value at the time of connecting, not at the time of the handler executing. You can solve this by passing self.rHours etc directly to eggTimer in prepare_timer. But it would be even easier to just combine all the click handlers into one, and use local variables instead of self.rHours etc. There's no reason to split your code over many click handlers like this. Edit: BTW, you can also use nested functions instead of methods: ... def prepare_timer(widget): self.timer = eggTimer( spinnerH.get_value_as_int(), spinnerM.get_value_as_int(), spinnerS.get_value_as_int(), "Title", "Text") button.connect("clicked", prepare_timer) ... Keep it simple! A: Going off of adw's answer recommending one click handler, a simple addition to your pastebin code would be: def read_and_prepare(self,spinnerS,spinnerM,spinnerH,title,text): self.get_seconds(spinnerS) self.get_minutes(spinnerM) self.get_hours(spinnerH) self.prepare_timer(elf.rHours, self.rMinutes, self.rSeconds, title, text) and only have button.connect("clicked", self.read_and_prepare,spinnerS,spinnerM,spinnerH,"Title","Text") for the connection code. You could also probably redesign a bit to avoid all the get_* calls and just read the values in the click handler.
How can I properly read out spin buttons in pyGTK?
For a small timer app I want to write a GTK interface where I can set the desired time. Here is a picture of the interface: However, I am having trouble reading out the fields of the spin buttons. My envisaged procedure for this is the following: Read out the buttons using methods for each button Here is one of the methods that does this: # Get the fields of the spinbuttons def get_seconds(self, widget, spin): self.rSeconds = spin.get_value_as_int() It is then called like this: button = gtk.Button("Start") button.connect("clicked", self.get_seconds, spinnerS) Create a timer object with the data from the buttons This is planned to be accomplished using this method: # Create the timer object ... def prepare_timer(self, widget, hours, minutes, seconds, title, text): self.timer = eggTimer(hours, minutes, seconds, title, text) Which is called here: button.connect("clicked", self.prepare_timer, self.rHours, self.rMinutes, self.rSeconds, "some title", "some text") Unfortunately, when running the script I get the following error message: Traceback (most recent call last): File "GTKInterface.py", line 140, in <module> SpinButtonExample() File "GTKInterface.py", line 126, in __init__ button.connect("clicked", self.prepare_timer, self.rHours, self.rMinutes, self.rSeconds, "Title", "Text") AttributeError: SpinButtonExample instance has no attribute 'rSeconds' To check whether there really is no instance of that variable, I programmed a short method to print it: def returnS(self, widget): print self.rSeconds And surprisingly this method can "see" self.rSeconds. This makes me wonder what determines the visibility of the variable. What am I doing wrong to read this out?
[ "You try to pass the attribute self.rHours to the connect method, but at that point the attribute doesn't exist yet (the clicked handlers haven't executed yet).\nNote that even if you fill in self.rHours before calling connect, it will pass the value at the time of connecting, not at the time of the handler executi...
[ 2, 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0004044759_pygtk_python.txt
Q: Python Tkinter Help Menu I have a paragraph of help information that I would like to display in a window with an "ok" button at the bottom. My issue is formatting...I want to be able to simply set the paragraph equal to a variable and then send that variable to a message box widget. By default, it formats laterally and in a very ugly manner. Any advice? def aboutF(): win = Toplevel() win.title("About") about = "Top/bottom 3 - Reports only the top/bottom 3 rows for a param you will later specify.\ Set noise threshold - Filters results with deltas below the specified noise threshold in ps.\ Sort output - Sorts by test,pre,post,unit,delta,abs(delta).\ Top 2 IDD2P/IDD6 registers - Reports only the top 2 IDD2P/IDD6 registers.\ Only critical registers - Reports only critical registers.\ Use tilda output format - Converts the output file from csv to tilda.\ Use html output format - Converts the output file from csv to html." Label(win, text=about, width=100, height=10).pack() Button(win, text='OK', command=win.destroy).pack() A: Use a text widget with word wrapping, and either define your string more accurately or do a little post-processing to remove all that extra whitespace. Using the code from this answer makes it easy to use multiple colors, fonts, etc. For example: import Tkinter as tk import re class CustomText(tk.Text): '''A text widget with a new method, HighlightPattern example: text = CustomText() text.tag_configure("red",foreground="#ff0000") text.HighlightPattern("this should be red", "red") The HighlightPattern method is a simplified python version of the tcl code at http://wiki.tcl.tk/3246 ''' def __init__(self, *args, **kwargs): tk.Text.__init__(self, *args, **kwargs) def HighlightPattern(self, pattern, tag, start="1.0", end="end", regexp=True): '''Apply the given tag to all text that matches the given pattern''' start = self.index(start) end = self.index(end) self.mark_set("matchStart",start) self.mark_set("matchEnd",end) self.mark_set("searchLimit", end) count = tk.IntVar() while True: index = self.search(pattern, "matchEnd","searchLimit",count=count, regexp=regexp) if index == "": break self.mark_set("matchStart", index) self.mark_set("matchEnd", "%s+%sc" % (index,count.get())) self.tag_add(tag, "matchStart","matchEnd") def aboutF(): win = tk.Toplevel() win.title("About") about = '''Top/bottom 3 - Reports only the top/bottom 3 rows for a param you will later specify. Set noise threshold - Filters results with deltas below the specified noise threshold in ps. Sort output - Sorts by test,pre,post,unit,delta,abs(delta). Top 2 IDD2P/IDD6 registers - Reports only the top 2 IDD2P/IDD6 registers. Only critical registers - Reports only critical registers. Use tilda output format - Converts the output file from csv to tilda. Use html output format - Converts the output file from csv to html.''' about = re.sub("\n\s*", "\n", about) # remove leading whitespace from each line t=CustomText(win, wrap="word", width=100, height=10, borderwidth=0) t.tag_configure("blue", foreground="blue") t.pack(sid="top",fill="both",expand=True) t.insert("1.0", about) t.HighlightPattern("^.*? - ", "blue") tk.Button(win, text='OK', command=win.destroy).pack() root=tk.Tk() aboutF() root.mainloop()
Python Tkinter Help Menu
I have a paragraph of help information that I would like to display in a window with an "ok" button at the bottom. My issue is formatting...I want to be able to simply set the paragraph equal to a variable and then send that variable to a message box widget. By default, it formats laterally and in a very ugly manner. Any advice? def aboutF(): win = Toplevel() win.title("About") about = "Top/bottom 3 - Reports only the top/bottom 3 rows for a param you will later specify.\ Set noise threshold - Filters results with deltas below the specified noise threshold in ps.\ Sort output - Sorts by test,pre,post,unit,delta,abs(delta).\ Top 2 IDD2P/IDD6 registers - Reports only the top 2 IDD2P/IDD6 registers.\ Only critical registers - Reports only critical registers.\ Use tilda output format - Converts the output file from csv to tilda.\ Use html output format - Converts the output file from csv to html." Label(win, text=about, width=100, height=10).pack() Button(win, text='OK', command=win.destroy).pack()
[ "Use a text widget with word wrapping, and either define your string more accurately or do a little post-processing to remove all that extra whitespace. Using the code from this answer makes it easy to use multiple colors, fonts, etc. \nFor example:\nimport Tkinter as tk\nimport re\n\nclass CustomText(tk.Text):\n ...
[ 1 ]
[]
[]
[ "menu", "python", "tkinter" ]
stackoverflow_0004028446_menu_python_tkinter.txt
Q: Python: Self is not defined class a(object): def __init__(self): self.b = 1 self.c = 2 This gives the error: NameError: name 'self' is not defined I looked at a previous post, but the error was for a different reason. Any help with this? A: I'm assuming the single space before def __init__(self): is actually a tab in your file and displayed as four spaces by your editor. However python interprets a tab as 8 spaces, so the following two lines (which are indented by 8 spaces) are seen by python to be at the same level of indentation as the def. This is exactly why you shouldn't mix tabs and spaces. A: This is just a guess because you didn't post the actual traceback or code, but if the actual snippet above is giving you problems, it's probably that your indentation is off and the interpreter is interpreting your scoping levels incorrectly.
Python: Self is not defined
class a(object): def __init__(self): self.b = 1 self.c = 2 This gives the error: NameError: name 'self' is not defined I looked at a previous post, but the error was for a different reason. Any help with this?
[ "I'm assuming the single space before def __init__(self): is actually a tab in your file and displayed as four spaces by your editor.\nHowever python interprets a tab as 8 spaces, so the following two lines (which are indented by 8 spaces) are seen by python to be at the same level of indentation as the def.\nThis ...
[ 12, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004045599_python.txt
Q: Scons Hierarchical Builds with Repository directory I have an SCons project set up as follows: proj/ SConstruct src/ c/ h/ app1/SConscript app2/SConscript ... All source/header files for each application are located in src/c and src/h. At first step I created a SConstruct in app1 which use the Repository function. ... src=Split("main.c first.c second.c") env = Environment(CC='g++', CCFLAGS=['-O0', '-ggdb'], CPPPATH=['.']) env.Program('appone', src) Repository("../src/c", "../src/h") All works fine. scons found all necessary source/header files from repository to build the appone application. But if I try to build appone hierarchical it will not work :-( I renamed app1/SConstruct to app1/SConscript and put SConscript('app1/SConscript') into proj/SConstruct Now I get following error: scons: *** [app1/main.o] Source `app1/main.c' not found, needed by target `app1/main.o'. How do I configure my proj/SConstruct or proj/app1/SConscript to search for all source files in my Repository directory? A: SCons is looking for your source files in the app1 directory. If you specify the sources like this: src=Split("#main.c #first.c #second.c") then scons will search the Repositories for the source files. A couple extra thoughts: You may want main.c to be in the app1 directory to avoid conflicts with main.c for other executables. In this case, remove the # from main.c in your source list. It's probably a good idea to define the Repositories in your top-level SConstruct if multiple apps share the repositories. It's often useful to build libraries from the shared sources so that unit tests can have their own main functions, but link the same sources as your apps (or so apps can share common modules). It may be easier to do this by putting SConscripts in the shared repository directory to build common libraries. Beyond the scope of this question, but something to consider as your project grows.
Scons Hierarchical Builds with Repository directory
I have an SCons project set up as follows: proj/ SConstruct src/ c/ h/ app1/SConscript app2/SConscript ... All source/header files for each application are located in src/c and src/h. At first step I created a SConstruct in app1 which use the Repository function. ... src=Split("main.c first.c second.c") env = Environment(CC='g++', CCFLAGS=['-O0', '-ggdb'], CPPPATH=['.']) env.Program('appone', src) Repository("../src/c", "../src/h") All works fine. scons found all necessary source/header files from repository to build the appone application. But if I try to build appone hierarchical it will not work :-( I renamed app1/SConstruct to app1/SConscript and put SConscript('app1/SConscript') into proj/SConstruct Now I get following error: scons: *** [app1/main.o] Source `app1/main.c' not found, needed by target `app1/main.o'. How do I configure my proj/SConstruct or proj/app1/SConscript to search for all source files in my Repository directory?
[ "SCons is looking for your source files in the app1 directory. If you specify the sources like this:\nsrc=Split(\"#main.c #first.c #second.c\")\n\nthen scons will search the Repositories for the source files. \nA couple extra thoughts:\n\nYou may want main.c to be in the app1 directory to avoid conflicts with main....
[ 0 ]
[]
[]
[ "python", "scons" ]
stackoverflow_0004043689_python_scons.txt
Q: Is there Python PDF metadata writing library for Windows? Can someone point me to Python PDF package that can do metadata writing? I found Python XMP Toolkit, but building Exempi on cygwin is nightmare I want to avoid. A: You can modify pdf docinfo metadata, (not xmp metadata) in either of the following ways: pdfrw seems to have some support for this (not a lot of documentation, but looking at the alter.py example, it seems to be possible). This SO question uses pyPdf library to make a new pdf with the desired metadata: Change metadata of pdf file with pypdf. Alternatively, you could wrap a command line application like pdftk. A: You might want to get a command line to modify metadata. Some tools modify both native and XMP metadata. I wrote a blog on metadata editing a while ago: http://www.barcodeschool.com/2010/09/publishers-fix-the-metadata-in-the-pdf-file/
Is there Python PDF metadata writing library for Windows?
Can someone point me to Python PDF package that can do metadata writing? I found Python XMP Toolkit, but building Exempi on cygwin is nightmare I want to avoid.
[ "You can modify pdf docinfo metadata, (not xmp metadata) in either of the following ways:\n\npdfrw seems to have some support for this (not a lot of documentation, but looking at the alter.py example, it seems to be possible). \nThis SO question uses pyPdf library to make a new pdf with the desired metadata: Change...
[ 3, 0 ]
[]
[]
[ "pdf", "python" ]
stackoverflow_0004003935_pdf_python.txt
Q: converting bibtex files to html with python (maybe pybtex?) Hi I want to parse a bibtex publications file and sort for specific fields (e.g. year) and filter certain content, to then put it on a website. I came across pybtex, which works as far as reading and parsing the bibtex file, but it is basically not documented and I can't figure out how to sort the entries. Is pybtex the way to go (how can I sort the entries) or are there better options? thanks a lot!! A: Found a solution, this sorts the entries in a descending order using pybtex, newest publications go first: from pybtex.database.input import bibtex from operator import itemgetter, attrgetter import pprint parser = bibtex.Parser() bib_data = parser.parse_file('ref.bib') def sort_by_year(y, x): return int(x[1].fields['year']) - int(y[1].fields['year']) bib_sorted = sorted(bib_data.entries.items(), cmp=sort_by_year) for key, value in bib_sorted: print key print value.fields['year'] print value.fields['author'] print value.fields['title']
converting bibtex files to html with python (maybe pybtex?)
Hi I want to parse a bibtex publications file and sort for specific fields (e.g. year) and filter certain content, to then put it on a website. I came across pybtex, which works as far as reading and parsing the bibtex file, but it is basically not documented and I can't figure out how to sort the entries. Is pybtex the way to go (how can I sort the entries) or are there better options? thanks a lot!!
[ "Found a solution, this sorts the entries in a descending order using pybtex, newest publications go first:\nfrom pybtex.database.input import bibtex\nfrom operator import itemgetter, attrgetter\nimport pprint\nparser = bibtex.Parser()\nbib_data = parser.parse_file('ref.bib')\n\ndef sort_by_year(y, x):\n return ...
[ 12 ]
[]
[]
[ "bibtex", "html", "parsing", "python", "text_parsing" ]
stackoverflow_0004038703_bibtex_html_parsing_python_text_parsing.txt
Q: Tkinter buttons help I have a class with a button, it runs the command automatically when the gui is constructed (which i dont want it to do) but then doesnt work again after. What am I doing wrong? Builtin commands such as endcommand work as they should. relevant excerpts (ignore the indent problem at the very beginning) class GuiPart(object): def __init__(self, master, queue, endCommand): self.queue = queue # Set up the GUI #tkinter.Button(master, text='Done', command=endCommand).grid(row=6,column=6) tkinter.Button(text='Update Variables', command=self.updateValues()).grid(row=3) Lp_pacingState = tkinter.Label(text="p_pacingState") Lp_pacingState.grid(row=1, column=3) Tp_pacingState = tkinter.Label(bg="white", relief="ridge",justify="center",width=9) Tp_pacingState.grid(row=1, column=4) .... self.textBoxes = {"p_pacingState" : Tp_pacingState, "p_pacingMode" : Tp_pacingMode, "p_hysteresis" : Tp_hysteresis, "p_hysteresisInterval" : Tp_hysteresisInterval, "p_lowrateInterval" : Tp_lowrateInterval, "p_vPaceAmp" : Tp_vPaceAmp, "p_vPaceWidth" : Tp_vPaceWidth, "p_VRP" : Tp_VRP} #def updateValues(self,input): def updateValues(self): testInput = ["p_pacingState=3", "garbage=poop", "p_VRP=5"] for updates in testInput: print("zzzz") var = updates.split("=") try: self.textBoxes[var[0]].config(text = var[1]) except: pass So I get "zzzz" printed 3 times at construction of gui (labels dont update their text though) and the button doesnt work after that. Also if theres a better way to update boxes please tell me. I get input from a stream in no particular order or relevance. Thanks in advance A: When you do this: command=self.updateValues() You are calling the function self.updateValues (because of the ()). The result of that function call is being assigned to the command attribute which is not what you want. You need to remove the () so that the command attribute gets a reference to the method rather than the result of calling the method.
Tkinter buttons help
I have a class with a button, it runs the command automatically when the gui is constructed (which i dont want it to do) but then doesnt work again after. What am I doing wrong? Builtin commands such as endcommand work as they should. relevant excerpts (ignore the indent problem at the very beginning) class GuiPart(object): def __init__(self, master, queue, endCommand): self.queue = queue # Set up the GUI #tkinter.Button(master, text='Done', command=endCommand).grid(row=6,column=6) tkinter.Button(text='Update Variables', command=self.updateValues()).grid(row=3) Lp_pacingState = tkinter.Label(text="p_pacingState") Lp_pacingState.grid(row=1, column=3) Tp_pacingState = tkinter.Label(bg="white", relief="ridge",justify="center",width=9) Tp_pacingState.grid(row=1, column=4) .... self.textBoxes = {"p_pacingState" : Tp_pacingState, "p_pacingMode" : Tp_pacingMode, "p_hysteresis" : Tp_hysteresis, "p_hysteresisInterval" : Tp_hysteresisInterval, "p_lowrateInterval" : Tp_lowrateInterval, "p_vPaceAmp" : Tp_vPaceAmp, "p_vPaceWidth" : Tp_vPaceWidth, "p_VRP" : Tp_VRP} #def updateValues(self,input): def updateValues(self): testInput = ["p_pacingState=3", "garbage=poop", "p_VRP=5"] for updates in testInput: print("zzzz") var = updates.split("=") try: self.textBoxes[var[0]].config(text = var[1]) except: pass So I get "zzzz" printed 3 times at construction of gui (labels dont update their text though) and the button doesnt work after that. Also if theres a better way to update boxes please tell me. I get input from a stream in no particular order or relevance. Thanks in advance
[ "When you do this:\ncommand=self.updateValues()\n\nYou are calling the function self.updateValues (because of the ()). The result of that function call is being assigned to the command attribute which is not what you want. You need to remove the () so that the command attribute gets a reference to the method rather...
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004046118_python_tkinter.txt
Q: What is the best way to serve small static images? Right now I'm base 64 encoding them and using data uris. The idea was that this will somehow lower the number of requests the browser needs to make. Does this bucket hold any water? What is the best way of serving images in general? DB, from FS, S3? I am most interested in python and java based answers, but all are welcome! A: I would definitely take a look at CSS Image Sprites, decent write-ups here and here. The concept is pretty simple, combine your images into one, show only the slice you need as a CSS background. This lets you lower the number of HTTP requests from many images into one or more (group your small images in sprite maps as appropriate) and have fewer images to maintain, the CSS just has some background coordinates in there. Also, as with any static resource, make sure your cache headers are set correctly, so the client isn't fetching it needlessly. A: Nicholas C. Zakas has written a tool that makes it easier to use data URIs in css, and also contains an IE6/7 compatible fix: CSSEmbed also supports an MHTML mode to make IE6 and IE7 compatible stylesheets that use internal images similar to data URIs. A: Right now I'm base 64 encoding them and using data uris. The idea was that this will somehow lower the number of requests the browser needs to make. Does this bucket hold any water? This is most definitely a bad idea: It won't work in IE < 8; it increases the data volume served by 33%; and it makes the images completely uncacheable. I'd say you should serve images as proper image resources - whether as separate files, or maybe as CSS sprites as @Nick suggests, will depend on their quantity and size. A: Data urls will definitely reduce the number of requests to the server, since the browser doesn't have to ask for the pixels in a separate request. But they are not supported in all browsers. You'll have to make the tradeoff.
What is the best way to serve small static images?
Right now I'm base 64 encoding them and using data uris. The idea was that this will somehow lower the number of requests the browser needs to make. Does this bucket hold any water? What is the best way of serving images in general? DB, from FS, S3? I am most interested in python and java based answers, but all are welcome!
[ "I would definitely take a look at CSS Image Sprites, decent write-ups here and here.\nThe concept is pretty simple, combine your images into one, show only the slice you need as a CSS background. This lets you lower the number of HTTP requests from many images into one or more (group your small images in sprite m...
[ 13, 3, 2, 1 ]
[]
[]
[ "image", "java", "javascript", "python" ]
stackoverflow_0004046242_image_java_javascript_python.txt
Q: How do you do string interpolation with a URL that contains formatting characters? I'm trying to use URLLIB2 to open a URL and read back the contents into an array. The issue seems to be that you cannot use string interpolation in a URL that has formatting characters such as %20 for space, %3C for '<'. The URL in question has spaces and a bit of xml in it. My code is pretty simple, looks something like this: #Python script to fetch NS Client Policies using GUID import sys import urllib2 def GetPolicies(ns, guid): ns = sys.argv[1] guid = sys.argv[2] fetch = urllib2.urlopen('http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%3Crequest%20configVersion=%222%22%20guid=%22{%s}%22') % (ns, guid) I've shortened the URL for brevity but you get the general idea, you get a 'Not enough arguments for format string' error since it assumes you're wanting to use the %3, %20, and other things as string interpolations. How do you get around this? Edit: Solution requires Python 2.6+, 2.5 or prior has no support for the string.format() method A: You can double the % signs url = 'http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%%3Crequest%%20configVersion=%%222%%22%%20guid=%%22{%s}%%22' % (ns, guid) or you can use .format() method url = 'http://{hostname}/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%3Crequest%20configVersion=%222%22%20guid=%22{id}%%2''.format(hostname=ns, id=guid) A: Use the .format method on the string instead. From its documentation: str.format(*args, **kwargs) Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument. >>> "The sum of 1 + 2 is {0}".format(1+2) 'The sum of 1 + 2 is 3' While we all sin by sticking to % as we're used to from C, the format method is really a more robust method of interpolating values into strings. A: Build your string up in steps, doing each encoding layer separately. Much more manageable than trying to cope with the multiple levels of escaping in one go. xml= '<request configVersion="2" guid="{%s}"/>' % cgi.escape(guid, True) query= 'xml=%s' % urllib2.quote(xml) url= 'http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?%s' % (ns, query) fetch= urllib2.urlopen(url) A: If you're trying to build the url yourself use urllib.urlencode. It will deal with a lot of the quoting issues for you. Just pass it a dict of the info you want: from urllib import urlencode args = urlencode({'xml': '<', 'request configVersion': 'bar', 'guid': 'zomg'}) As for replacing hostname in the base of your url string, just do what everyone else said and use the %s formatting. The final string could be somthing like: print 'http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?%s' % ('foobar.com', args)
How do you do string interpolation with a URL that contains formatting characters?
I'm trying to use URLLIB2 to open a URL and read back the contents into an array. The issue seems to be that you cannot use string interpolation in a URL that has formatting characters such as %20 for space, %3C for '<'. The URL in question has spaces and a bit of xml in it. My code is pretty simple, looks something like this: #Python script to fetch NS Client Policies using GUID import sys import urllib2 def GetPolicies(ns, guid): ns = sys.argv[1] guid = sys.argv[2] fetch = urllib2.urlopen('http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%3Crequest%20configVersion=%222%22%20guid=%22{%s}%22') % (ns, guid) I've shortened the URL for brevity but you get the general idea, you get a 'Not enough arguments for format string' error since it assumes you're wanting to use the %3, %20, and other things as string interpolations. How do you get around this? Edit: Solution requires Python 2.6+, 2.5 or prior has no support for the string.format() method
[ "You can double the % signs\nurl = 'http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%%3Crequest%%20configVersion=%%222%%22%%20guid=%%22{%s}%%22' % (ns, guid)\n\nor you can use .format() method\nurl = 'http://{hostname}/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%3Crequest%20configVersion=%222%22%20guid=%22{i...
[ 7, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004044754_python.txt
Q: Ignore optparse if value is given I would like to have the ability to pass an argument w/o having to specify an option for optparse. If I do pass an option, it has to be a known option or else the script will fail. Rsync the following file to destination myscript.py filename Rsync the following folder to destination (all this is figured out in function I create). myscript.py -f foldername The reason is, I have an array (or dict) that ties with the "foldername." If no options are passed, the argument given in the CLI is a file that's in the working folder where the user calls the script. Passing -f means to upload a folder whose value is stored in a dict (user can be in any directory, this folder's path is known ahead of time). Am I better off adding options for both options? -f for file and -v for folder aka version? A: I am always a fan of being explicit, but you can short circuit optparse. # args[0] is always the executable's name if len(args) > 1: parser.parse_args(args, options) else: #open file A: Treat -f as an option with no argument and use it to switch the behavior of the positional argument (i.e. foldername). A: parser.parse_args() always returns two values: options, an object containing values for all of your options args, the list of positional arguments leftover after parsing options (Totorial) As such, you could do something like this: parser = OptionParser() parser.add_option("-f", "", action="store_true", dest="folder", default=False) (options, args) = parser.parse_args(sys.argv) fname = args[1] # name of folder or file if options.folder: # do stuff for folder else: # do stuff for file
Ignore optparse if value is given
I would like to have the ability to pass an argument w/o having to specify an option for optparse. If I do pass an option, it has to be a known option or else the script will fail. Rsync the following file to destination myscript.py filename Rsync the following folder to destination (all this is figured out in function I create). myscript.py -f foldername The reason is, I have an array (or dict) that ties with the "foldername." If no options are passed, the argument given in the CLI is a file that's in the working folder where the user calls the script. Passing -f means to upload a folder whose value is stored in a dict (user can be in any directory, this folder's path is known ahead of time). Am I better off adding options for both options? -f for file and -v for folder aka version?
[ "I am always a fan of being explicit, but you can short circuit optparse.\n# args[0] is always the executable's name\nif len(args) > 1:\n parser.parse_args(args, options)\nelse:\n #open file\n\n", "Treat -f as an option with no argument and use it to switch the behavior of the positional argument (i.e. fold...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004046162_python.txt
Q: good refactoring or bad? Given the following code: status = row[COL_STATUS] if status == "idle": row[COL_EDITABLE] = True row[COL_FONTSTYLE] = pango.STYLE_NORMAL row[COL_WEIGHT] = pango.WEIGHT_NORMAL elif status == "DCed": row[COL_EDITABLE] = True row[COL_FONTSTYLE] = pango.STYLE_ITALIC row[COL_WEIGHT] = pango.WEIGHT_NORMAL else: row[COL_EDITABLE] = False row[COL_FONTSTYLE] = pango.STYLE_NORMAL row[COL_WEIGHT] = pango.WEIGHT_BOLD Would the following be a net beneficial refactoring, in your opinion? d = {"idle": (True, pango.STYLE_NORMAL, pango.WEIGHT_NORMAL), "DCed": (True, pango.STYLE_ITALIC, pango.WEIGHT_NORMAL), None: (False, pango.STYLE_NORMAL, pango.WEIGHT_BOLD)} e,f,w = d.get(status, d[None]) row[COL_EDITABLE] = e row[COL_FONTSTYLE] = f row[COL_WEIGHT] = w What if there were more cases or more row components to edit? A: What about using objects and doing something akin to "Replace Type Code With Subclasses"? http://www.refactoring.com/catalog/replaceTypeCodeWithSubclasses.html A: What you gain in conciseness you lose in readability. In the current example, I can easily tell what goes where. In the new code, I have to think a little harder. Multiply that by the next thousand edits and you're going to have some serious maintainability problems on your hands.
good refactoring or bad?
Given the following code: status = row[COL_STATUS] if status == "idle": row[COL_EDITABLE] = True row[COL_FONTSTYLE] = pango.STYLE_NORMAL row[COL_WEIGHT] = pango.WEIGHT_NORMAL elif status == "DCed": row[COL_EDITABLE] = True row[COL_FONTSTYLE] = pango.STYLE_ITALIC row[COL_WEIGHT] = pango.WEIGHT_NORMAL else: row[COL_EDITABLE] = False row[COL_FONTSTYLE] = pango.STYLE_NORMAL row[COL_WEIGHT] = pango.WEIGHT_BOLD Would the following be a net beneficial refactoring, in your opinion? d = {"idle": (True, pango.STYLE_NORMAL, pango.WEIGHT_NORMAL), "DCed": (True, pango.STYLE_ITALIC, pango.WEIGHT_NORMAL), None: (False, pango.STYLE_NORMAL, pango.WEIGHT_BOLD)} e,f,w = d.get(status, d[None]) row[COL_EDITABLE] = e row[COL_FONTSTYLE] = f row[COL_WEIGHT] = w What if there were more cases or more row components to edit?
[ "What about using objects and doing something akin to \"Replace Type Code With Subclasses\"?\nhttp://www.refactoring.com/catalog/replaceTypeCodeWithSubclasses.html\n", "What you gain in conciseness you lose in readability. In the current example, I can easily tell what goes where. In the new code, I have to think...
[ 4, 3 ]
[]
[]
[ "coding_style", "python", "refactoring" ]
stackoverflow_0004046468_coding_style_python_refactoring.txt
Q: Django Paginator not working beyond first page As mentioned in the title, my paginator doesn't show anything when I click to go to a page beyond the first. First, let me describe my page in general: Its function is to get a request input from the user specifying the period interval from which he wants to see a bunch of "call records" along with other filters (this is important). So essentially there's a start and end date from the request and I use it to filter my objects. The link to "page2" is something like: "localhost:8000/?page=2" and redirects to my existing page but without any data. It's obvious now that the link to the next page should include the other parameters such as start_date=xxxx-xx-xx, or else it wouldn't work. Here's part of my view.py and I took out a lot of lines to make it brief, the code runs fine: if request.GET: filter_form = ReportFilterForm(request.GET) if filter_form.is_valid(): start = filter_form.cleaned_data["start_date"] end = filter_form.cleaned_data["end_date"] #a bunch of omitted lines that use the form to filter paginator = Paginator(queryset, 100) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: call_logs = paginator.page(page) except (EmptyPage, InvalidPage): call_logs = paginator.page(paginator.num_pages) else: filter_form = ReportFilterForm() return render_to_response('xxxx.html', {'queryset': queryset, 'filter_form': filter_form, 'call_logs': call_logs, }) My template xxxx.html, just the paginator section, which is pretty standard, taken from the documentation: {% if call_logs.paginator.num_pages %} <div class="pagination"> <span class="step-links"> {% if call_logs.has_previous %} <a href="**{{ SOME_MAGIC_TEMPLATE_VARIABLE_THAT_GETS_CURRENT_ABSOLUTE_URL}}**&?page={{ call_logs.previous_page_number }}"><<</a> {% endif %} <span class="current"> Page {{ call_logs.number }} of {{ call_logs.paginator.num_pages }} </span> {% if call_logs.has_next %} <a href=" **{{ SOME_MAGIC_TEMPLATE_VARIABLE_THAT_GETS_CURRENT_ABSOLUTE_URL}}**&page={{ call_logs.next_page_number }}">>></a> {% endif %} </span> </div> {% endif %} My question is how do I get the current window URL using django templates and not javascript? Thank you. A: My question is how do I get the current window URL using django templates and not javascript? Thank you. it's not necessary the right way to do it, but you can check this post but i will suggest that you shouldn't mix the filter with the pagination. rather that you can use AJAX when doing filtering you can create a new function that deal with filtering alone or you can just use the same function and test if request.is_ajax(): , like that when a users filter the contain you will have your filter data (start_date,end_date ) in the URL. and now when a user want to pass to the next page you already have the filtered argument in the url that you can use to create a queryset that will be pass to the Paginator. And to deal with the javascript not active you can replace AJAX with a simple POST form and just remember don't mix the filtering with the pagination :) Hope this will Help :) A: You could add the full path to the context from the request object if I understand you correctly: return render_to_response('xxxx.html', {'queryset': queryset, 'filter_form': filter_form, 'call_logs': call_logs,, 'magic_url': request.get_full_path(), })
Django Paginator not working beyond first page
As mentioned in the title, my paginator doesn't show anything when I click to go to a page beyond the first. First, let me describe my page in general: Its function is to get a request input from the user specifying the period interval from which he wants to see a bunch of "call records" along with other filters (this is important). So essentially there's a start and end date from the request and I use it to filter my objects. The link to "page2" is something like: "localhost:8000/?page=2" and redirects to my existing page but without any data. It's obvious now that the link to the next page should include the other parameters such as start_date=xxxx-xx-xx, or else it wouldn't work. Here's part of my view.py and I took out a lot of lines to make it brief, the code runs fine: if request.GET: filter_form = ReportFilterForm(request.GET) if filter_form.is_valid(): start = filter_form.cleaned_data["start_date"] end = filter_form.cleaned_data["end_date"] #a bunch of omitted lines that use the form to filter paginator = Paginator(queryset, 100) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: call_logs = paginator.page(page) except (EmptyPage, InvalidPage): call_logs = paginator.page(paginator.num_pages) else: filter_form = ReportFilterForm() return render_to_response('xxxx.html', {'queryset': queryset, 'filter_form': filter_form, 'call_logs': call_logs, }) My template xxxx.html, just the paginator section, which is pretty standard, taken from the documentation: {% if call_logs.paginator.num_pages %} <div class="pagination"> <span class="step-links"> {% if call_logs.has_previous %} <a href="**{{ SOME_MAGIC_TEMPLATE_VARIABLE_THAT_GETS_CURRENT_ABSOLUTE_URL}}**&?page={{ call_logs.previous_page_number }}"><<</a> {% endif %} <span class="current"> Page {{ call_logs.number }} of {{ call_logs.paginator.num_pages }} </span> {% if call_logs.has_next %} <a href=" **{{ SOME_MAGIC_TEMPLATE_VARIABLE_THAT_GETS_CURRENT_ABSOLUTE_URL}}**&page={{ call_logs.next_page_number }}">>></a> {% endif %} </span> </div> {% endif %} My question is how do I get the current window URL using django templates and not javascript? Thank you.
[ "\nMy question is how do I get the\n current window URL using django\n templates and not javascript? Thank\n you.\n\nit's not necessary the right way to do it, but you can check this post\nbut i will suggest that you shouldn't mix the filter with the pagination.\nrather that you can use AJAX when doing filtering...
[ 1, 1 ]
[]
[]
[ "django", "pagination", "python" ]
stackoverflow_0004045743_django_pagination_python.txt