title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python: Convert a string to an integer
2,508,861
7
2010-03-24T15:17:04Z
2,508,868
8
2010-03-24T15:18:00Z
[ "python" ]
Does anybody have a quickie for converting an unsafe string to an `int`? The string typically comes back as: `'234\r\n'` or something like that. In this case I want `234`. If `'-1\r\n'`, I want `-1`. I never want the method to fail but I don't want to go so far as try, except, pass just to hide errors either (in case...
`int('243\r\n'.strip())` But that won't help you, if something else than a number is passed. Always put try, except and catch `ValueError`. Anyway, this also works: `int('243\n\r ')`, so maybe you don't even need `strip`. **EDIT**: Why don't you just write your own function, that will catch the exception and return...
Python: Convert a string to an integer
2,508,861
7
2010-03-24T15:17:04Z
2,508,940
16
2010-03-24T15:27:00Z
[ "python" ]
Does anybody have a quickie for converting an unsafe string to an `int`? The string typically comes back as: `'234\r\n'` or something like that. In this case I want `234`. If `'-1\r\n'`, I want `-1`. I never want the method to fail but I don't want to go so far as try, except, pass just to hide errors either (in case...
In this case you do have a way to avoid `try`/`except`, although I wouldn't recommend it (assuming your input string is named `s`, and you're in a function that must return something): ``` xs = s.strip() if xs[0:1] in '+-': xs = xs[1:] if xs.isdigit(): return int(s) else: ... ``` the `...` part in the `else` is where...
catalogue a list of dictionaries
2,509,260
2
2010-03-24T16:04:44Z
2,509,414
8
2010-03-24T16:24:00Z
[ "python", "dictionary", "nested", "catalog" ]
I have a list of dictionaries: ``` people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"}, {"name": "Dan", "city": "Boston", "age": 20, "sex": "M"}, {"name": "Roger", "city": "Boston", "age": 21, "sex": "M"}, {"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}] ``` I want...
recursively: ``` import itertools, operator def catalog(fields,people): cur_field = operator.itemgetter(fields[0]) groups = itertools.groupby(sorted(people, key=cur_field),cur_field) if len(fields)==1: return dict((k,list(v)) for k,v in groups) else: return dict((k,catalog(fields[1:],v...
Convert UTF-8 bytes to some other encoding in Python
2,509,578
2
2010-03-24T16:43:22Z
2,509,590
9
2010-03-24T16:45:01Z
[ "python", "unicode", "encoding" ]
I need to do in Python 2.4 (yes, 2.4 :-( ). I've got a plain string object, which represents some text encoded with UTF-8. It comes from an external library, which can't be modified. So, what I think I need to do, is to create an Unicode object using bytes from that source object, and then convert it to some other en...
``` >>> x.decode('utf8').encode('iso-8859-2') 'Sk\xb3odowski' ```
More nest Python nested dictionaries
2,510,126
3
2010-03-24T17:48:11Z
2,510,138
14
2010-03-24T17:49:51Z
[ "python", "collections", "nested" ]
After reading <http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python> why is it wrong to do: ``` c = collections.defaultdict(collections.defaultdict(int)) ``` in python? I would think this would work to produce ``` {key:{key:1}} ``` or am I thinking about it wrong...
The constructor of `defaultdict` expects a callable. `defaultdict(int)` is a default dictionary object, not a callable. Using a `lambda` it can work, however: ``` c = collections.defaultdict(lambda: collections.defaultdict(int)) ``` This works since what I pass to the outer `defaultdict` is a callable that creates a ...
What's the best django way to do a query that spans several tables?
2,510,429
2
2010-03-24T18:34:05Z
2,510,693
10
2010-03-24T19:11:26Z
[ "python", "mysql", "database", "django" ]
I have a reviews/ratings web application, a la Digg. My django app `content` has the following model: ``` class Content(models.Model): title = models.CharField(max_length=128) url = models.URLField(max_length=2048) description = models.TextField(blank=True) class Recommendation(models.Model): user = m...
I would use: ``` Recommendation.objects.filter(user__publication_set__subscriber=request.user).select_related() ``` That will get you all the Recommendation objects as you requested, and the select\_related will load all the related User and Content objects into memory so that subsequent access of them won't hit the ...
Short Python alphanumeric hash with minimal collisions
2,510,716
13
2010-03-24T19:14:36Z
2,510,733
12
2010-03-24T19:16:22Z
[ "python", "hash" ]
I'd like to set non-integer primary keys for a table using some kind of hash function. md5() seems to be kind of long (32-characters). What are some alternative hash functions that perhaps use every letter in the alphabet as well as integers that are perhaps shorter in string length and have low collision rates? Than...
Why don't you just truncate SHA1 or MD5? You'll have more collisions then if you didn't truncate, but it's still better than designing your own. Note that you can base64-encode the truncated hash, rather than using hexadecimal. E.g. ``` import base64 import hashlib hasher = hashlib.sha1("The quick brown fox") base64.u...
Short Python alphanumeric hash with minimal collisions
2,510,716
13
2010-03-24T19:14:36Z
2,510,935
17
2010-03-24T19:51:52Z
[ "python", "hash" ]
I'd like to set non-integer primary keys for a table using some kind of hash function. md5() seems to be kind of long (32-characters). What are some alternative hash functions that perhaps use every letter in the alphabet as well as integers that are perhaps shorter in string length and have low collision rates? Than...
The smallest builtin hash I am aware of is md5 ``` >>> import hashlib >>> hashlib.md5("hello worlds").digest().encode("base64") 'uWuHitcvVnCdu1Yo4c6hjQ==\n' ``` Low collision and short are somewhat mutually exclusive due to the [birthday paradox](http://en.wikipedia.org/wiki/Birthday_problem) To make it urlsafe you ...
Persistent Hashing of Strings in Python
2,511,058
19
2010-03-24T20:14:16Z
2,511,075
26
2010-03-24T20:17:29Z
[ "python" ]
How would you convert an arbitrary string into a unique integer, which would be the same across Python sessions and platforms? For example `hash('my string')` wouldn't work because a different value is returned for each Python session and platform.
Use a hash algorithm such as MD5 or SHA1, then convert the `hexdigest` via `int()`: ``` >>> import hashlib >>> int(hashlib.md5('Hello, world!').hexdigest(), 16) 144653930895353261282233826065192032313L ```
Persistent Hashing of Strings in Python
2,511,058
19
2010-03-24T20:14:16Z
2,511,232
8
2010-03-24T20:41:51Z
[ "python" ]
How would you convert an arbitrary string into a unique integer, which would be the same across Python sessions and platforms? For example `hash('my string')` wouldn't work because a different value is returned for each Python session and platform.
If a hash function really won't work for you, you can turn the string into a number. ``` my_string = 'my string' def string_to_int(s): ord3 = lambda x : '%.3d' % ord(x) return int(''.join(map(ord3, s))) In[10]: string_to_int(my_string) Out[11]: 109121032115116114105110103L ``` This is invertible, by mapping ...
Efficiently generate a 16-character, alphanumeric string
2,511,222
19
2010-03-24T20:40:16Z
2,511,238
31
2010-03-24T20:42:58Z
[ "python", "hash", "random" ]
I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table. Would something like this work? ``` def genKey(): hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64") alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash) return alnum_hash[:16] ``` What would be a good...
You can use this: ``` >>> import random >>> ''.join(random.choice('0123456789ABCDEF') for i in range(16)) 'E2C6B2E19E4A7777' ``` There is no guarantee that the keys generated will be unique so you should be ready to retry with a new key in the case the original insert fails. Also, you might want to consider using a d...
Efficiently generate a 16-character, alphanumeric string
2,511,222
19
2010-03-24T20:40:16Z
2,511,244
18
2010-03-24T20:43:17Z
[ "python", "hash", "random" ]
I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table. Would something like this work? ``` def genKey(): hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64") alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash) return alnum_hash[:16] ``` What would be a good...
Have a look at the [uuid module](http://docs.python.org/library/uuid.html) (Python 2.5+). A quick example: ``` >>> import uuid >>> uid = uuid.uuid4() >>> uid.hex 'df008b2e24f947b1b873c94d8a3f2201' ``` Note that the OP asked for a 16-character alphanumeric string, but UUID4 strings are 32 characters long. You should ...
Efficiently generate a 16-character, alphanumeric string
2,511,222
19
2010-03-24T20:40:16Z
30,779,367
12
2015-06-11T11:21:17Z
[ "python", "hash", "random" ]
I'm looking for a very quick way to generate an alphanumeric unique id for a primary key in a table. Would something like this work? ``` def genKey(): hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base64") alnum_hash = re.sub(r'[^a-zA-Z0-9]', "", hash) return alnum_hash[:16] ``` What would be a good...
As none of the answers provide you with a random string consisting of characters 0-9, a-z, A-Z: Here is a working solution which will give you approx. 4.5231285e+74 keys: ``` import random, string x = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(16)) print(x) ``...
Why does x,y = zip(*zip(a,b)) work in Python?
2,511,300
59
2010-03-24T20:51:31Z
2,511,319
14
2010-03-24T20:54:08Z
[ "python", "zip" ]
OK I love Python's `zip()` function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of `zip()`, think "I used to know how to do that", then google python unzip, then remember that one uses this magical `*` to unzip a zipped list of tuples. Like this: ``` x = [1,2,3] y = [4,5,6] zipp...
The asterisk performs `apply` (as it's known in Lisp and Scheme). Basically, it takes your list, and calls the function with that list's contents as arguments.
Why does x,y = zip(*zip(a,b)) work in Python?
2,511,300
59
2010-03-24T20:51:31Z
2,511,332
31
2010-03-24T20:55:32Z
[ "python", "zip" ]
OK I love Python's `zip()` function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of `zip()`, think "I used to know how to do that", then google python unzip, then remember that one uses this magical `*` to unzip a zipped list of tuples. Like this: ``` x = [1,2,3] y = [4,5,6] zipp...
The asterisk in Python is documented in the Python tutorial, under [Unpacking Argument Lists](http://docs.python.org/tutorial/controlflow.html#tut-unpacking-arguments).
Why does x,y = zip(*zip(a,b)) work in Python?
2,511,300
59
2010-03-24T20:51:31Z
2,511,400
7
2010-03-24T21:04:43Z
[ "python", "zip" ]
OK I love Python's `zip()` function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of `zip()`, think "I used to know how to do that", then google python unzip, then remember that one uses this magical `*` to unzip a zipped list of tuples. Like this: ``` x = [1,2,3] y = [4,5,6] zipp...
It's also useful for multiple args: ``` def foo(*args): print args foo(1, 2, 3) # (1, 2, 3) # also legal t = (1, 2, 3) foo(*t) # (1, 2, 3) ``` And, you can use double asterisk for keyword arguments and dictionaries: ``` def foo(**kwargs): print kwargs foo(a=1, b=2) # {'a': 1, 'b': 2} # also legal d = {"a": ...
Python: Number of rows affected by cursor.execute("SELECT ...)
2,511,679
26
2010-03-24T21:52:54Z
2,511,718
70
2010-03-24T21:59:35Z
[ "python", "sql", "rows", "database" ]
How can I access the number of rows affected by: ``` cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'") ```
From [PEP 249](http://www.python.org/dev/peps/pep-0249/), which is usually implemented by Python database APIs: > Cursor Objects should respond to the following methods and attributes: > > [...] > > .rowcount > This read-only attribute specifies the number of rows that the last .execute\*() produced (for DQL stateme...
Python: Number of rows affected by cursor.execute("SELECT ...)
2,511,679
26
2010-03-24T21:52:54Z
2,512,521
34
2010-03-25T01:07:06Z
[ "python", "sql", "rows", "database" ]
How can I access the number of rows affected by: ``` cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'") ```
Try using `fetchone`: ``` cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'") result=cursor.fetchone() ``` `result` will hold a tuple with one element, the value of `COUNT(*)`. So to find the number of rows: ``` number_of_rows=result[0] ``` Or, if you'd rath...
Python: Number of rows affected by cursor.execute("SELECT ...)
2,511,679
26
2010-03-24T21:52:54Z
2,834,349
25
2010-05-14T13:08:27Z
[ "python", "sql", "rows", "database" ]
How can I access the number of rows affected by: ``` cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'") ```
The number of rows effected is returned from execute: ``` rows_affected=cursor.execute("SELECT ... ") ``` of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute: ``` cursor.execute("SELECT ... ") rows_affec...
Python: Number of rows affected by cursor.execute("SELECT ...)
2,511,679
26
2010-03-24T21:52:54Z
19,854,354
7
2013-11-08T08:14:09Z
[ "python", "sql", "rows", "database" ]
How can I access the number of rows affected by: ``` cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'") ```
In my opinion, the simplest way to get the amount of selected rows is the following: The cursor object returns a list with the results when using the fetch commands (fetchall(), fetchone(), fetchmany()). To get the selected rows just print the length of this list. But it just makes sense for fetchall(). ;-) Example: ...
Is there a recommended command for "hg bisect --command"?
2,511,704
8
2010-03-24T21:56:12Z
2,513,749
10
2010-03-25T07:37:08Z
[ "python", "mercurial" ]
I have an emergent bug that I've got to track down tomorrow. I know a previous hg revision which was good so I'm thinking about using hg bisect. However, I'm on Windows and don't want to get into DOS scripting. Ideally, I'd be able to write a Python unit test and have hg bisect use that. This is my first attempt. bi...
Thanks to all, especially to Will McCutchen. The solution that worked best is below. bisector.py ``` #!/usr/bin/env python import unittest class TestCase(unittest.TestCase): def test(self): # Raise an assertion error to mark the revision as bad pass if '__main__' == __name__: unittest.mai...
Matplotlib not showing up in Mac OSX
2,512,225
34
2010-03-24T23:36:24Z
2,512,358
30
2010-03-25T00:12:07Z
[ "python", "osx", "matplotlib" ]
I am running Mac OSX 10.5.8. I installed matplotlib using macports. I get some examples from the matplotlib gallery like this one, without modification: <http://matplotlib.sourceforge.net/examples/api/unicode_minus.html> I run it, get no error, but the picture does not show up. In Linux Ubuntu I get it. Do you know ...
I can verify this on my end as well. To fix, here's what I did ``` sudo port install py25-matplotlib +cairo+gtk2 sudo port install py26-matplotlib +cairo+gtk2 ``` Also, we need to change the default backend to a GUI based one. Edit the file `~/.matplotlib/matplotlibrc`, and add: ``` backend: GTKCairo ``` --- Also...
how to merge 200 csv files in Python
2,512,386
22
2010-03-25T00:24:29Z
2,512,418
9
2010-03-25T00:35:48Z
[ "python", "csv", "merge" ]
Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?
``` fout=open("out.csv","a") for num in range(1,201): for line in open("sh"+str(num)+".csv"): fout.write(line) fout.close() ```
how to merge 200 csv files in Python
2,512,386
22
2010-03-25T00:24:29Z
2,512,425
9
2010-03-25T00:41:28Z
[ "python", "csv", "merge" ]
Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?
It depends what you mean by "merging" -- do they have the same columns? Do they have headers? For example, if they all have the same columns, and no headers, simple concatenation is sufficient (open the destination file for writing, loop over the sources opening each for reading, use [shutil.copyfileobj](http://docs.py...
how to merge 200 csv files in Python
2,512,386
22
2010-03-25T00:24:29Z
2,512,572
34
2010-03-25T01:20:10Z
[ "python", "csv", "merge" ]
Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?
As ghostdog74 said, but this time with headers: ``` fout=open("out.csv","a") # first file: for line in open("sh1.csv"): fout.write(line) # now the rest: for num in range(2,201): f = open("sh"+str(num)+".csv") f.next() # skip the header for line in f: fout.write(line) f.close() # not re...
how to merge 200 csv files in Python
2,512,386
22
2010-03-25T00:24:29Z
5,876,058
17
2011-05-03T21:41:01Z
[ "python", "csv", "merge" ]
Guys, I here have 200 separate csv files named from SH (1) to SH (200). I want to merge them into a single csv file. How can I do it?
Why can't you just `sed 1d sh*.csv > merged.csv`? Sometimes you don't even have to use python!
How do I mock a class property with mox?
2,512,453
5
2010-03-25T00:48:25Z
2,519,772
9
2010-03-25T22:06:42Z
[ "python", "mocking", "properties", "mox" ]
I have a class: ``` class MyClass(object): @property def myproperty(self): return 'hello' ``` Using [`mox`](http://code.google.com/p/pymox/) and `py.test`, how do I mock out `myproperty`? I've tried: ``` mock.StubOutWithMock(myclass, 'myproperty') myclass.myproperty = 'goodbye' ``` and ``` mock.St...
When stubbing out class attributes `mox` uses `setattr`. Thus ``` mock.StubOutWithMock(myinstance, 'myproperty') myinstance.myproperty = 'goodbye' ``` is equivalent to ``` # Save old attribute so it can be replaced during teardown saved = getattr(myinstance, 'myproperty') # Replace the existing attribute with a mock...
Encoding gives "'ascii' codec can't encode character … ordinal not in range(128)"
2,513,027
13
2010-03-25T04:19:23Z
8,684,956
11
2011-12-30T23:14:10Z
[ "python", "django", "unicode", "character-encoding" ]
I am working through the Django RSS reader project [here](http://code.djangoproject.com/browser/djangoproject.com/django_website/apps/aggregator/bin/update_feeds.py). The RSS feed will read something like "OKLAHOMA CITY (AP) — James Harden let". The RSS feed's encoding reads encoding="UTF-8" so I believe I am passin...
If the data that you are receiving is, in fact, encoded in UTF-8, then it should be a sequence of bytes -- a Python 'str' object, in Python 2.X You can verify this with an assertion: ``` assert isinstance(content, str) ``` Once you know that that's true, you can move to the actual encoding. Python doesn't do transco...
redirect prints to log file
2,513,479
13
2010-03-25T06:25:21Z
2,513,489
21
2010-03-25T06:27:40Z
[ "python", "logging", "printing" ]
Okay. I have completed my first python program.It has around 1000 lines of code. During development I placed plenty of `print` statements before running a command using `os.system()` say something like, ``` print "running command",cmd os.system(cmd) ``` Now I have completed the program. I thought about commenting the...
You should take a look at [python logging module](http://docs.python.org/library/logging.html) --- EDIT: Sample code: ``` import logging if __name__ == "__main__": logging.basicConfig(level=logging.DEBUG, filename="logfile", filemode="a+", format="%(asctime)-15s %(levelname)-8s %(message...
redirect prints to log file
2,513,479
13
2010-03-25T06:25:21Z
2,513,511
19
2010-03-25T06:35:45Z
[ "python", "logging", "printing" ]
Okay. I have completed my first python program.It has around 1000 lines of code. During development I placed plenty of `print` statements before running a command using `os.system()` say something like, ``` print "running command",cmd os.system(cmd) ``` Now I have completed the program. I thought about commenting the...
Python lets you capture and assign sys.stdout - as mentioned - to do this: ``` old_stdout = sys.stdout log_file = open("message.log","w") sys.stdout = log_file print "this will be written to message.log" sys.stdout = old_stdout log_file.close() ```
redirect prints to log file
2,513,479
13
2010-03-25T06:25:21Z
2,516,480
7
2010-03-25T14:49:08Z
[ "python", "logging", "printing" ]
Okay. I have completed my first python program.It has around 1000 lines of code. During development I placed plenty of `print` statements before running a command using `os.system()` say something like, ``` print "running command",cmd os.system(cmd) ``` Now I have completed the program. I thought about commenting the...
* Next time, you'll be happier if instead of using `print` statements at all you use the `logging` module from the start. It provides the control you want and you can have it write to stdout while that's still where you want it. * Many people here have suggested redirecting stdout. *This is an ugly solution.* It mutate...
How to scroll text in Python/Curses subwindow?
2,515,244
14
2010-03-25T12:04:53Z
2,523,020
18
2010-03-26T11:55:42Z
[ "python", "scroll", "curses" ]
In my Python script which uses Curses, I have a subwin to which some text is assigned. Because the text length may be longer than the window size, the text should be scrollable. It doesn't seem that there is any CSS-"overflow" like attribute for Curses windows. The Python/Curses docs are also rather cryptic on this as...
OK with window.scroll it was too complicated to move the content of the window. Instead, curses.newpad did it for me. Create a pad: ``` mypad = curses.newpad(40,60) mypad_pos = 0 mypad.refresh(mypad_pos, 0, 5, 5, 10, 60) ``` Then you can scroll by increasing/decreasing mypad\_pos depending on the input from window.g...
Injecting variables into the caller's scope?
2,515,450
15
2010-03-25T12:37:44Z
2,516,425
7
2010-03-25T14:43:45Z
[ "python", "variables", "scope" ]
Can I define a function which, when called, inserts new locals into the caller's scope? I have a feeling that passing the caller's *locals()* into the function might work, but is there a way to do what I want *without* having to do this?
By Python's rules, you cannot alter your caller's `locals`; in the current implementations, if you try (e.g. with the black magic Anurag suggests) you will not get an exception (though I'd like to add that error check to some future version), but it will be essentially inoperative if your caller is a function (not if y...
Injecting variables into the caller's scope?
2,515,450
15
2010-03-25T12:37:44Z
7,028,618
13
2011-08-11T15:29:04Z
[ "python", "variables", "scope" ]
Can I define a function which, when called, inserts new locals into the caller's scope? I have a feeling that passing the caller's *locals()* into the function might work, but is there a way to do what I want *without* having to do this?
Check out the [inspect module](http://docs.python.org/library/inspect.html), it is used by [minimock](https://bitbucket.org/jab/minimock/src/b7acbfeadbd2/minimock.py#cl-169) to mock the caller's scope. This code ought to do what you want exactly: ``` import inspect def mess_with_caller(): stack = inspect.stack() ...
Changing python interpreter for emacs
2,515,754
9
2010-03-25T13:14:51Z
2,520,486
10
2010-03-26T00:46:42Z
[ "python", "emacs" ]
Emacs uses an older version of python(2.3) i have for the default python mode, is there a way for me to tell emacs to use the newer version that i have in my home directory? btw I'm using a red hat distro and dont have root privileges.
It is good habit to check **customize-group** of things you wanna tweak. Just do: ``` M-x customize-group RET python RET ``` you've got now multiple options of which one should be interesting: ``` Python Python Command ``` You can customize it there and Save for further sessions.
Perl for a Python programmer
2,515,814
18
2010-03-25T13:21:32Z
2,515,881
15
2010-03-25T13:29:39Z
[ "python", "perl" ]
I know Python (and a bunch of other languages) and I think it might be nice to learn Perl, even if it seems that most of the people is doing it [the other way around](http://stackoverflow.com/questions/2283034/python-for-a-perl-programmer). My main concern is not about the language itself (I think that part is always ...
One area where Perl is more "convenient" is using it for one liners. Python can be used to produced one liners, but often its "clunky" (or ugly). Note that Perl is renowned for its "terseness" or "short and concise", often at the expense of readability. So coming from Python, you have to learn to get used to it. Anoth...
Perl for a Python programmer
2,515,814
18
2010-03-25T13:21:32Z
2,516,511
14
2010-03-25T14:51:42Z
[ "python", "perl" ]
I know Python (and a bunch of other languages) and I think it might be nice to learn Perl, even if it seems that most of the people is doing it [the other way around](http://stackoverflow.com/questions/2283034/python-for-a-perl-programmer). My main concern is not about the language itself (I think that part is always ...
For best practices, check out [Perl Best Practices](http://books.google.com/books?id=gJf9tI2mytIC&lpg=PP1&dq=perl%20best%20practices&pg=PP1#v=onepage&q=&f=false) by Damian Conway. Not all of the recommended practices make sense, but most of them do. The [Perl::Critic](http://www.perlcritic.org/) module also helps with...
Perl for a Python programmer
2,515,814
18
2010-03-25T13:21:32Z
2,516,877
11
2010-03-25T15:31:18Z
[ "python", "perl" ]
I know Python (and a bunch of other languages) and I think it might be nice to learn Perl, even if it seems that most of the people is doing it [the other way around](http://stackoverflow.com/questions/2283034/python-for-a-perl-programmer). My main concern is not about the language itself (I think that part is always ...
* Have a look at [`Moose`](http://moose.perl.org). Its a *state of the art* OO framework akin to [`CLOS`](http://en.wikipedia.org/wiki/Common_Lisp_Object_System) and what will be available in [`Perl6`](http://en.wikipedia.org/wiki/Perl_6). It introduces the new(ish) concepts of [`roles`](http://search.cpan.org/dist/Moo...
scoping error in recursive closure
2,516,652
8
2010-03-25T15:07:43Z
2,516,870
12
2010-03-25T15:30:10Z
[ "python", "recursion", "scope", "closures" ]
why does this work: ``` def function1(): a = 10 def function2(): print...
The error doesn't seem to be very descriptive of the root problem. Mike explains the messages but that does not explain the root cause. The actual problem is that in python you cannot assign to closed over variables. So in function2 'a' is read only. When you assign to it you create a new variable which, as Mike point...
Python string comparison
2,516,787
4
2010-03-25T15:21:40Z
2,516,812
8
2010-03-25T15:23:59Z
[ "python", "string", "compare" ]
I have a python function that makes a subprocess call to a shell script that outputs 'true' or 'false'. I'm storing the output from `subprocess.communicate()` and trying to do `return output == 'true'` but it returns `False` every time. I'm not too familiar with python, but reading about string comparisons says you can...
Are you sure that there isn't a terminating line feed character, making your string contain `"true\n"`? That seems likely. You could try return `isdeployed.startswith("true")`, or some stripping.
Python | mktime overflow error
2,518,706
14
2010-03-25T19:26:53Z
2,518,828
17
2010-03-25T19:42:56Z
[ "python" ]
I have been search all over the net and couldn't find an appropriate solution for this issue ``` OverflowError: mktime argument out of range ``` The code that causes this exception ``` t = (1956, 3, 2, 0, 0, 0, 0, 0, 0) ser = time.mktime(t) ``` I would like to know the actual reason for this exception, some say t...
`time.mktime` calls the underlying `mktime` function from the platform's C library. For instance, the above code that you posted works perfectly well for me on Mac OS X, although it returns a negative number as the date is before the Unix epoch. So the reason is that your platform's `mktime` implementation probably doe...
best way to implement a deck for a card game in python
2,518,753
14
2010-03-25T19:32:55Z
2,518,806
19
2010-03-25T19:40:49Z
[ "python" ]
What is the best way to store the cards and suits in python so that I can hold a reference to these values in another variable? For example, if I have a list called hand (cards in players hand), how could I hold values that could refer to the names of suits and values of specific cards, and how would these names and v...
Poker servers tend to use a 2-character string to identify each card, which is nice because it's easy to deal with programmatically and just as easy to read for a human. ``` >>> import random >>> import itertools >>> SUITS = 'cdhs' >>> RANKS = '23456789TJQKA' >>> DECK = tuple(''.join(card) for card in itertools.produc...
Importing a function/class from a Python module of the same name
2,519,511
6
2010-03-25T21:24:26Z
2,520,564
7
2010-03-26T01:12:46Z
[ "python", "import", "module" ]
I have a Python package `mymodule` with a sub-package `utils` (i.e. a subdirectory which contains modules each with a function). The functions have the same name as the file/module in which they live. I would like to be able to access the functions as follows, `from mymodule.utils import a_function` Strangely howeve...
Do your utils functions need to import other utils functions? (or import other modules that import other utils functions). Suppose for example that a\_function.py contains contains "from mymodule.utils import b\_function". Here's your utils.py with a bunch of extra comments: ``` # interpreter is executing utils.py # R...
Are strings pooled in Python
2,519,580
7
2010-03-25T21:33:32Z
2,519,616
15
2010-03-25T21:40:19Z
[ "python", "string", "memory", "singleton", "string-interning" ]
Does Python have a pool of all strings and are they (strings) singletons there? More precise, in the following code one or two strings were created in memory: ``` a = str(num) b = str(num) ``` ?
Strings are immutable in Python, so the implementation can decide whether to intern (that's a term often associated with C#, meaning that some strings are stored in a pool) strings or not. In your example, you're dynamically creating strings. CPython does *not always* look into the pool to detect whether the string is...
Writing a telnet client
2,519,598
9
2010-03-25T21:37:48Z
2,519,610
10
2010-03-25T21:39:31Z
[ "python", "c", "telnet" ]
HI, I have a device that exposes a telnet interface which you can log into using a username and password and then manipulate the working of the device. I have to write a C program that hides the telnet aspect from the client and instead provides an interface for the user to control the device. What would be a good w...
If Python is an option you could use [telnetlib](http://docs.python.org/library/telnetlib.html). [Code example](http://docs.python.org/library/telnetlib.html#telnet-example): ``` #!/usr/bin/env python import getpass import sys import telnetlib HOST = "localhost" user = raw_input("Enter your remote account: ") passwo...
Python code to use a regular expression to make sure a string is alphanumeric plus . - _
2,519,670
4
2010-03-25T21:51:53Z
2,519,701
13
2010-03-25T21:56:22Z
[ "python", "regex", "alphanumeric" ]
I looked and searched and couldn't find what I needed although I think it should be simple (if you have any Python experience, which I don't). Given a string, I want to verify, in Python, that it contains ONLY alphanumeric characters: `a-zA-Z0-9` and `.` `_` `-` examples: Accepted: `bill-gates` `Steve_Jobs` `Micr...
[`re.match`](http://docs.python.org/library/re.html#re.match) does not return a boolean; it returns a `MatchObject` on a match, or `None` on a non-match. ``` >>> re.match("^[a-zA-Z0-9_.-]+$", "hello") <_sre.SRE_Match object at 0xb7600250> >>> re.match("^[a-zA-Z0-9_.-]+$", " ") >>> print re.match("^[a-zA-Z0-9_.-]+$"...
Generate unique hashes for django models
2,519,896
17
2010-03-25T22:29:11Z
2,519,931
7
2010-03-25T22:34:34Z
[ "python", "django", "hash", "random" ]
I want to use unique hashes for each model rather than ids. I implemented the following function to use it across the board easily. ``` import random,hashlib from base64 import urlsafe_b64encode def set_unique_random_value(model_object,field_name='hash_uuid',length=5,use_sha=True,urlencode=False): while 1: ...
Use your database engine's UUID support instead of making up your own hash. Almost everything beyond SQLite supports them, so there's little reason to not use them.
Generate unique hashes for django models
2,519,896
17
2010-03-25T22:29:11Z
2,520,136
29
2010-03-25T23:20:33Z
[ "python", "django", "hash", "random" ]
I want to use unique hashes for each model rather than ids. I implemented the following function to use it across the board easily. ``` import random,hashlib from base64 import urlsafe_b64encode def set_unique_random_value(model_object,field_name='hash_uuid',length=5,use_sha=True,urlencode=False): while 1: ...
I do not like this bit: ``` uuid = uuid[:5] ``` In the best scenario (uuid are uniformly distributed) you will get a collision with probability greater than 0.5 after 1k of elements! It is because of the [birthday problem](http://en.wikipedia.org/wiki/Birthday_problem). In a brief it is proven that the probability o...
Generate unique hashes for django models
2,519,896
17
2010-03-25T22:29:11Z
2,523,320
13
2010-03-26T12:53:37Z
[ "python", "django", "hash", "random" ]
I want to use unique hashes for each model rather than ids. I implemented the following function to use it across the board easily. ``` import random,hashlib from base64 import urlsafe_b64encode def set_unique_random_value(model_object,field_name='hash_uuid',length=5,use_sha=True,urlencode=False): while 1: ...
The ugly: > import random [From the documentation:](http://docs.python.org/library/random.html) > This module implements **pseudo-random** number generators for various distributions. If anything, please use [os.urandom](http://docs.python.org/library/os.html?highlight=urandom#os.urandom) > Return a string of n ra...
What algorithms are suitable for this simple machine learning problem?
2,520,018
13
2010-03-25T22:54:07Z
2,520,801
8
2010-03-26T02:21:55Z
[ "python", "artificial-intelligence", "machine-learning", "classification", "neural-network" ]
I have a what I think is a simple machine learning question. Here is the basic problem: I am repeatedly given a new object and a list of descriptions about the object. For example: new\_object: `'bob'` new\_object\_descriptions: `['tall','old','funny']`. I then have to use some kind of machine learning to find previou...
An algorithm that seems to meet your requirements (and is perhaps similar to what John the Statistician is suggesting) is [Semantic Hashing](http://www.cs.toronto.edu/~rsalakhu/papers/semantic_final.pdf). The basic idea is that it trains a deep belief network (a type of neural network that some have called 'neural netw...
Purpose of Zope Interfaces?
2,521,189
32
2010-03-26T04:45:26Z
2,521,650
22
2010-03-26T07:20:22Z
[ "python", "interface", "zope", "zope.interface" ]
I have started using Zope interfaces in my code, and as of now, they are really only documentation. I use them to specify what attributes the class should possess, explicitly implement them in the appropriate classes and explicitly check for them where I expect one. This is fine, but I would like them to do more if pos...
You can actually test if your object or class implements your interface. For that you can use `verify` module (you would normally use it in your tests): ``` >>> from zope.interface import Interface, Attribute, implements >>> class IFoo(Interface): ... x = Attribute("The X attribute") ... y = Attribute("The Y a...
Purpose of Zope Interfaces?
2,521,189
32
2010-03-26T04:45:26Z
2,642,063
18
2010-04-15T01:02:30Z
[ "python", "interface", "zope", "zope.interface" ]
I have started using Zope interfaces in my code, and as of now, they are really only documentation. I use them to specify what attributes the class should possess, explicitly implement them in the appropriate classes and explicitly check for them where I expect one. This is fine, but I would like them to do more if pos...
Zope interfaces can provide a useful way to decouple two pieces of code that shouldn't depend on each other. Say we have a component that knows how to print a greeting in module a.py: ``` >>> class Greeter(object): ... def greet(self): ... print 'Hello' ``` And some code that needs to print a greeting in...
Purpose of Zope Interfaces?
2,521,189
32
2010-03-26T04:45:26Z
2,840,774
44
2010-05-15T16:05:57Z
[ "python", "interface", "zope", "zope.interface" ]
I have started using Zope interfaces in my code, and as of now, they are really only documentation. I use them to specify what attributes the class should possess, explicitly implement them in the appropriate classes and explicitly check for them where I expect one. This is fine, but I would like them to do more if pos...
Where I work, we use Interfaces so that we can use ZCA, or the [Zope Component Architecture](http://www.muthukadan.net/docs/zca.html), which is a whole framework for making components that are swappable and pluggable using `Interface`s. We use ZCA so that we can cope with all manner of per-client customisations without...
Avoid IF statement after condition has been met
2,521,558
4
2010-03-26T06:54:05Z
2,521,564
9
2010-03-26T06:56:46Z
[ "python", "performance", "if-statement" ]
I have a division operation inside a cycle that repeats many times. It so happens that in the first few passes through the loop (more or less first 10 loops) the divisor is zero. Once it gains value, a div by zero error is not longer possible. I have an `if` condition to test the divisor value in order to avoid the di...
Don't worry. An `if (a != 0)` is cheap. The alternative (if you really want one) could be to split the loop into two, and exit the first one once the divisor gets its value. But that sounds like it would make the code unnecessarily complex (difficult to read).
Proper way to set object instance variables
2,521,753
9
2010-03-26T07:52:32Z
2,521,792
13
2010-03-26T08:02:48Z
[ "python", "oop", "pylons" ]
I'm writing a class to insert users into a database, and before I get too far in, I just want to make sure that my OO approach is clean: ``` class User(object): def setName(self,name): #Do sanity checks on name self._name = name def setPassword(self,password): #Check password length...
It's generally correct, AFAIK, but you could clean it up with [properties](http://docs.python.org/library/functions.html#property). ``` class User(object): def _setName(self, name=None): self._name = name def _getName(self): return self._name def _setPassword(self, password): sel...
Get a list/tuple/dict of the arguments passed to a function?
2,521,901
30
2010-03-26T08:30:54Z
2,521,937
35
2010-03-26T08:38:23Z
[ "python", "function", "arguments" ]
Given the following function: ``` def foo(a, b, c): pass ``` How would one obtain a list/tuple/dict/etc of the arguments passed in, **without having to build the structure myself**? Specifically, I'm looking for Python's version of JavaScript's `arguments` keyword or PHP's `func_get_args()` method. What I'm **n...
You can use `locals()` to get a dict of the local variables in your function, like this: ``` def foo(a, b, c): print locals() >>> foo(1, 2, 3) {'a': 1, 'c': 3, 'b': 2} ``` This is a bit hackish, however, as `locals()` returns all variables in the local scope, not only the arguments passed to the function, so if ...
Cost of exception handlers in Python
2,522,005
33
2010-03-26T08:52:20Z
2,522,013
46
2010-03-26T08:54:50Z
[ "python", "performance", "exception", "micro-optimization" ]
In [another question](http://stackoverflow.com/questions/2521558/avoid-if-statement-after-condition-has-been-met), the accepted answer suggested replacing a (very cheap) if statement in Python code with a try/except block to improve performance. Coding style issues aside, and assuming that the exception is never trigg...
Why don't you measure it using the [`timeit` module](http://docs.python.org/library/timeit.html)? That way you can see whether it's relevant to your application. OK, so I've just tried the following: ``` import timeit statements=["""\ try: b = 10/a except ZeroDivisionError: pass""", """\ if a: b = 10/a""...
Cost of exception handlers in Python
2,522,005
33
2010-03-26T08:52:20Z
2,529,713
18
2010-03-27T14:56:19Z
[ "python", "performance", "exception", "micro-optimization" ]
In [another question](http://stackoverflow.com/questions/2521558/avoid-if-statement-after-condition-has-been-met), the accepted answer suggested replacing a (very cheap) if statement in Python code with a try/except block to improve performance. Coding style issues aside, and assuming that the exception is never trigg...
This question is actually answered in the [Design and History FAQ](http://docs.python.org/2/faq/design.html#how-fast-are-exceptions): > A try/except block is extremely efficient if no exceptions are raised > Actually catching an exception is expensive.
Cost of exception handlers in Python
2,522,005
33
2010-03-26T08:52:20Z
3,743,528
7
2010-09-18T21:12:39Z
[ "python", "performance", "exception", "micro-optimization" ]
In [another question](http://stackoverflow.com/questions/2521558/avoid-if-statement-after-condition-has-been-met), the accepted answer suggested replacing a (very cheap) if statement in Python code with a try/except block to improve performance. Coding style issues aside, and assuming that the exception is never trigg...
This question is misleading. If you assume the exception is *never* triggered, neither one is optimal code. If you assume the exception is triggered as part of an error condition, you are already outside the realm of wanting optimal code (and you probably aren't handling it at a fine-grained level like that anyway). ...
Python - Is a dictionary slow to find frequency of each character?
2,522,152
23
2010-03-26T09:31:23Z
2,522,226
16
2010-03-26T09:42:41Z
[ "python", "algorithm", "probability", "frequency" ]
I am trying to find a frequency of each symbol in any given text using an algorithm of O(n) complexity. My algorithm looks like: ``` s = len(text) P = 1.0/s freqs = {} for char in text: try: freqs[char]+=P except: freqs[char]=P ``` but I doubt that this dictionary-method is fast enough, b...
How about avoiding float operations inside the loop and do it after everything is done? By that way, you could just do +1 everytime, and its should be faster. And better use collections.defaultdict as S.Lott advised. ``` freqs=collections.defaultdict(int) for char in text: freqs[char]+=1 ``` Or You may want to...
Python - Is a dictionary slow to find frequency of each character?
2,522,152
23
2010-03-26T09:31:23Z
2,525,617
44
2010-03-26T18:04:25Z
[ "python", "algorithm", "probability", "frequency" ]
I am trying to find a frequency of each symbol in any given text using an algorithm of O(n) complexity. My algorithm looks like: ``` s = len(text) P = 1.0/s freqs = {} for char in text: try: freqs[char]+=P except: freqs[char]=P ``` but I doubt that this dictionary-method is fast enough, b...
## Performance comparison Note: time in the table doesn't include the time it takes to load files. ``` | approach | american-english, | big.txt, | time w.r.t. defaultdict | | | time, seconds | time, seconds | | |----------------+-------------------+---------------...
Python - Is a dictionary slow to find frequency of each character?
2,522,152
23
2010-03-26T09:31:23Z
2,532,564
10
2010-03-28T10:35:48Z
[ "python", "algorithm", "probability", "frequency" ]
I am trying to find a frequency of each symbol in any given text using an algorithm of O(n) complexity. My algorithm looks like: ``` s = len(text) P = 1.0/s freqs = {} for char in text: try: freqs[char]+=P except: freqs[char]=P ``` but I doubt that this dictionary-method is fast enough, b...
I've written Char Counter C Extension to Python, looks like **300x** faster than `collections.Counter` and **150x** faster than `collections.default(int)` ``` C Char Counter : 0.0469999313354 s 93 chars {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8, ``` Here ...
Advanced Python list comprehension
2,522,503
9
2010-03-26T10:30:45Z
2,522,531
12
2010-03-26T10:35:43Z
[ "python", "list-comprehension" ]
Given two lists: ``` chars = ['ab', 'bc', 'ca'] words = ['abc', 'bca', 'dac', 'dbc', 'cba'] ``` how can you use list comprehensions to generate a filtered list of `words` by the following condition: given that each word is of length `n` and `chars` is of length `n` as well, the filtered list should include only words...
``` [w for w in words if all([w[i] in chars[i] for i in range(len(w))])] ```
Advanced Python list comprehension
2,522,503
9
2010-03-26T10:30:45Z
2,522,553
19
2010-03-26T10:40:26Z
[ "python", "list-comprehension" ]
Given two lists: ``` chars = ['ab', 'bc', 'ca'] words = ['abc', 'bca', 'dac', 'dbc', 'cba'] ``` how can you use list comprehensions to generate a filtered list of `words` by the following condition: given that each word is of length `n` and `chars` is of length `n` as well, the filtered list should include only words...
``` >>> [word for word in words if all(l in chars[i] for i, l in enumerate(word))] ['abc', 'bca'] ```
Assignment to None
2,522,854
15
2010-03-26T11:29:31Z
2,522,856
21
2010-03-26T11:30:07Z
[ "python" ]
I have a function which returns 3 numbers, e.g.: ``` def numbers(): return 1,2,3 ``` usually I call this function to receive all three returned numbers e.g.: ``` a, b, c = numbers() ``` However, I have one case in which I only need the first returned number. I tried using: ``` a, None, None = numbers() ``` But...
``` a, _, _ = numbers() ``` is a pythonic way to do this. In Python 3, you could also use: ``` a, *_ = numbers() ``` To clarify `_` is a normal variable name in Python, except it is conventionally used to refer to non-important variables.
Assignment to None
2,522,854
15
2010-03-26T11:29:31Z
2,522,898
9
2010-03-26T11:35:47Z
[ "python" ]
I have a function which returns 3 numbers, e.g.: ``` def numbers(): return 1,2,3 ``` usually I call this function to receive all three returned numbers e.g.: ``` a, b, c = numbers() ``` However, I have one case in which I only need the first returned number. I tried using: ``` a, None, None = numbers() ``` But...
Another way is of course `a=numbers()[0]`, if you do not want to declare another variable. Having said this though, I generally use \_ myself.
Easiest ways to generate graphs from Python?
2,523,689
6
2010-03-26T13:49:14Z
2,523,705
7
2010-03-26T13:51:12Z
[ "python", "graph", "visualization", "google-visualization" ]
I'm using Python to process CSV files filled with data that I want to run calculations on, and then graph. I'm looking for a library to use that I can send processed CSV information to, or a dict of some sort, and then choose different graphing styles with. Does anyone have any recommendations?
I'm personally using [matplotlib](http://matplotlib.sourceforge.net/) and am very happy with it.
How to connect a variable to Entry widget?
2,524,031
8
2010-03-26T14:38:26Z
2,524,242
12
2010-03-26T15:07:24Z
[ "python", "variables", "tkinter", "validation", "entry" ]
I'm trying to associate a variable with a Tkinter entry widget, in a way that: 1. Whenever I change the value (the "content") of the entry, mainly by typing something into it, the variable automatically gets assigned the value of what I've typed. Without me having to push a button "Update value " or something like tha...
I think you want something like this. In the example below, I created a variable `myvar` and assigned it to be `textvariable` of both a `Label` and `Entry` widgets. This way both are coupled and changes in the Entry widget will reflect automatically in Label. You can also [set trace](http://effbot.org/tkinterbook/vari...
Entity references and lxml
2,524,299
8
2010-03-26T15:14:23Z
2,524,627
19
2010-03-26T15:54:11Z
[ "python", "xml", "lxml" ]
Here's the code I have: ``` from cStringIO import StringIO from lxml import etree xml = StringIO('''<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE root [ <!ENTITY test "This is a test"> ]> <root> <sub>&test;</sub> </root>''') d1 = etree.parse(xml) print '%r' % d1.find('/sub').text parser = etree.XMLParser(resol...
The "unresolved" Entity is left as child node of the element node `sub` ``` >>> print d2.find('/sub')[0] &test; >>> d2.find('/sub').getchildren() [&test;] ```
How do I join three tables with SQLalchemy and keeping all of the columns in one of the tables?
2,524,600
7
2010-03-26T15:52:05Z
2,527,255
10
2010-03-26T22:44:11Z
[ "python", "sql", "sqlite", "sqlalchemy" ]
So, I have three tables: The class defenitions: ``` engine = create_engine('sqlite://test.db', echo=False) SQLSession = sessionmaker(bind=engine) Base = declarative_base() class Channel(Base): __tablename__ = 'channel' id = Column(Integer, primary_key = True) title = Column(String) description = Col...
**Option-1:** `Subscription` is just a many-to-many relation object, and I would suggest that you model it as such rather then as a separate class. See [Configuring Many-to-Many Relationships](http://www.sqlalchemy.org/docs/reference/ext/declarative.html#configuring-many-to-many-relationships) documentation of `SQLAlc...
Machine Learning Algorithm for Predicting Order of Events?
2,524,608
31
2010-03-26T15:52:17Z
2,525,149
20
2010-03-26T17:04:07Z
[ "python", "compression", "machine-learning", "neural-network", "evolutionary-algorithm" ]
Simple machine learning question. Probably numerous ways to solve this: There is an **infinite** stream of 4 possible events: `'event_1', 'event_2', 'event_4', 'event_4'` The events do not come in in completely random order. We will assume that there are some complex patterns to the order that most events come in, a...
This is essentially a sequence prediction problem, so you want Recurrent neural networks or hidden Markov models. If you only have a fixed time to look back, time window approaches might suffice. You take the sequence data and split it into overlapping windows of length n. (eg. you split a sequence ABCDEFG into ABC, B...
Machine Learning Algorithm for Predicting Order of Events?
2,524,608
31
2010-03-26T15:52:17Z
2,525,170
10
2010-03-26T17:06:43Z
[ "python", "compression", "machine-learning", "neural-network", "evolutionary-algorithm" ]
Simple machine learning question. Probably numerous ways to solve this: There is an **infinite** stream of 4 possible events: `'event_1', 'event_2', 'event_4', 'event_4'` The events do not come in in completely random order. We will assume that there are some complex patterns to the order that most events come in, a...
Rather than keeping a full history, one can keep ***aggregated information*** about the past (along with a relatively short sliding history, to be used as input to the Predictor logic). A tentative implementation could go like this: In a nutshell: **Managing a set of Markov chains *of increasing order*, and *grading...
Python: try statement in a single line
2,524,853
31
2010-03-26T16:21:19Z
2,524,880
26
2010-03-26T16:26:17Z
[ "python", "exception-handling" ]
Is there a way in python to turn a try/except into a single line? something like... ``` b = 'some variable' a = c | b #try statement goes here ``` Where `b` is a declared variable and `c` is not... so `c` would throw an error and `a` would become `b`...
There is no way to compress a `try`/`except` block onto a single line in Python. Also, it is a bad thing not to know whether a variable exists in Python, like you would in some other dynamic languages. The safer way (and the prevailing style) is to set all variables to something. If they might not get set, set them to...
Python: try statement in a single line
2,524,853
31
2010-03-26T16:21:19Z
8,061,176
34
2011-11-09T06:26:30Z
[ "python", "exception-handling" ]
Is there a way in python to turn a try/except into a single line? something like... ``` b = 'some variable' a = c | b #try statement goes here ``` Where `b` is a declared variable and `c` is not... so `c` would throw an error and `a` would become `b`...
This is terribly hackish, but I've used it at the prompt when I wanted to write up a sequence of actions for debugging: ``` exec "try: some_problematic_thing()\nexcept: problem=sys.exc_info()" print "The problem is %s" % problem[1] ``` For the most part, I'm not at all bothered by the no-single-line-try-except restri...
Regex for [a-zA-Z0-9\-] with dashes allowed in between but not at the start or end
2,525,327
5
2010-03-26T17:27:31Z
2,525,339
14
2010-03-26T17:29:07Z
[ "python", "regex" ]
# Update: This question was an epic failure, but here's the working solution. It's based on Gumbo's answer (Gumbo's was close to working so I chose it as the accepted answer): ### Solution: ``` r'(?=[a-zA-Z0-9\-]{4,25}$)^[a-zA-Z0-9]+(\-[a-zA-Z0-9]+)*$' ``` # Original Question (albeit, after 3 edits) I'm using Pyth...
Try this regular expression: ``` ^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$ ``` This regular expression does only allow hyphens to separate sequences of one or more characters of `[a-zA-Z0-9]`. --- **Edit**    Following up your comment: The expression `(…)*` allows the part inside the group to be repeated zero or more ti...
How to write the Visitor Pattern for Abstract Syntax Tree in Python?
2,525,677
17
2010-03-26T18:14:07Z
2,525,771
10
2010-03-26T18:32:54Z
[ "python", "parsing", "compiler-construction", "abstract-syntax-tree", "visitor" ]
My collegue suggested me to write a visitor pattern to navigate the AST. Can anyone tell me more how would I start writing it? As far as I understand, each Node in AST would have `visit()` method (?) that would somehow get called (from where?). That about concludes my understanding. To simplify everything, suppose I ...
See [the docs](http://docs.python.org/library/ast.html?highlight=ast#ast.NodeVisitor) for `ast.NodeVisitor`, e.g. a crude possibility might be: ``` import ast class MyVisitor(ast.NodeVisitor): def visit_BinaryOp(self, node): self.visit(node.left) print node.op, self.visit(node.right) def visit_Num(sel...
How to write the Visitor Pattern for Abstract Syntax Tree in Python?
2,525,677
17
2010-03-26T18:14:07Z
2,526,397
8
2010-03-26T20:09:28Z
[ "python", "parsing", "compiler-construction", "abstract-syntax-tree", "visitor" ]
My collegue suggested me to write a visitor pattern to navigate the AST. Can anyone tell me more how would I start writing it? As far as I understand, each Node in AST would have `visit()` method (?) that would somehow get called (from where?). That about concludes my understanding. To simplify everything, suppose I ...
Wikipedia has a great overview of [how the Visitor pattern works](http://en.wikipedia.org/wiki/Visitor_pattern#Example), although the sample implementation that they use is in Java. You can easily port that to Python, though, no? Basically, you want to implement a mechanism for [double dispatch](http://en.wikipedia.or...
Proper way in Python to raise errors while setting variables
2,525,845
11
2010-03-26T18:45:02Z
2,525,936
9
2010-03-26T18:57:32Z
[ "python", "error-handling" ]
What is the proper way to do error-checking in a class? Raising exceptions? Setting an instance variable dictionary "errors" that contains all the errors and returning it? Is it bad to print errors from a class? Do I have to return False if I'm raising an exception? Just want to make sure that I'm doing things right....
The standard way of signalling an error in python is to raise an exception and let the calling code handle it. Either let the NameError & TypeError carry on upwards, or catch them and raise an InvalidPassword exception that you define. While it is possible to return a success/fail flag or error code from the function ...
Proper way in Python to raise errors while setting variables
2,525,845
11
2010-03-26T18:45:02Z
2,526,154
17
2010-03-26T19:30:22Z
[ "python", "error-handling" ]
What is the proper way to do error-checking in a class? Raising exceptions? Setting an instance variable dictionary "errors" that contains all the errors and returning it? Is it bad to print errors from a class? Do I have to return False if I'm raising an exception? Just want to make sure that I'm doing things right....
Your code is out of a context so is not obvious the right choice. Following some tips: * Don't use `NameError` exception, it is only used when a name, as the exception itself said, is not found in the local or global scope, use `ValueError` or `TypeError` if the exception concerns the value or the type of the paramete...
I need a simple command line program to transform XML using an XSL Stylesheet
2,526,681
15
2010-03-26T20:55:22Z
2,526,724
13
2010-03-26T21:02:38Z
[ "java", "python", "xml", "osx", "xslt" ]
I am on OSX Snow Leopard (10.6.2) I can install anything I need to. I would preferably like a Python or Java solution. I have searched on Google and found lots of information on writing my own program to do this, but this is a just a quick and dirty experiment so I don't want to invest a lot of time on writing a bunch ...
I'd recommend [Saxon](http://sourceforge.net/projects/saxon/), which can be run from the command line like so: ``` java -jar /path/to/saxon.jar xmlfile xslfile ```
I need a simple command line program to transform XML using an XSL Stylesheet
2,526,681
15
2010-03-26T20:55:22Z
2,528,244
18
2010-03-27T05:23:42Z
[ "java", "python", "xml", "osx", "xslt" ]
I am on OSX Snow Leopard (10.6.2) I can install anything I need to. I would preferably like a Python or Java solution. I have searched on Google and found lots of information on writing my own program to do this, but this is a just a quick and dirty experiment so I don't want to invest a lot of time on writing a bunch ...
Have you tried '*xsltproc*'? It's probably already installed. <http://xmlsoft.org/XSLT/xsltproc2.html>
Moon / Lunar Phase Algorithm
2,526,815
24
2010-03-26T21:16:21Z
2,526,824
12
2010-03-26T21:18:51Z
[ "python", "c", "algorithm", "calendar", "astronomy" ]
Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year? Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page. **Update:** I should have qualified my stat...
I think you searched on wrong google: * <http://home.att.net/~srschmitt/zenosamples/zs_lunarphasecalc.html> * <http://www.voidware.com/moon_phase.htm> * <http://www.ben-daglish.net/moon.shtml> * <http://www.faqs.org/faqs/astronomy/faq/part3/section-15.html>
Moon / Lunar Phase Algorithm
2,526,815
24
2010-03-26T21:16:21Z
2,531,541
14
2010-03-28T01:03:41Z
[ "python", "c", "algorithm", "calendar", "astronomy" ]
Does anyone know an algorithm to either calculate the moon phase or age on a given date or find the dates for new/full moons in a given year? Googling tells me the answer is in some Astronomy book, but I don't really want to buy a whole book when I only need a single page. **Update:** I should have qualified my stat...
I ported some code to Python for this a while back. I was going to just link to it, but it turns out that it fell off the web in the meantime, so I had to go dust it off and upload it again. See [moon.py](http://bazaar.launchpad.net/~keturn/py-moon-phase/trunk/annotate/head:/moon.py) which is derived from [John Walker'...
Fastest way to uniqify a list in Python
2,527,405
18
2010-03-26T23:17:37Z
2,527,511
21
2010-03-26T23:45:22Z
[ "python", "performance", "list" ]
Fastest way to uniqify a list in Python without preserving order? I saw many complicated solutions on the Internet - could they be faster than simply: ``` list(set([a,b,c,a])) ```
``` set([a, b, c, a]) ``` Leave it in that form if possible.
Fastest way to uniqify a list in Python
2,527,405
18
2010-03-26T23:17:37Z
2,527,608
25
2010-03-27T00:11:40Z
[ "python", "performance", "list" ]
Fastest way to uniqify a list in Python without preserving order? I saw many complicated solutions on the Internet - could they be faster than simply: ``` list(set([a,b,c,a])) ```
Going to a set only works for lists such that all their items are *hashable* -- so e.g. in your example if `c = []`, the code you give will raise an exception. For non-hashable, but comparable items, sorting the list, then using `itertools.groupby` to extract the unique items from it, is the best available solution (O(...
Parsing a tweet to extract hashtags into an array in Python
2,527,892
9
2010-03-27T02:25:09Z
2,527,903
36
2010-03-27T02:30:27Z
[ "python", "arrays" ]
I am having a heck of a time taking the information in a tweet including hashtags, and pulling each hashtag into an array using Python. I am embarrassed to even put what I have been trying thus far. For example, "I love #stackoverflow because #people are very #helpful!" This should pull the 3 hashtags into an array.
A simple regex should do the job: ``` >>> import re >>> s = "I love #stackoverflow because #people are very #helpful!" >>> re.findall(r"#(\w+)", s) ['stackoverflow', 'people', 'helpful'] ``` Note though, that as suggested in other answers, this may also find non-hashtags, such as a hash location in a URL: ``` >>> re...
Parsing a tweet to extract hashtags into an array in Python
2,527,892
9
2010-03-27T02:25:09Z
2,527,954
11
2010-03-27T02:51:37Z
[ "python", "arrays" ]
I am having a heck of a time taking the information in a tweet including hashtags, and pulling each hashtag into an array using Python. I am embarrassed to even put what I have been trying thus far. For example, "I love #stackoverflow because #people are very #helpful!" This should pull the 3 hashtags into an array.
``` >>> s="I love #stackoverflow because #people are very #helpful!" >>> [i for i in s.split() if i.startswith("#") ] ['#stackoverflow', '#people', '#helpful!'] ```
Can SQLAlchemy DateTime Objects Only Be Naive?
2,528,189
22
2010-03-27T05:01:00Z
2,528,453
36
2010-03-27T07:01:27Z
[ "python", "datetime", "sqlalchemy" ]
I am working with SQLAlchemy, and I'm not yet sure which database I'll use under it, so I want to remain as DB-agnostic as possible. How can I store a timezone-aware datetime object in the DB without tying myself to a specific database? Right now, I'm making sure that times are UTC before I store them in the DB, and co...
There is a `timezone` parameter to [`DateTime`](http://docs.sqlalchemy.org/en/latest/core/types.html#sqlalchemy.types.DateTime) column time, so there is no problem with storing timezone-aware `datetime` objects. However I found convenient to convert stored `datetime` to UTC automatically with simple type decorator: ``...
Automatically deleting pyc files when corresponding py is moved (Mercurial)
2,528,283
14
2010-03-27T05:46:16Z
2,528,326
9
2010-03-27T06:04:28Z
[ "python", "mercurial" ]
(I foresaw this problem might happen 3 months ago, and was told to be diligent to avoid it. Yesterday, I was bitten by it, hard, and now that it has cost me real money, I am keen to fix it.) If I move one of my Python source files into another directory, I need to remember to tell Mercurial that it moved (`hg move`). ...
How about using an [update hook](http://hgbook.red-bean.com/read/handling-repository-events-with-hooks.html) on the server side? Put this in the repository's `.hg` directory's `hgrc` file: ``` [hooks] update = find . -name '*.pyc' | xargs rm ``` That will delete all .pyc files whenever you update on the server. If yo...
Automatically deleting pyc files when corresponding py is moved (Mercurial)
2,528,283
14
2010-03-27T05:46:16Z
2,528,509
16
2010-03-27T07:22:31Z
[ "python", "mercurial" ]
(I foresaw this problem might happen 3 months ago, and was told to be diligent to avoid it. Yesterday, I was bitten by it, hard, and now that it has cost me real money, I am keen to fix it.) If I move one of my Python source files into another directory, I need to remember to tell Mercurial that it moved (`hg move`). ...
1. Do not store .pyc files in the repository. 2. Automatize .pyc delete with: find . -name '\*.pyc' -delete 3. While develop use -B argument in Python.
Number of elements in Python Set
2,528,513
3
2010-03-27T07:23:28Z
2,528,526
8
2010-03-27T07:29:48Z
[ "python", "comparison", "dataset" ]
I have a list of phone numbers that have been dialed (nums\_dialed). I also have a set of phone numbers which are the number in a client's office (client\_nums) How do I efficiently figure out how many times I've called a particular client (total) For example: ``` >>>nums_dialed=[1,2,2,3,3] >>>client_nums=set([2,3]) ...
which client has `10^5` numbers in his office? Do you do work for an entire telephone company? Anyway: ``` print sum(1 for num in nums_dialed if num in client_nums) ``` That will give you as fast as possible the number. --- If you want to do it for multiple clients, using the same `nums_dialed` list, then you coul...
How do I get minidom to ignore namespaces?
2,528,852
9
2010-03-27T10:11:47Z
2,529,311
12
2010-03-27T12:52:59Z
[ "python", "xml" ]
I am using minidom in Python and I'd like getElementsByTagName() to match elements purely by tag-name and ignore any namespaces. The documents are being parsed by minidom.parseString(). Is it possible?
`getElementsByTagName` does match elements purely by tagName. Do you mean you want to match purely on localName? ie. the part of the tag name after the `:` (if any)? If so use the DOM Level 2 Core method [getElementsByTagNameNS](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-getElBTNNS): ``` els= document.getElem...
What is the difference between .get() and .fetch(1)
2,529,198
4
2010-03-27T12:10:58Z
2,529,314
8
2010-03-27T12:53:48Z
[ "python", "google-app-engine", "gae-datastore" ]
I have written an app and part of it is uses a URL parser to get certain data in a ReST type manner. So if you put /foo/bar as the path it will find all the bar items and if you put /foo it will return all items below foo So my app has a query like ``` data = Paths.all().filter('path =', self.request.path).get() ``` ...
You're looking at the docs for the wrong get() - you want the [get() method on the Query object](http://code.google.com/appengine/docs/python/datastore/queryclass.html#Query_get). In a nutshell, .fetch() always returns a list, while .get() returns the first result, or None if there are no results.
google app engine - auto increment
2,529,620
5
2010-03-27T14:30:37Z
2,529,655
18
2010-03-27T14:41:40Z
[ "python", "google-app-engine", "gae-datastore" ]
I am new to Google App Engine, I have this entites User class - user\_id - integer user\_name - string password - string I want to do auto increment for the user\_id,How I can do this?
You don't need to declare user\_id, GAE will create a unique key id every time you insert a new row. ``` class User(db.Model): user_name = db.StringProperty() password = db.StringProperty() ``` and to store a new user you will do: ``` user = User() user.user_name = "Username" user.password = "Password" user.put() ``...
Django Foreign key queries
2,530,158
10
2010-03-27T17:12:08Z
2,530,236
8
2010-03-27T17:34:36Z
[ "python", "django", "django-views", "django-queryset" ]
In the following model: ``` class header(models.Model): title = models.CharField(max_length = 255) created_by = models.CharField(max_length = 255) def __unicode__(self): return self.id() class criteria(models.Model): details = models.CharField(max_length = 255) headerid = models.Foreign...
First of all, don't use `id` in the names, because it is confusing. That field isn't the ID, it is the object itself. (If you have a field `ref` it automatically creates a field `ref_id`) ``` options.objects.filter(header=a_header) ``` You query it like any value, where some header instance is the value you are filte...
Django Foreign key queries
2,530,158
10
2010-03-27T17:12:08Z
2,530,376
19
2010-03-27T18:15:33Z
[ "python", "django", "django-views", "django-queryset" ]
In the following model: ``` class header(models.Model): title = models.CharField(max_length = 255) created_by = models.CharField(max_length = 255) def __unicode__(self): return self.id() class criteria(models.Model): details = models.CharField(max_length = 255) headerid = models.Foreign...
Ironfroggy is right, but there is another more obvious way to get the relevant `options` and `criteria` objects. Django automatically creates a 'reverse relation' for every foreign key pointing at a model, and that is usually the name of the related model plus `_set`. So: ``` mycriteria.options_set.all() mycriteria.he...
Help getting frame rate (fps) up in Python + Pygame
2,530,478
9
2010-03-27T18:43:18Z
2,530,745
7
2010-03-27T20:06:15Z
[ "python", "performance", "pygame", "frame-rate" ]
I am working on a little card-swapping world-travel game that I sort of envision as a cross between Bejeweled and the 10 Days geography board games. So far the coding has been going okay, but the frame rate is pretty bad... currently I'm getting low 20's on my Core 2 Duo. This is a problem since I'm creating the game f...
**Let events come to you with event.wait** Do you really need to do processing every tick? If not, use `pygame.event.wait` for your event loop to only process when an event comes in, and `pygame.time.set_timer` if you need periodic events like your `SecondEvent`. This means you won't be drawing many frames during sec...
Python: How to transfer varrying length arrays over a network connection
2,530,865
5
2010-03-27T20:44:59Z
2,530,899
7
2010-03-27T20:53:43Z
[ "python", "arrays", "networking", "unpack", "pack" ]
I need to transfer an array of varying length in which each element is a tuple of two integers. As an example: ``` path = [(1,1),(1,2)] path = [(1,1),(1,2),(2,2)] ``` I am trying to use pack and unpack, however, since the array is of varying length I don't know how to create a format such that both know the format. I...
While you can use pack and unpack, I'd recommend using something like [YAML](http://yaml.org/) or [JSON](http://www.json.org/) to transfer your data. * Pack and unpack can lead to difficult to debug errors and incompatibilities if you change your interface and have different versions trying to communicate with each ot...
Apply relative URL to an absolute URL
2,531,538
9
2010-03-28T01:03:05Z
2,531,554
9
2010-03-28T01:09:46Z
[ "python", "url" ]
I have an absolute URL, and the URL that a link on that page points to. Is there a builtin function to apply a relative URL to an absolute URL? Ie. "http://example.com/some/url", "/some/url/I/want/to/go/to" => "http://example.com/some/url/I/want/to/go/to"
[`urlparse.urljoin()`](http://docs.python.org/library/urlparse.html#urlparse.urljoin) does just this.
In Python, what are some examples of when decorators greatly simplify a task?
2,531,696
5
2010-03-28T02:31:54Z
2,531,719
8
2010-03-28T02:44:41Z
[ "python", "decorator" ]
Trying to find examples of when decorators might be really beneficial, and when not so much. Sample code is appreciated.
Decorators are simple syntax for a specific way to call higher-order functions, so if you're focusing just on the syntax it's unlikely to make a **great** difference. IOW, wherever you can say ``` @mydecorator def f(...): # body of f ``` you could identically say ``` def f(...): # body of f f = mydecorator(f) ``...