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
Installing MySQLdb on Mac OS X
5,531,958
9
2011-04-03T19:37:48Z
12,354,621
51
2012-09-10T15:16:13Z
[ "python", "mysql", "osx", "mysql-python" ]
I've spent several hours trying to install MySQLdb (the Python library) on Mac OS X Snow Leopard. I'm using [these instructions](http://stackoverflow.com/questions/1448429/how-to-install-mysqldb-python-data-access-library-to-mysql-on-mac-os-x) from SO. I keep getting an error, so I've tried using MacPorts (as one of th...
`sudo pip install mysql-python` worked for me in 10.8.1.
Delete files with python through OS shell
5,532,498
7
2011-04-03T21:02:26Z
5,532,521
24
2011-04-03T21:06:02Z
[ "python", "file" ]
Im Tyring to Delete all Files in E:. with wildcard. ``` E:\test\*.txt ``` I would ask rather than test the os.walk. In windows.
The way you would do this is use the [`glob`](http://docs.python.org/library/glob.html) module: ``` import glob import os for fl in glob.glob("E:\\test\\*.txt"): #Do what you want with the file os.remove(fl) ```
Delete files with python through OS shell
5,532,498
7
2011-04-03T21:02:26Z
5,918,298
8
2011-05-07T00:23:56Z
[ "python", "file" ]
Im Tyring to Delete all Files in E:. with wildcard. ``` E:\test\*.txt ``` I would ask rather than test the os.walk. In windows.
A slightly verbose writing of another method ``` import os dir = "E:\\test" files = os.listdir(dir) for file in files: if file.endswith(".txt"): os.remove(os.path.join(dir,file)) ``` Or ``` import os [os.remove(os.path.join("E:\\test",f)) for f in os.listdir("E:\\test") if f.endswith(".txt")] ```
Automatic indentation for Python in Notepad++
5,532,549
14
2011-04-03T21:10:25Z
5,532,767
8
2011-04-03T21:49:54Z
[ "python", "notepad++", "indentation", "auto-indent" ]
I've been googling lots and this is getting really frustrating. It doesn't act like idle. Example: ``` else: name = 'World' print 'Howdy', name print 'yay' ``` but in Notepad++ ``` else: # i press enter and this is what it does lands me here ``` But I want to be able to do like in idle: after the `:`...
I played a bit with python in Notepad++ and I had a problem with the tab. Since in python your indentation is really important but notepad ++ put space instead of a tab. So to change to tab you need to go in notepad ++ Menu **Settings > Preferences...** then select **Tab Settings** Then select **python** in the **Tab ...
Automatic indentation for Python in Notepad++
5,532,549
14
2011-04-03T21:10:25Z
6,492,582
31
2011-06-27T12:06:19Z
[ "python", "notepad++", "indentation", "auto-indent" ]
I've been googling lots and this is getting really frustrating. It doesn't act like idle. Example: ``` else: name = 'World' print 'Howdy', name print 'yay' ``` but in Notepad++ ``` else: # i press enter and this is what it does lands me here ``` But I want to be able to do like in idle: after the `:`...
This is what you want: Settings > Preferences > MISC. > Auto-Indent (checkbox) -- Sometimes people ask, "How can I do x in program y?" I have a dream that one day "Use program z instead" will not be the most popular response.
Automatic indentation for Python in Notepad++
5,532,549
14
2011-04-03T21:10:25Z
16,571,149
10
2013-05-15T17:13:18Z
[ "python", "notepad++", "indentation", "auto-indent" ]
I've been googling lots and this is getting really frustrating. It doesn't act like idle. Example: ``` else: name = 'World' print 'Howdy', name print 'yay' ``` but in Notepad++ ``` else: # i press enter and this is what it does lands me here ``` But I want to be able to do like in idle: after the `:`...
I found the Python Indent plugin on the official plugin page, and it worked fine! <http://docs.notepad-plus-plus.org/index.php/Plugin_Central#P>
Python global variable
5,532,890
11
2011-04-03T22:11:02Z
5,532,906
24
2011-04-03T22:13:44Z
[ "python", "variables", "global-variables", "global" ]
``` def say_boo_twice(): global boo boo = 'Boo!' print boo, boo boo = 'boo boo' say_boo_twice() ``` The output is > Boo! Boo! Not as I expected. Since I declared `boo` as global, why is the output not: > boo boo boo boo
You've changed `boo` inside your function, why wouldn't it change? Also, global variables are bad.
Python global variable
5,532,890
11
2011-04-03T22:11:02Z
5,532,926
17
2011-04-03T22:16:08Z
[ "python", "variables", "global-variables", "global" ]
``` def say_boo_twice(): global boo boo = 'Boo!' print boo, boo boo = 'boo boo' say_boo_twice() ``` The output is > Boo! Boo! Not as I expected. Since I declared `boo` as global, why is the output not: > boo boo boo boo
Because you reassign right before hand. Comment out `boo = 'Boo!'` and you will get what you describe. ``` def say_boo_twice(): global boo #boo = 'Boo!' print boo, boo boo = 'boo boo' say_boo_twice() ``` Also that `global boo` is unnecessary, `boo` is already in global scope. This is where the `global` m...
Python reversing a string using recursion
5,532,902
5
2011-04-03T22:12:54Z
5,532,914
17
2011-04-03T22:14:35Z
[ "python", "string", "recursion" ]
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): ...
``` def rreverse(s): if s == "": return s else: return rreverse(s[1:]) + s[0] ``` (Very few people do heavy recursive processing in Python, the language [wasn't designed for it](http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html).)
Python reversing a string using recursion
5,532,902
5
2011-04-03T22:12:54Z
5,532,974
12
2011-04-03T22:27:36Z
[ "python", "string", "recursion" ]
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): ...
To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself. What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, ...
Simple python question: How do i add multiple strings over several lines?
5,533,401
3
2011-04-04T00:05:59Z
5,533,417
8
2011-04-04T00:09:33Z
[ "python" ]
Help, i'm lost in python-world: ``` message = struct.pack('B', 4) + minissdpdStringEncode(st) + minissdpdStringEncode(usn) + minissdpdStringEncode(server) + minissdpdStringEncode(location) ``` It doesn't run, do i really need to put this all on one line or something? That would be messy in my opin...
You have two choices: ``` message = struct.pack('B', 4) + \ minissdpdStringEncode(st) ``` or ``` message = (struct.pack('B', 4) + minissdpdStringEncode(st)) ``` I usually find the second form with parentheses easier to read.
python string formatting
5,533,700
3
2011-04-04T01:17:35Z
5,533,712
7
2011-04-04T01:19:45Z
[ "python", "string", "format" ]
I need some help with the Python's new string formatter. Basically, I want the outer curly braces to not escape the string replacement field. This works: ``` foo = 'bar' print '{%s}' % foo ``` But, this doesn't: ``` foo = 'bar' print('{{0}}'.format(foo)) ``` Desired output: '{bar}'
It looks like you want: ``` >>> foo = 'bar' >>> print('{{{0}}}'.format(foo)) '{bar}' ``` The outer pair of doubled `{{` and `}}` are copied literally to the output, leaving `{0}` to be interpreted as a substitution.
python sys.argv limitations?
5,533,704
5
2011-04-04T01:18:30Z
5,533,727
11
2011-04-04T01:23:53Z
[ "python" ]
Suppose I'd like to run a python script like this: `python my_script.py MY_INPUT`. In this case, `MY_INPUT` will be transmitted to `sys.argv[1]`. Is there a limit to the **number** of characters `MY_INPUT` can contain? Is there a limit to the **type** of characters `MY_INPUT` can contain? Any other limitations with ...
The size of `argv` is limited by the operating system, and it varies wildly from OS to OS. Quoting from the Linux `execve(2)` manpage: ``` Limits on size of arguments and environment Most Unix implementations impose some limit on the total size of the command-line argument (argv) and environment (envp) string...
What Javascript constructs does JsLex incorrectly lex?
5,533,925
10
2011-04-04T02:09:20Z
5,573,409
7
2011-04-06T21:51:28Z
[ "javascript", "python", "tokenize", "lexical-analysis" ]
[JsLex](https://bitbucket.org/ned/jslex) is a Javascript lexer I've written in Python. It does a good job for a day's work (or so), but I'm sure there are cases it gets wrong. In particular, it doesn't understand anything about semicolon insertion, and there are probably ways that's important for lexing. I just don't k...
Interestingly enough I tried your lexer on the code of my lexer/evaluator written in JS ;) You're right, it is not always doing well with regular expressions. Here some examples: ``` rexl.re = { NAME: /^(?!\d)(?:\w)+|^"(?:[^"]|"")+"/, UNQUOTED_LITERAL: /^@(?:(?!\d)(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/, QUOTED_L...
How do I separate my models out in django?
5,534,206
12
2011-04-04T03:06:17Z
5,534,251
23
2011-04-04T03:16:42Z
[ "python", "django", "django-models", "split" ]
I'm trying to learn python/django. Right now, I have all of my models in models.py Is it possible to have my models broken out so that I can have a single file per model in a separate models folder so that I can do something like: > ~/myproject/myapp/models/user.py > ~/myproject/myapp/models/group.py Thanks
It is possible, just make sure to import all the models you create in `__init__.py` in your `models` directory. In your case, it would look like this: ``` # __init__.py from user import UserModel from group import GroupModel ``` This needs to be done because Django looks in `app.models` for an app's models. As other...
To find synonyms, defintions and example sentences using WordNet
5,534,926
13
2011-04-04T05:35:29Z
5,535,079
20
2011-04-04T06:04:27Z
[ "python", "nltk", "wordnet" ]
I need to take an input text file with a one word. I then need to find the lemma\_names, definition and examples of the synset of the word using wordnet. I have gone through the book : "Python Text Processing with NLTK 2.0 Cookbook" and also "Natural Language Processing using NLTK" to help me in this direction. Though ...
``` def synset(word): wn.synsets(word) ``` doesn't return anything so by default you get `None` you should write ``` def synset(word): return wn.synsets(word) ``` Extracting lemma names: ``` from nltk.corpus import wordnet syns = wordnet.synsets('car') syns[0].lemmas[0].name >>> 'car' [s.lemmas[0].name for...
Negative integer division surprising result
5,535,206
22
2011-04-04T06:25:04Z
5,535,239
28
2011-04-04T06:29:16Z
[ "python", "python-3.x", "division", "integer-division" ]
In my application I encountered the following and was surprised by the results: `8/-7=-2` (both integers). what does this means?
For the actual values, i.e. `8.0/(-7.0)`, the result is roughly `-1.143`. Your result using integer division is being rounded down toward the more negative value of `-2`. (This is also known as "Floor division") This is why you will get the somewhat perplexing answers of: ``` >>> 8/(-7) -2 >>> 8/7 1 ``` **Note:** T...
Negative integer division surprising result
5,535,206
22
2011-04-04T06:25:04Z
5,535,294
8
2011-04-04T06:35:27Z
[ "python", "python-3.x", "division", "integer-division" ]
In my application I encountered the following and was surprised by the results: `8/-7=-2` (both integers). what does this means?
to have python automatically convert integer division to float, you can use: ``` from __future__ import division ``` now: ``` 8/-7=-1.1428571428571428 ``` this feature is not in the standard python 2 not to break existing code that relied on integer division. However, this is the default behavior for python 3.
Django Admin Page missing CSS
5,537,268
19
2011-04-04T10:33:13Z
5,537,377
7
2011-04-04T10:44:24Z
[ "python", "css", "django", "django-admin" ]
I saw this [question](http://stackoverflow.com/questions/3271731/djangos-admin-pages-are-missing-their-typical-formatting-style-have-i-set-it-up) and recommendation from Django Projects [here](http://docs.djangoproject.com/en/dev/howto/deployment/modpython/?from=olddocs#id3) but still can't get this to work. My Django ...
There's a couple of problems here, both to do with your symbolic link. Firstly, the source and target needed to be the other way round (I always get that wrong myself). Secondly, you have used a completely different path to the one you've specified in your Apache conf - `djangotest/sgelections` vs `django/sgel`. Do ...
Django Admin Page missing CSS
5,537,268
19
2011-04-04T10:33:13Z
5,626,064
12
2011-04-11T18:53:55Z
[ "python", "css", "django", "django-admin" ]
I saw this [question](http://stackoverflow.com/questions/3271731/djangos-admin-pages-are-missing-their-typical-formatting-style-have-i-set-it-up) and recommendation from Django Projects [here](http://docs.djangoproject.com/en/dev/howto/deployment/modpython/?from=olddocs#id3) but still can't get this to work. My Django ...
In addition to correcting the symbolic link as Daniel Roseman suggested, you'll need to make sure that the user that is running Apache has read access to the admin media. * If you do `ls -l` in your media directory, do you see the symbolic link? * If you `cd admin` from your media directory, does it work? If you then ...
Memory errors and list limits?
5,537,618
31
2011-04-04T11:09:38Z
5,537,759
14
2011-04-04T11:22:56Z
[ "python", "list", "memory", "limits" ]
I need to produce large and big (very) matrices (Markov chains) for scientific purposes. I perform calculus that I put in a list of 20301 elements (=one row of my matrix). I need all those data in memory to proceed next Markov step but i can store them elsewhere (eg file) if needed even if it will slow my Markov chain ...
The `MemoryError` exception that you are seeing is the direct result of running out of available RAM. This could be caused by either the 2GB per program limit imposed by Windows ([32bit programs](http://msdn.microsoft.com/en-us/library/aa366778%28v=vs.85%29.aspx#memory_limits)), or lack of available RAM on your compute...
Memory errors and list limits?
5,537,618
31
2011-04-04T11:09:38Z
5,537,764
27
2011-04-04T11:23:57Z
[ "python", "list", "memory", "limits" ]
I need to produce large and big (very) matrices (Markov chains) for scientific purposes. I perform calculus that I put in a list of 20301 elements (=one row of my matrix). I need all those data in memory to proceed next Markov step but i can store them elsewhere (eg file) if needed even if it will slow my Markov chain ...
First off, see [How Big can a Python Array Get?](http://stackoverflow.com/questions/855191/how-big-can-a-python-array-get) and [Numpy, problem with long arrays.](http://stackoverflow.com/questions/1697557/numpy-problem-with-long-arrays) Second, the only real limit comes from the amount of memory you have and how your ...
get UTC offset from time zone name in python
5,537,876
27
2011-04-04T11:34:13Z
5,537,942
41
2011-04-04T11:42:19Z
[ "python" ]
How can I get UTC offset from time zone name in python? For example: I have "Asia/Jerusalem" and I want to get "+0200"
Because of DST (Daylight Saving Time), the result depends on the time of the year: ``` import datetime, pytz datetime.datetime.now(pytz.timezone('Asia/Jerusalem')).strftime('%z') # returns '+0300' (because 'now' they have DST) pytz.timezone('Asia/Jerusalem').localize(datetime.datetime(2011,1,1)).strftime('%z') # ...
get UTC offset from time zone name in python
5,537,876
27
2011-04-04T11:34:13Z
5,537,943
10
2011-04-04T11:42:20Z
[ "python" ]
How can I get UTC offset from time zone name in python? For example: I have "Asia/Jerusalem" and I want to get "+0200"
Have you tried using the [pytz](http://pytz.sourceforge.net/) project and the [`utcoffset` method](http://pytz.sourceforge.net/#tzinfo-api)? e.g. ``` >>> import datetime >>> import pytz >>> today = datetime.datetime.now() >>> pst = pytz.timezone('US/Pacific') >>> pst.utcoffset(today).total_seconds()/60/60 -7.0 ```
Determining redirected URL in Python
5,538,280
3
2011-04-04T12:14:47Z
5,538,568
8
2011-04-04T12:38:15Z
[ "python", "parsing", "redirect" ]
I make a little parser using HTMLparser and I would like to know where a link is redirected. I don't know how to explain this, so please look this example: On my page I have a link on the source: `http://www.myweb.com?out=147`, which redirects to `"http://www.mylink.com"`. I can parse `"http://www.myweb.com?out=147"` ...
You can use [`urllib2`](https://docs.python.org/2/library/urllib2.html#module-urllib2) ([`urllib.request`](https://docs.python.org/3/library/urllib.request.html#module-urllib.request) in Python 3) and its [`HTTPRedirectHandler`](https://docs.python.org/2/library/urllib2.html#httpredirecthandler-objects) in order to fin...
Pip installing into an older Python version
5,538,329
14
2011-04-04T12:19:11Z
5,538,353
27
2011-04-04T12:21:05Z
[ "python", "pip" ]
I am trying to install mysql-python using: ``` pip install mysql-python ``` the package is being installed below, although I already have Python 2.6 on the system. ``` /Library/Python/2.5/site-packages ``` How can I get pip to install in: ``` /Library/Python/2.6/site-packages ``` I tried using: ``` pip install -...
You should have pip-2.6. If you don't have pip version 2.6 : You have to install setuptools for Python 2.6 (example : setuptools-0.6c11-py2.6.egg). Then, you have easy\_install-2.6. You can do : ``` easy_install-2.6 pip ``` Finally, you have pip version 2.6. To install mysql-python : ``` pip-2.6 install mysql-pytho...
python Call to external program results in [Error 193] %1 is not a valid Win32 application
5,538,671
4
2011-04-04T12:48:07Z
12,655,207
7
2012-09-29T18:13:22Z
[ "python", "windows" ]
I am writing a GUI front end that after it does a bunch of validation will execute a series of already existing vbscript .wsf files. My problem is when I try to execute the .wsf files I get the error ``` WindowsError: [Error 193] %1 is not a valid Win32 application ``` Running them from the command line works fine ...
Do you have the 64-bit version of Python installed? I got the same kind of error when I was trying to do a ctype call to a (32-bit) dll running Python 2.7 (64-bit). When I changed to the 32-bit version of Python, the error disappeared and things started working! Perhaps you are having the same problem? I suppose in W...
Boost and Python 3.x
5,539,557
13
2011-04-04T13:58:33Z
5,542,020
10
2011-04-04T17:21:33Z
[ "c++", "python", "boost", "python-3.x", "boost-python" ]
How boost.python deal with Python 3 ? Is it Python 2 only ? Thank you.
Newer versions of Boost should work fine with Python V3.x. This support has been added quite some time ago, I believe after a successful Google Summer of Code project back in 2009. The way to use Python V3 with Boost is to properly configure the build system by adding for instance: ``` using python : 3.1 : /your_pyth...
python: Can I run a python script without actually installing python?
5,539,736
19
2011-04-04T14:13:03Z
5,539,766
7
2011-04-04T14:14:57Z
[ "python", "executable", "py2exe", "cx-freeze" ]
I have some .py files I wrote that I want to run on a different machine. The target machine does not have python installed, and I can't 'install' it by policy. What I can do is copy files over, run my stuff, and then remove them. What I tried was to just take my development python folder over to the target machine and...
**Edit:** Development of Portable Python has stopped. I will remove this answer shortly. Check out [Portable Python](http://www.portablepython.com/). That should do what you need. Current versions (as of April 2015) are 2.7.6 and 3.2.5
How to sort an integer array in-place in Python?
5,540,148
4
2011-04-04T14:43:28Z
5,540,359
8
2011-04-04T15:00:36Z
[ "python", "arrays", "sorting" ]
how can one sort an integer array (**not** a list) in-place in Python 2.6? Is there a suitable function in one of the standard libraries? In other words, I'm looking for a function that would do something like this: ``` >>> a = array.array('i', [1, 3, 2]) >>> some_function(a) >>> a array('i', [1, 2, 3]) ``` Thanks i...
Well, you can't do it with `array.array`, but you can with `numpy.array`: ``` In [3]: a = numpy.array([0,1,3,2], dtype=numpy.int) In [4]: a.sort() In [5]: a Out[5]: array([0, 1, 2, 3]) ``` Or you can convert directly from an `array.array` if you have that already: ``` a = array.array('i', [1, 3, 2]) a = numpy.arra...
How to check for presence of a layer in a scapy packet?
5,540,571
7
2011-04-04T15:15:57Z
5,552,002
13
2011-04-05T12:43:23Z
[ "python", "scapy" ]
How do I check for the presence of a particular layer in a scapy packet? For example, I need to check the src/dst fields of an IP header, how do I know that a particular packet actually has an IP header (as opposed to IPv6 for instance). My problem is that when I go to check for an IP header field, I get an error sayi...
You should try the "in" operator. It returns true or false depending if the layer is present or not in the packet. ``` root@u1010:~/scapy# scapy Welcome to Scapy (2.2.0-dev) >>> load_contrib("ospf") >>> pkts=rdpcap("rogue_ospf_hello.pcap") >>> p=pkts[0] >>> IP in p True >>> UDP in p False >>> root@u1010:~/scapy# ```
How to check for presence of a layer in a scapy packet?
5,540,571
7
2011-04-04T15:15:57Z
10,174,108
10
2012-04-16T12:30:34Z
[ "python", "scapy" ]
How do I check for the presence of a particular layer in a scapy packet? For example, I need to check the src/dst fields of an IP header, how do I know that a particular packet actually has an IP header (as opposed to IPv6 for instance). My problem is that when I go to check for an IP header field, I get an error sayi...
For completion I thought I would also mention the haslayer method. ``` >>> pkts=rdpcap("rogue_ospf_hello.pcap") >>> p=pkts[0] >>> p.haslayer(UDP) 0 >>> p.haslayer(IP) 1 ``` Hope that helps as well..
How can a test called by Robot Framework return information to the console
5,540,784
8
2011-04-04T15:30:39Z
5,544,621
12
2011-04-04T21:34:52Z
[ "python", "frameworks", "automated-tests", "robotframework" ]
I have a robot framework test suite that calls a python method. I would like that python method to return a message to the console without failing the test. Specifically I am trying to time a process. I can use "raise" to return a message to the console, but that simultaneously fails the test. ``` def doSomething(se...
Since you are using Python you have two simple possibilities: 1. Write your messages to the `stderr`. These messages are written both to Robot's log file and to the console. A limitation is that the messages end up to the console only after the keyword you are executing finishes. A bonus is that this approach works al...
Eclipse external tool for Qt .ui to .py with pyuic
5,541,024
5
2011-04-04T15:51:09Z
6,419,843
10
2011-06-21T02:53:03Z
[ "python", "eclipse", "qt", "pydev" ]
I use PyDev in Eclipse with the Qt integration. With an external tool I can create python source in a .py from a qt .ui file. This is the external tool: <http://permalink.gmane.org/gmane.comp.python.xy.devel/413> The problem is that the generated python .py file has a name like MyGeneratedFile.ui.py. How can I adapt th...
So it seems the problem boils down to **${resource\_loc}**, since this gives you the full path name **/path/to/file/filename.ui** - Yes, it does include the **.ui** hence when you say **${resource\_loc}.py** this translates into **/path/to/file/filename.ui.py** So probably the simplest way to correct this problem sinc...
Immutable numpy array?
5,541,324
30
2011-04-04T16:18:52Z
5,541,452
47
2011-04-04T16:29:17Z
[ "python", "arrays", "numpy", "immutability", "readonly" ]
Is there a simple way to create an immutable NumPy array? If one has to derive a class from `ndarray` to do this, what's the minimum set of methods that one has to override to achieve immutability?
You can make a numpy array unwriteable: ``` a = np.arange(10) a.flags.writeable = False a[0] = 1 # Gives: RuntimeError: array is not writeable ``` Also see the discussion in this thread: <http://mail.scipy.org/pipermail/numpy-discussion/2008-December/039274.html> and the documentation: <http://docs.scipy.org/doc/n...
Image compositing
5,541,582
6
2011-04-04T16:40:54Z
5,628,573
7
2011-04-11T23:04:33Z
[ "python", "image", "composite", "cairo" ]
I have an album title of some music band. I want to draw it with some mask which will round the corners of image. So, I've prepared such mask in gimp: ![enter image description here](http://i.stack.imgur.com/4TPsF.png) I'm using white mask, but it's invisible at white background here. So, here is the code of renderin...
You need to share your surface creation code as well, here's some code I extended from your example: ``` import cairo surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, 128, 128) ctx = cairo.Context (surface) posX = posY = 0 img = cairo.ImageSurface.create_from_png('sample.png') ctx.set_source_surface(img, posX, ...
Get rid of stopwords and punctuation
5,541,745
3
2011-04-04T16:53:43Z
5,541,855
17
2011-04-04T17:05:20Z
[ "python", "nltk", "stop-words" ]
I'm struggling with NLTK stopword. Here's my bit of code.. Could someone tell me what's wrong? ``` from nltk.corpus import stopwords def removeStopwords( palabras ): return [ word for word in palabras if word not in stopwords.words('spanish') ] palabras = ''' my text is here ''' ```
Your problem is that the iterator for a string returns each character not each word. For example: ``` >>> palabras = "Buenos dias" >>> [c for c in palabras] ['B', 'u', 'e', 'n', 'a', 's', ' ', 'd', 'i', 'a', 's'] ``` You need to iterate and check each word, fortunately the split function already exists in the python...
difference between filter with multiple arguments and chain filter in django
5,542,874
31
2011-04-04T18:48:36Z
11,025,652
29
2012-06-14T01:45:38Z
[ "python", "django", "django-models" ]
What is the difference between filter with multiple arguments and chain filter in django?
As you can see in the generated SQL statements the difference is not the "OR" as some may suspect. It is how the WHERE and JOIN is placed. Example1 (same joined table): from <https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships> ``` Blog.objects.filter( entry__headline__...
Computing Standard Deviation in a stream
5,543,651
23
2011-04-04T20:00:06Z
5,543,790
30
2011-04-04T20:12:01Z
[ "python", "math" ]
Using Python, assume I'm running through a known quantity of items `I`, and have the ability to time how long it takes to process each one `t`, as well as a running total of time spent processing `T` and the number of items processed so far `c`. I'm currently calculating the average on the fly `A = T / c` but this can ...
As outlined in the [Wikipedia article on the standard deviation](http://en.wikipedia.org/wiki/Standard_deviation#Rapid_calculation_methods), it is enough to keep track of the following three sums: ``` s0 = sum(1 for x in samples) s1 = sum(x for x in samples) s2 = sum(x*x for x in samples) ``` These sums are easily up...
Computing Standard Deviation in a stream
5,543,651
23
2011-04-04T20:00:06Z
5,543,818
13
2011-04-04T20:14:28Z
[ "python", "math" ]
Using Python, assume I'm running through a known quantity of items `I`, and have the ability to time how long it takes to process each one `t`, as well as a running total of time spent processing `T` and the number of items processed so far `c`. I'm currently calculating the average on the fly `A = T / c` but this can ...
I use [Welford's Method](http://stackoverflow.com/questions/895929/how-do-i-determine-the-standard-deviation-stddev-of-a-set-of-values), which gives more accurate results. This link points to [John D. Cook's overview](http://www.johndcook.com/standard_deviation.html).
Computing Standard Deviation in a stream
5,543,651
23
2011-04-04T20:00:06Z
5,544,108
14
2011-04-04T20:43:12Z
[ "python", "math" ]
Using Python, assume I'm running through a known quantity of items `I`, and have the ability to time how long it takes to process each one `t`, as well as a running total of time spent processing `T` and the number of items processed so far `c`. I'm currently calculating the average on the fly `A = T / c` but this can ...
Based on [Welford's algorithm](http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm): ``` import numpy as np class OnlineVariance(object): """ Welford's algorithm computes the sample variance incrementally. """ def __init__(self, iterable=None, ddof=1): self.ddof...
How to change button color with tkinter
5,543,815
3
2011-04-04T20:14:06Z
5,544,055
9
2011-04-04T20:38:42Z
[ "python", "button", "tkinter" ]
I keep getting the following error: AttributeError: 'NoneType' object has no attribute 'configure' ``` # create color button self.button = Button(self, text = "Click Me", command = self.color_change, bg = "blue" ).grid(row = 2, column =...
When you do `self.button = Button(...).grid(...)`, what gets assigned to `self.button` is the result of the `grid()` command, *not* a reference to the `Button` object created. You need to assign your `self.button` variable before packing/griding it. It should look something like this: ``` self.button = Button(self,te...
Call a function in Python and pass only the arguments it expects
5,543,870
8
2011-04-04T20:19:12Z
5,543,911
10
2011-04-04T20:23:51Z
[ "python" ]
How do I call a function and only pass it the arguments that it expects. For example say I have the following functions: ``` func1 = lambda a: True func2 = lambda a, b: True func3 = lambda c: True ``` I want some Python code that is able to successfully call these functions without raising a `TypeError` by passing un...
You can use `inspect.getargspec()`: ``` from inspect import getargspec kwargs = dict(a=1, b=2, c=3) for func in (func1, func2, func3): func(**dict((name, kwargs[name]) for name in getargspec(func)[0])) ```
Comprehensive tutorial on Pyinstaller?
5,543,920
25
2011-04-04T20:24:46Z
6,918,646
13
2011-08-02T21:09:53Z
[ "python", "documentation", "pyinstaller" ]
I'm looking for a tutorial on [PyInstaller](http://www.pyinstaller.org/) that will explain things like * how to create .pkg files * how to include/exclude modules * how to include data files inside the install directory. I cannot make much sense out of the [standard PyInstaller documentation](http://www.pyinstaller.o...
Have you looked here: [simplified tutorial](http://excid3.com/blog/pyinstaller-a-simple-tutorial/) Or here: [a bit longer tutorial](http://www.blog.pythonlibrary.org/2010/08/10/a-pyinstaller-tutorial-build-a-binary-series/) EDIT: Adding data files is implied in the second tutorial. If you use the second example just ...
Comprehensive tutorial on Pyinstaller?
5,543,920
25
2011-04-04T20:24:46Z
20,031,445
16
2013-11-17T13:49:59Z
[ "python", "documentation", "pyinstaller" ]
I'm looking for a tutorial on [PyInstaller](http://www.pyinstaller.org/) that will explain things like * how to create .pkg files * how to include/exclude modules * how to include data files inside the install directory. I cannot make much sense out of the [standard PyInstaller documentation](http://www.pyinstaller.o...
Both guides in the accepted answer seem outdated. PyInstaller now provides an executable script that allows you to do `pyinstaller your_script.py` wherever `your_script.py` is located -- instead of the old mode of copying your `your_script.py` to wherever you copied the source code of PyInstaller. Here's a brief, mo...
Combining multiple for loops in Python
5,544,549
3
2011-04-04T21:27:49Z
5,544,568
9
2011-04-04T21:29:47Z
[ "python" ]
Let's say, we have and list of objects in variable called "articles", each object has a member "tags" (which is simple list). Expected output: all tags in all articles, joined in a single list. In multiple lines, solution would be: ``` arr = [] for article in articles: for tag in article.tags: arr.append(...
It's invalid because `article` doesn't exist by the time the first loop is parsed. ``` arr = [tag for article in articles for tag in article.tags] ```
Retrieve a task result object, given a `task_id` in Celery
5,544,611
24
2011-04-04T21:33:39Z
5,544,834
46
2011-04-04T21:59:32Z
[ "python", "celery" ]
I store the `task_id` from an `celery.result.AsyncResult` in a database and relate it to the item that the task affects. This allows me to perform a query to retrieve all the `task_id`s of tasks that relate to a specific item. So after retrieving the `task_id` from the database, how do I go about retrieving informatio...
From the [Celery FAQ](http://docs.celeryproject.org/en/latest/faq.html#how-do-i-get-the-result-of-a-task-if-i-have-the-id-that-points-there): ``` result = MyTask.AsyncResult(task_id) result.get() ```
Retrieve list of tasks in a queue in Celery
5,544,629
66
2011-04-04T21:35:36Z
9,369,466
89
2012-02-20T22:35:47Z
[ "python", "celery" ]
How can I retrieve a list of tasks in a queue that are yet to be processed?
You should look here: [Celery Guide - Inspecting Workers](http://docs.celeryproject.org/en/latest/userguide/workers.html?highlight=revoke#inspecting-workers) Basically this: ``` >>> from celery.task.control import inspect # Inspect all nodes. >>> i = inspect() >>> i.scheduled() or: >>> i.active() ``` Depending on ...
Retrieve list of tasks in a queue in Celery
5,544,629
66
2011-04-04T21:35:36Z
29,537,823
14
2015-04-09T11:55:20Z
[ "python", "celery" ]
How can I retrieve a list of tasks in a queue that are yet to be processed?
if you are using rabbitMQ, use this in terminal: ``` sudo rabbitmqctl list_queues ``` it will print list of queues with number of pending tasks. for example: ``` Listing queues ... 0b27d8c59fba4974893ec22d478a7093 0 0e0a2da9828a48bc86fe993b210d984f 0 10@torob2.celery.pidbox 0 11926b79e30a4f0a9d95df61b6f402f7 ...
2D RTS in Python?
5,544,634
4
2011-04-04T21:36:11Z
5,544,725
7
2011-04-04T21:46:12Z
[ "python", "performance", "graphics", "real-time-strategy" ]
I am a great python fan. Recently I got an idea to write RTS engine and/or maybe a simple RTS game based upon this engine. There are a couple of things I need to think about and maybe you can give me some advice on these: 1. Performance. Most games are written in C++. Isn't python too slow for game engine? I am aiming...
1. Performance *may* be an issue with heavy graphics/math processing. If so, see Panda3D, NumPy, Cython, and PyPy. 2. Use Pyglet, PyOpenGL with Pyglet, Panda3D (although you are writing in 2D, you can still use a 3D engine), or perhaps some other library. 3. There don't seem to be existing RTS libraries, but there are ...
Should I use a main() method in a simple Python script?
5,544,752
22
2011-04-04T21:48:55Z
5,544,783
24
2011-04-04T21:53:01Z
[ "python" ]
I have a lot of simple scripts that calculate some stuff or so. They consist of just a single module. Should I write main methods for them and call them with the `if __name__` construct, or just dump it all right in there? What are the advantages of either method?
Well, if you do this: ``` # your code ``` Then `import your_module` will execute your code. On the contrary, with this: ``` if __name__ == '__main__': # your code ``` The import won't run the code, but targeting the interpreter at that file will. **If the only way the script is ever going to run is by manual i...
Should I use a main() method in a simple Python script?
5,544,752
22
2011-04-04T21:48:55Z
5,544,937
34
2011-04-04T22:13:45Z
[ "python" ]
I have a lot of simple scripts that calculate some stuff or so. They consist of just a single module. Should I write main methods for them and call them with the `if __name__` construct, or just dump it all right in there? What are the advantages of either method?
I always write a `main()` function (appropriately named), and put nothing but command-line parsing and a call to `main()` in the `if __name__ == '__main__'` block. That's because no matter how silly, trivial, or single-purpose I originally expect that script to be, I always end up wanting to call it from another module...
What's the recommended scoped_session usage pattern in a multithreaded sqlalchemy webapp?
5,544,774
21
2011-04-04T21:51:54Z
11,547,942
14
2012-07-18T18:26:25Z
[ "python", "multithreading", "session", "sqlalchemy" ]
I'm writing an application with python and sqlalchemy-0.7. It starts by initializing the sqlalchemy orm (using declarative) and then it starts a multithreaded web server - I'm currently using web.py for rapid prototyping but that could change in the future. I will also add other "threads" for scheduled jobs and so on, ...
Yes, this is the right way. Example: The [Flask](http://flask.pocoo.org/) microframework with [Flask-sqlalchemy](http://packages.python.org/Flask-SQLAlchemy/) extension does what you described. It also does .remove() automatically at the end of each HTTP request ("view" functions), so the session is released by the c...
PIL - libjpeg.so.8: cannot open shared object file: No such file or directory
5,545,580
13
2011-04-04T23:42:20Z
5,545,618
18
2011-04-04T23:47:08Z
[ "python", "django", "python-imaging-library" ]
Compiled the libjpeg v8, PIL 1.1.7 and and import for \_imaging works on the system Python, but spouts this error inside the virtualenv: ``` libjpeg.so.8: cannot open shared object file: No such file or directory ``` here is the error run with a python -v interpreter inside the virtualenv ``` >>> import _imaging dlo...
See an explanation here: [Why can't Python find shared objects that are in directories in sys.path?](http://stackoverflow.com/questions/1099981/why-cant-python-find-shared-objects-that-are-in-directories-in-sys-path) A quick fix is to add the directory that contains `libjpeg.so.8` to your `/etc/ld.so.conf` file, and t...
How do I change where Bash looks for Python in Linux?
5,546,141
3
2011-04-05T01:23:07Z
5,546,147
12
2011-04-05T01:24:05Z
[ "python", "linux", "bash" ]
I just updated my ReadyNas from python 2.3.5 to python 2.6.6. The upgrade placed the new version in the `/usr/local/bin` directory. So * `/usr/local/bin/python` is Python 2.6.6 * `/usr/bin/python` is Python 2.3.5 When I type `python` at a bash prompt tries to run `/usr/bin/python` or my old version. I relocated my ol...
Your `PATH` environment variable. It has a list of directories which bash searches (in the same order) when it's looking for an program to execute. Basically you want to put `/usr/local/bin` at the start of your `PATH` environment variable. Add the following to your `~/.bashrc` file: ``` export PATH=/usr/local/bin:$PA...
minimum value of y axis is not being applied in matplotlib vlines plot
5,548,121
5
2011-04-05T06:37:34Z
5,548,223
11
2011-04-05T06:50:23Z
[ "python", "matplotlib" ]
I am doing a vlines plot in matplotlib and I have all my y values in the dataset as `>=0`. I want my y axis bottom most tick to read `0`, but instead, I get -500. Here is the code: ``` #!/usr/bin/env python import numpy as np from matplotlib import pyplot as plt, dates as mdates import datetime as dt, time # Read t...
You can set the limit manually *after plotting the data*, like so: ``` pyplot.ylim(ymin=0) ``` What happens is that Matplotlib adjusts the plot limits so that it looks "best". Sometimes, this implies going beyond the strict range of your data. You must then update the limits *after* the plot, since each plot updates ...
Sorting a List based on dates
5,549,000
2
2011-04-05T08:11:16Z
5,549,042
11
2011-04-05T08:15:34Z
[ "python" ]
Below is a code which I wrote to sort the elements of a list based on certain parameters. One the parameters is a date. Now the date format is mm/dd/yy. Now if the year is the same, I dont face any problem. However, if I change the year from 2011 to 2012 of a particular element, the solution breaks down. For example it...
Try this: ``` sorted(List, key=lambda x: (x[2].split('/')[2], x[2].split('/')[0], x[2].split('/')[1])) ``` For an example: ``` List=[['G1','E','03/12/2011',2], ['G2','E','03/10/2011',2], ['G3','2','03/19/2012',1], ['G4','2','03/15/2010',2], ['G6','2','03/15/2012',2]] ``` it returns: ``` [['...
How to finish sys.stdin.readlines() input?
5,549,141
14
2011-04-05T08:26:36Z
5,549,182
29
2011-04-05T08:30:29Z
[ "python", "input", "interactive", "sys" ]
This might be a silly question, but as I can't find an answer, I have to ask it. In interactive python I want to process a message which i get with: ``` >>> message = sys.stdin.readlines() ``` Everything works fine, but... how to stop it from getting an input and make it save into message variable? Stopping with ctr...
**For unix based system :** Hello, you can tape : `Ctrl``d` `Ctrl``d` closes the standard input (stdin) by sending [EOF](http://en.wikipedia.org/wiki/End-of-file). Example : ``` >>> import sys >>> message = sys.stdin.readlines() Hello World My Name Is James Bond # <ctrl-d> EOF sent >>> print message ['Hello\n', 'Wo...
Is shared readonly data copied to different processes for Python multiprocessing?
5,549,190
33
2011-04-05T08:31:28Z
5,550,156
70
2011-04-05T10:01:34Z
[ "python", "numpy", "multiprocessing" ]
The piece of code that I have looks some what like this: ``` glbl_array = # a 3 Gb array def my_func( args, def_param = glbl_array): #do stuff on args and def_param if __name__ == '__main__': pool = Pool(processes=4) pool.map(my_func, range(1000)) ``` Is there a way to make sure (or encourage) that the diff...
You can use the shared memory stuff from `multiprocessing` together with Numpy fairly easily: ``` import multiprocessing import ctypes import numpy as np shared_array_base = multiprocessing.Array(ctypes.c_double, 10*10) shared_array = np.ctypeslib.as_array(shared_array_base.get_obj()) shared_array = shared_array.resh...
Ignore file .pyc in git repository
5,551,269
18
2011-04-05T11:45:31Z
5,551,327
14
2011-04-05T11:50:04Z
[ "python", "git" ]
how can i ignore file .pyc in git. If i put in .gitignore don't work: i need they are untrack and don't check its for commit.
Put it in `.gitignore`. But from the `gitignore(5)` man page: > ``` > · If the pattern does not contain a slash /, git treats it as a shell > glob pattern and checks for a match against the pathname relative > to the location of the .gitignore file (relative to the toplevel of > the work tree...
Ignore file .pyc in git repository
5,551,269
18
2011-04-05T11:45:31Z
5,551,629
40
2011-04-05T12:15:42Z
[ "python", "git" ]
how can i ignore file .pyc in git. If i put in .gitignore don't work: i need they are untrack and don't check its for commit.
You have probably added them to the repository before putting \*.pyc in .gitignore. First remove them from the repository.
Ignore file .pyc in git repository
5,551,269
18
2011-04-05T11:45:31Z
24,956,208
39
2014-07-25T12:49:42Z
[ "python", "git" ]
how can i ignore file .pyc in git. If i put in .gitignore don't work: i need they are untrack and don't check its for commit.
You should add a line with ``` *.pyc ``` to the ".gitignore" file in the root folder of your git repository tree right after repository initialization. As *ralphtheninja* said, if you forgot to to do it beforehand, if you just add the line to the gitignore file, all previously committed .pyc files will still be trac...
Filling gaps in a numpy array
5,551,286
10
2011-04-05T11:46:49Z
5,556,426
13
2011-04-05T18:10:09Z
[ "python", "numpy", "matplotlib", "scipy", "interpolation" ]
I just want to interpolate, in the simplest possible terms, a 3D dataset. Linear interpolation, nearest neighbour, all that would suffice (this is to start off some algorithm, so no accurate estimate is required). In new scipy versions, things like griddata would be useful, but currently I only have scipy 0.8. So I ha...
You can set up a crystal-growth-style algorithm shifting a view alternately along each axis, replacing only data that is flagged with a `False` but has a `True` neighbor. This gives a "nearest-neighbor"-like result (but not in Euclidean or Manhattan distance -- I think it might be nearest-neighbor if you are counting p...
Filling gaps in a numpy array
5,551,286
10
2011-04-05T11:46:49Z
9,262,129
20
2012-02-13T14:25:37Z
[ "python", "numpy", "matplotlib", "scipy", "interpolation" ]
I just want to interpolate, in the simplest possible terms, a 3D dataset. Linear interpolation, nearest neighbour, all that would suffice (this is to start off some algorithm, so no accurate estimate is required). In new scipy versions, things like griddata would be useful, but currently I only have scipy 0.8. So I ha...
Using scipy.ndimage, your problem can be solved with nearest neighbor interpolation in 2 lines : ``` from scipy import ndimage as nd indices = nd.distance_transform_edt(invalid_cell_mask, return_distances=False, return_indices=True) data = data[tuple(ind)] ``` --- Now, in the form of a function: ``` import numpy a...
How to copy a dict and modify it in one line of code
5,551,672
14
2011-04-05T12:19:24Z
5,551,706
14
2011-04-05T12:21:33Z
[ "coding-style", "python" ]
Very often I need to create dicts that differ one from another by an item or two. Here is what I usually do: ``` setup1 = {'param1': val1, 'param2': val2, 'param3': val3, 'param4': val4, 'paramN': valN} setup2 = copy.deepcopy(dict(setup1)) setup2.update({'param1': val1...
### Solution Build a function for that. Your intention would be clearer when you use it in the code, and you can handle complicated decisions (e.g., deep versus shallow copy) in a single place. ``` def copy_dict(source_dict, diffs): """Returns a copy of source_dict, updated with the new key-value pairs in...
How to copy a dict and modify it in one line of code
5,551,672
14
2011-04-05T12:19:24Z
5,551,729
12
2011-04-05T12:23:04Z
[ "coding-style", "python" ]
Very often I need to create dicts that differ one from another by an item or two. Here is what I usually do: ``` setup1 = {'param1': val1, 'param2': val2, 'param3': val3, 'param4': val4, 'paramN': valN} setup2 = copy.deepcopy(dict(setup1)) setup2.update({'param1': val1...
``` setup2 = dict((k, {'param1': val10, 'param2': val20}.get(k, v)) for k, v in setup1.iteritems()) ``` This only works if all keys of the update dictionary are already contained in `setup1`. If all your keys are strings, you can also do ``` setup2 = dict(setup1, param1=val10, param2=val20) ```
How to copy a dict and modify it in one line of code
5,551,672
14
2011-04-05T12:19:24Z
5,551,804
14
2011-04-05T12:29:50Z
[ "coding-style", "python" ]
Very often I need to create dicts that differ one from another by an item or two. Here is what I usually do: ``` setup1 = {'param1': val1, 'param2': val2, 'param3': val3, 'param4': val4, 'paramN': valN} setup2 = copy.deepcopy(dict(setup1)) setup2.update({'param1': val1...
``` setup2 = dict(setup1.items() + {'param1': val10, 'param2': val20}.items()) ``` This way if new keys do not exist in `setup1` they get added, otherwise they replace the old key/value pairs.
python split function
5,552,364
3
2011-04-05T13:10:45Z
5,552,416
12
2011-04-05T13:14:12Z
[ "python" ]
I have problem in splitting data. I have data as follows in CSV file: ``` "a";"b";"c;d";"e" ``` The problem is when I used `line.split(";")` function, it splits even between `c` and `d`. I don't want `c` and `d` to be separated. Later I need to store these four values in four different columns in a table, but using t...
``` import csv reader = csv.reader(open("yourfile.csv", "rb"), delimiter=';') for row in reader: print row ``` Try this out. ``` import csv reader = csv.reader(open("yourfile.csv", "rb"), delimiter=';', quoting=csv.QUOTE_NONE ) for row in reader: print row ``` This ^^^ if you want quotes preserved **Edit:**...
UnicodeDecodeError, invalid continuation byte
5,552,555
73
2011-04-05T13:23:41Z
5,552,593
30
2011-04-05T13:26:56Z
[ "python", "unicode", "decode" ]
Why is the below item failing? and why does it succeed with "latin-1" codec? ``` o = "a test of \xe9 char" #I want this to remain a string as this is what I am receiving v = o.decode("utf-8") ``` results in: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\encod...
It is invalid UTF-8. That character is the e-acute character in ISO-Latin1, which is why it succeeds with that codeset. If you don't know the codeset you're receiving strings in, you're in a bit of trouble. It would be best if a single codeset (hopefully UTF-8) would be chosen for your protocol/application and then yo...
UnicodeDecodeError, invalid continuation byte
5,552,555
73
2011-04-05T13:23:41Z
5,552,616
27
2011-04-05T13:28:50Z
[ "python", "unicode", "decode" ]
Why is the below item failing? and why does it succeed with "latin-1" codec? ``` o = "a test of \xe9 char" #I want this to remain a string as this is what I am receiving v = o.decode("utf-8") ``` results in: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\encod...
Because UTF-8 is multibyte and there is no char corresponding to your combination of `\xe9` plus following space. Why should it succeed in **both** utf-8 and latin-1? Here how the same sentence should be in utf-8: ``` >>> o.decode('latin-1').encode("utf-8") 'a test of \xc3\xa9 char' ```
UnicodeDecodeError, invalid continuation byte
5,552,555
73
2011-04-05T13:23:41Z
5,552,623
83
2011-04-05T13:29:13Z
[ "python", "unicode", "decode" ]
Why is the below item failing? and why does it succeed with "latin-1" codec? ``` o = "a test of \xe9 char" #I want this to remain a string as this is what I am receiving v = o.decode("utf-8") ``` results in: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\encod...
In binary, 0xE9 looks like `1110 1001`. If you read about [UTF-8 on Wikipedia](http://en.wikipedia.org/wiki/UTF-8#Design), you’ll see that such a byte must be followed by two of the form `10xx xxxx`. So, for example: ``` >>> '\xe9\x80\x80'.decode('utf-8') u'\u9000' ``` But that’s just the mechanical cause of the ...
UnicodeDecodeError, invalid continuation byte
5,552,555
73
2011-04-05T13:23:41Z
31,492,722
11
2015-07-18T15:33:57Z
[ "python", "unicode", "decode" ]
Why is the below item failing? and why does it succeed with "latin-1" codec? ``` o = "a test of \xe9 char" #I want this to remain a string as this is what I am receiving v = o.decode("utf-8") ``` results in: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python27\lib\encod...
I had the same error when I tried to open a csv file by pandas read\_csv method. The solution was change the encoding to 'latin-1': ``` pd.read_csv('ml-100k/u.item', sep='|', names=m_cols , encoding='latin-1') ```
plotting a 2D matrix in python, code and most useful visualization
5,552,641
3
2011-04-05T13:30:46Z
5,554,261
11
2011-04-05T15:20:34Z
[ "python", "numpy", "matplotlib", "plot", "visualization" ]
I have a very large matrix(10x55678) in "numpy" matrix format. the rows of this matrix correspond to some "topics" and the columns correspond to words(unique words from a text corpus). Each entry i,j in this matrix is a probability, meaning that word j belongs to topic i with probability x. since I am using ids rather ...
You could certainly use matplotlib's `imshow`or `pcolor` method to display the data, but as comments have mentioned, it might be hard to interpret without zooming in on subsets of the data. ``` a = np.random.normal(0.0,0.5,size=(5000,10))**2 a = a/np.sum(a,axis=1)[:,None] # Normalize pcolor(a) ``` ![Unsorted random...
Adding images to a QTableWidget in PyQt
5,553,342
3
2011-04-05T14:16:59Z
5,556,310
8
2011-04-05T18:00:35Z
[ "python", "pyqt", "qtablewidget", "qtablewidgetitem" ]
I'm very new to Python and even newer to PyQt. I've managed to create a table, but want to add images in certain cells. I've read that I need to subclass the QTableWidget class, or possibly the QTableWidgetItem class and re-implement the QPaintEvent. If anyone has an example of what goes into re-implementing the QPaint...
``` from PyQt4 import QtGui import sys imagePath = "enter the path to your image here" class ImgWidget1(QtGui.QLabel): def __init__(self, parent=None): super(ImgWidget1, self).__init__(parent) pic = QtGui.QPixmap(imagePath) self.setPixmap(pic) class ImgWidget2(QtGui.QWidget): def __...
How to print all possibilities of nested lists in python?
5,553,518
2
2011-04-05T14:28:32Z
5,553,560
9
2011-04-05T14:31:22Z
[ "python", "list", "recursion" ]
Here is my list: ``` pos = [['det'], ['noun', 'adj'], ['noun'], ['vb'], ['det'], ['vb', 'noun', 'adj']] ``` Or ``` pos = ['det', ['noun', 'adj'], 'noun', 'vb', 'det', ['vb', 'noun', 'adj']] ``` I'm trying to print all the combinations: ``` det noun noun vb det vb det adj noun vb det vb det noun noun vb det noun de...
I think `itertools.product()` actually *is* what you are looking for: ``` pos = [['det'], ['noun', 'adj'], ['noun'], ['vb'], ['det'], ['vb', 'noun', 'adj']] for x in itertools.product(*pos): print " ".join(x) ``` prints ``` det noun noun vb det vb det noun noun vb det noun det noun noun vb det adj det adj...
How to list all dlls loaded by a process with Python?
5,553,917
7
2011-04-05T14:55:59Z
5,554,207
7
2011-04-05T15:16:47Z
[ "python", "windows", "dll" ]
I want to list all the dlls loaded by a process, like this: ![enter image description here](http://i.stack.imgur.com/2u7qX.png) How could I get the information with Python on Windows?
Using [listdlls](http://technet.microsoft.com/en-us/sysinternals/bb896656): ``` import os os.system('listdlls PID_OR_PROCESS_NAME_HERE') ```
Python on iPhone
5,555,015
11
2011-04-05T16:16:34Z
5,558,722
11
2011-04-05T21:24:40Z
[ "iphone", "python", "shell", "jailbreak" ]
How can I get a Python shell on my iPhone? I'm looking for step-by-step instructions. It's jailbroken using greenpo1son, I have SSH enabled and know how to use it.
You can browse the packages manually here: <http://apt.saurik.com/cydia/debs/> These are the Python related packages: - iPhone/Python = Example applications including source - PyObjC = Python/Objective-C connection library - Python = Packages required to run Python - Setup Tools = Package manager for Python ...
Unescaping Characters in a String with Python
5,555,063
4
2011-04-05T16:19:44Z
5,555,121
13
2011-04-05T16:23:34Z
[ "python", "json", "unicode", "escaping", "posterous" ]
I made a JSON request that gives me a string that uses [Unicode character codes](http://en.wikipedia.org/wiki/List_of_Unicode_characters) that looks like: ``` s = "\u003Cp\u003E" ``` And I want to convert it to: ``` s = "<p>" ``` What's the best way to do this in Python? Note, this is the same question as [this on...
``` >>> "\\u003Cp\\u003E".decode('unicode-escape') u'<p>' ```
Unescaping Characters in a String with Python
5,555,063
4
2011-04-05T16:19:44Z
5,555,149
7
2011-04-05T16:26:07Z
[ "python", "json", "unicode", "escaping", "posterous" ]
I made a JSON request that gives me a string that uses [Unicode character codes](http://en.wikipedia.org/wiki/List_of_Unicode_characters) that looks like: ``` s = "\u003Cp\u003E" ``` And I want to convert it to: ``` s = "<p>" ``` What's the best way to do this in Python? Note, this is the same question as [this on...
If the data came from JSON, the `json` module should already have decoded these escapes for you: ``` >>> import json >>> json.loads('"\u003Cp\u003E"') u'<p>' ```
Using self.xxxx as default parameter - Python
5,555,449
24
2011-04-05T16:50:27Z
5,555,470
22
2011-04-05T16:52:26Z
[ "python", "object", "recursion", "tree" ]
Hey y'all, I'm trying to simplify one of my homework problems and make the code a little better. What I'm working with is a binary search tree. Right now I have a function in my `Tree()` class that finds all the elements and puts them into a list. ``` tree = Tree() #insert a bunch of items into tree ``` then I use my...
It doesn't work because default arguments are evaluated at function definition time, not at call time: ``` def f(lst = []): lst.append(1) return lst print(f()) # prints [1] print(f()) # prints [1, 1] ``` The common strategy is to use a `None` default parameter. If `None` is a valid value, use a singleton sen...
Using self.xxxx as default parameter - Python
5,555,449
24
2011-04-05T16:50:27Z
5,561,292
18
2011-04-06T04:00:19Z
[ "python", "object", "recursion", "tree" ]
Hey y'all, I'm trying to simplify one of my homework problems and make the code a little better. What I'm working with is a binary search tree. Right now I have a function in my `Tree()` class that finds all the elements and puts them into a list. ``` tree = Tree() #insert a bunch of items into tree ``` then I use my...
larsmans [answered](http://stackoverflow.com/questions/5555449/using-self-xxxx-as-default-parameter-python/5555470#5555470) your first question For your second question, can you simply look before you leap to avoid recursion? ``` def makeList(self, aNode=None): if aNode is None: aNode = self.root tree...
Fixing the singularity of a function
5,556,919
2
2011-04-05T18:50:45Z
5,557,136
7
2011-04-05T19:08:49Z
[ "python", "numpy", null, "singular" ]
Assume you have a function like ``` F = lambda x: sin(x)/x ``` Evaluating `F(0.0)` would result in a divide by zero warning, and would not give the expected result of `1.0`. Is it possible to write another function `fix_singularity` that would give the desired result when applied to the above function, so that ``` f...
`numpy` has a `sinc()` function, which is the normalised form of your function, i.e. ``` F = lambda x: sin(pi*x) / (pi*x) ``` It handles the case for `x == 0.0` correctly, ``` In [16]: x = numpy.linspace(-1,1,11) In [17]: print x [-1. -0.8 -0.6 -0.4 -0.2 0. 0.2 0.4 0.6 0.8 1. ] ``` To "unnormalize" do, ``...
CRC32 checksum in Python with hex input
5,557,214
4
2011-04-05T19:15:01Z
5,557,664
12
2011-04-05T19:51:39Z
[ "python", "string", "hex", "checksum", "crc32" ]
I'm wanting to calculate the CRC32 checksum of a string of hex values in python. I found zlib.crc32(data) and binascii.crc32(data), but all the examples I found using these functions have 'data' as a string ('hello' for example). I want to pass hex values in as data and find the checksum. I've tried setting data as a h...
I think you are looking for [`binascii.a2b_hex()`](http://docs.python.org/library/binascii.html#binascii.a2b_hex): ``` >>> binascii.crc32(binascii.a2b_hex('18329a7e')) -1357533383 ```
Is there a unicode-ready substitute I can use for urllib.quote and urllib.unquote in Python 2.6.5?
5,557,849
29
2011-04-05T20:08:45Z
5,605,354
32
2011-04-09T13:37:41Z
[ "python", "unicode", "urllib" ]
Python's `urllib.quote` and `urllib.unquote` do not handle Unicode correctly in Python 2.6.5. This is what happens: ``` In [5]: print urllib.unquote(urllib.quote(u'Cataño')) --------------------------------------------------------------------------- KeyError Traceback (most recent cal...
> Python's urllib.quote and urllib.unquote do not handle Unicode correctly `urllib` does not handle Unicode at all. URLs don't contain non-ASCII characters, by definition. When you're dealing with `urllib` you should use only byte strings. If you want those to represent Unicode characters you will have to encode and d...
How do I use try .. except or if ...else to validate user input?
5,557,937
5
2011-04-05T20:16:27Z
5,557,998
9
2011-04-05T20:20:29Z
[ "python" ]
I want to restrict user input so that a provided `N` obeys `N >0` or `N < 100`. Should I use `if... else` or `try... except`? Could you provide examples of both approaches?
I'd suggest a combination:) ``` while True: value = raw_input('Value between 0 and 100:') try: value = int(value) except ValueError: print 'Valid number, please' continue if 0 <= value <= 100: break else: print 'Valid range, please: 0-100' ``` Hope it helps.
Sort a pandas DataMatrix in ascending order
5,558,607
2
2011-04-05T21:13:50Z
6,468,964
8
2011-06-24T14:08:42Z
[ "python", "sorting", "numpy", "pandas" ]
The pandas DataFrame object has a [sort method](http://pandas.pydata.org/pandas-docs/stable/basics.html#sorting-by-index-and-value) but pandas DataMatrix object does not. What is the best way to sort this DataMatrix object by index (the date column) in ascending order? ``` >>> dm compound_ret 2/16/2011...
Indeed between 0.2 and 0.3 I renamed `sortUp`/`sortDown` to the single `sort` methods. Sorry about that. I definitely recommend keeping up on the bleeding edge of pandas if you can ( <https://github.com/wesm/pandas> )! Also, consider using IPython for all your interactive work ( <http://ipython.scipy.org> )-- I find t...
Django: Cookie set to expire in 30 seconds is actually expiring in 30 minutes?
5,559,271
2
2011-04-05T22:20:39Z
5,559,490
7
2011-04-05T22:50:14Z
[ "python", "django", "cookies" ]
This is my code: ``` def update_session(request): if not request.is_ajax() or not request.method=='POST': return HttpResponseNotAllowed(['POST']) user_id = request.POST.get('u') hr = set_terminal_cookie(user_id) return hr def set_terminal_cookie(user_id): print 'set_terminal_cookie' hr ...
You can use the `max_age` parameter with a number of seconds instead of using `expires`; it'll calculate `expires` for you. The problem with your `datetime.now()` may be that you're not using UTC (you can use `datetime.utcnow()` instead). ``` hr.set_cookie('user_id', user_id, max_age=30) ``` Moral of the story: [rea...
Why is python choking on numpy.core.ma?
5,560,129
3
2011-04-06T00:18:49Z
5,770,573
7
2011-04-24T12:50:39Z
[ "python", "numpy", "matplotlib" ]
I'm trying to set up pylab on my mac 10.6.7 32 bit machine; using virutalenv to isolate what I'm doing from everything else (coming from a ruby/rvm background this just makes me feel better--but I'm open to correction if it's not the "python way"). I have the following modules/libs installed: ``` DateUtils-0.5.1-py2....
For someone else coming googling around, the one liner you search is currently: ``` pip install -U 'http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.0.1/matplotlib-1.0.1.tar.gz/download' ```
Get sorted combinations
5,560,479
4
2011-04-06T01:20:50Z
5,560,509
9
2011-04-06T01:24:57Z
[ "python", "combinations" ]
I have a input like A = [2,0,1,3,2,2,0,1,1,2,0]. Following I remove all the duplicates by A = list(Set(A)) A is now [0,1,2,3]. Now I want all the pair combinations that I can make with this list, however they do not need to be unique... thus [0,3] equals [3,0] and [2,3] equals [3,2]. In this example it should return ...
``` >>> A = [2,0,1,3,2,2,0,1,1,2,0] >>> A = sorted(set(A)) # list(set(A)) is not usually in order >>> from itertools import combinations >>> list(combinations(A, 2)) [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] >>> map(list, combinations(A, 2)) [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]] ``` --- ``` >>> h...
How to read text from a Tkinter Text Widget
5,560,828
7
2011-04-06T02:29:06Z
5,561,178
11
2011-04-06T03:38:20Z
[ "python", "tkinter" ]
``` from Tkinter import * window = Tk() frame=Frame(window) frame.pack() text_area = Text(frame) text_area.pack() text1 = text_area.get('0.0',END) def cipher(data): As,Ts,Cs,Gs, = 0,0,0,0 for x in data: if 'A' == x: As+=1 elif x == 'T': Ts+=1 elif x =='C': ...
I think you misunderstand some concepts of Python an Tkinter. When you create the Button, command should be a reference to a function, i.e. the function name without the (). Actually, you call the cipher function once, at the creation of the button. You cannot pass arguments to that function. You need to use global va...
How to scrape HTTPS javascript web pages
5,561,950
7
2011-04-06T05:41:46Z
5,562,003
7
2011-04-06T05:48:26Z
[ "java", "javascript", "python", "https", "web-scraping" ]
I am trying to monitor day-to-day prices from an online catalogue. The site uses HTTPS and generates the catalogue pages with javascript. How can i interface with the site and make it generate the pages I need? I have done this with other sites where the HTML can easily be accessed, I have no problem parseing the HTML...
Take a look at [HTMLUnit](http://htmlunit.sourceforge.net/apidocs/index.html) - a headless Java browser that can be fully controlled by your code. A simple example can be seen here: <http://htmlunit.sourceforge.net/gettingStarted.html> (obligatory warning: by screen-scraping the site, you may be breaking its ToS, and ...
raw_input function in Python
5,563,089
35
2011-04-06T07:52:08Z
5,563,119
60
2011-04-06T07:54:52Z
[ "python", "python-2.x" ]
What is the `raw_input` function? Is it a user interface? When do we use it?
It presents a prompt to the user (the optional `arg` of `raw_input([arg])`), gets input from the user and returns the data input by the user in a string. See the docs for [`raw_input()`](https://docs.python.org/2/library/functions.html#raw_input). Example: ``` name = raw_input("What is your name? ") print "Hello, %s....
Check for positive or semi-positive definite matrix
5,563,743
5
2011-04-06T08:51:25Z
5,563,883
13
2011-04-06T09:03:42Z
[ "python", "math", "scipy", "scientific-computing" ]
I want to check if a matrix is positive or semi-positive definite using Python. How can I do that? Is there a dedicated function in scipy for that or in other modules?
I assume you already know your matrix is symmetric. A good test for positive definiteness (actually the standard one !) is to try to compute its Cholesky factorization. It succeeds iff your matrix is positive definite. This is the most direct way, since it needs O(n^3) operations (with a small constant), and you woul...
Repeat NumPy array without replicating data?
5,564,098
18
2011-04-06T09:20:56Z
5,568,169
21
2011-04-06T14:37:32Z
[ "python", "memory", "numpy", "large-data" ]
I'd like to create a 1D NumPy array that would consist of 1000 back-to-back repetitions of another 1D array, without replicating the data 1000 times. Is it possible? If it helps, I intend to treat both arrays as immutable.
By "not replicating data" I am assuming you mean "not allocating more memory". In that you just want a view of the data repeating 1000 times. Setup: ``` import numpy as np a = np.arange(10) ``` Make a veiw of a that repeats using no extra allocated memory. (However, this trick can only produce a 2D array) ``` b = n...
How to avoid django "clashes with related m2m field" error?
5,564,782
3
2011-04-06T10:19:43Z
5,565,239
10
2011-04-06T11:00:02Z
[ "python", "django", "django-models" ]
I have a lot of models with voting functionality, so I created a structure like this: ``` class Voteable(models.Model): likes_balance = models.IntegerField(default=0, editable=False) votes = models.ManyToManyField(User, blank=True, editable=False) likes = models.ManyToManyField(User, blank=True, editable=F...
[I found a solution in Django documention](https://docs.djangoproject.com/en/dev/topics/db/models/#be-careful-with-related-name). It's possible to write in abstract models things like this:`related_name="%(app_label)s_%(class)s_related"`
How to mock external servers in Python unit tests?
5,565,165
7
2011-04-06T10:53:33Z
5,567,038
9
2011-04-06T13:21:15Z
[ "python", "unit-testing", "mocking" ]
I have several unit tests that take a long time (minutes) because of calls to external services (Twitter, Facebook, Klout, etc.) I'd like to cache the results from these services and serve them transparently, with minimal changes to my current tests. The cache key depends on the URL, query arguments, headers, etc., so...
You would (should) usually use some kind of adapter to connect to these external services, modules. These are your interfaces to the outside world and can be [mock](http://en.wikipedia.org/wiki/Mock_object)ed and fake responses created depending on scenario. I've experimented with a number of mocking libraries and fin...
Detecting hangs with Python urllib2.urlopen
5,565,291
11
2011-04-06T11:04:06Z
5,565,757
9
2011-04-06T11:43:14Z
[ "python", "sockets", "networking" ]
I'm using [Python's urllib2](http://docs.python.org/library/urllib2.html) to send an HTTP post: ``` import socket, urllib, urllib2 socket.setdefaulttimeout(15) postdata = urllib.urlencode({'value1' : 'a string', 'value2' : 'another string'}) headers = { 'User-Agent': 'Agent', 'Content-Type': 'application...
You can use signals, first set a handler for your signal ``` import signal ... def handler(signum, frame): print 'Signal handler called with signal', signum ... signal.signal(signal.SIGALRM, handler) ``` and put an alarm just before the *urlopen* call ``` signal.alarm(5) response = urllib2.urlopen(request) signa...
Why is this shell script calling itself as python script?
5,565,340
12
2011-04-06T11:08:47Z
5,565,601
8
2011-04-06T11:30:25Z
[ "android", "python", "sh" ]
Obviously this shell script is calling itself as a Python script: ``` #!/bin/sh ## repo default configuration ## REPO_URL='git://android.git.kernel.org/tools/repo.git' REPO_REV='stable' magic='--calling-python-from-/bin/sh--' """exec" python -E "$0" "$@" """#$magic" if __name__ == '__main__': import sys if sys.ar...
Your first question: this is done to fix unix systems (or emulations thereof) that do not handle the #! correctly or at all. The high art is to make a script that is coreect in shell as well as in the other language. For perl, one often sees something like: ``` exec "/usr/bin/perl" if 0; ``` The exec is interprete...
how to get [(1, 2, 3, 4), (5, 6, 7, 8)] in my code using python
5,566,160
3
2011-04-06T12:15:25Z
5,566,188
8
2011-04-06T12:17:32Z
[ "python" ]
this is my code : ``` a = [(1,2),(5,6)] b = [(3,4),(7,8)] print zip(a,b) ``` and it show : ``` [((1, 2), (3, 4)), ((5, 6), (7, 8))] ``` but i want get : ``` [(1, 2, 3, 4), (5, 6, 7, 8)] ``` so what can i do , thanks
Try this: ``` [aa+bb for aa,bb in zip(a,b)] ```
PyLab title/legend labels with multiple line of text
5,568,288
5
2011-04-06T14:45:28Z
5,570,024
9
2011-04-06T16:48:41Z
[ "python", "matplotlib" ]
Is it possible to make multiple lines of text inside a title/legend label in pylab?
Yes, just use the \n escape sequence inside it. ``` element = pylab.plot(range(100)) pylab.legend([element],[ "first line \n second line"]) ```