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 GTK "Getting started" tutorial problem
4,523,790
4
2010-12-24T02:01:45Z
4,523,801
7
2010-12-24T02:05:38Z
[ "python", "gtk", "pygtk" ]
I have a problem with compiling a basic and really simple example of PyGTK usage listed on pygtk's website. This is the first example from this site: <http://www.pygtk.org/pygtk2tutorial/ch-GettingStarted.html> My code looks like this: ``` #!/usr/bin/env python # example gtk.py import pygtk pygtk.require('2.0') im...
Yep, it seems like you might have named your script "gtk.py". Which is a bad idea for what should be fairly obvious reasons!
Writing docstrings - specifying functions arguments and returns
4,524,450
3
2010-12-24T05:38:56Z
4,524,486
7
2010-12-24T05:49:15Z
[ "python", "docstring" ]
Suppose I have a function, say: ``` >>> def foo(a): return a+1 ``` I want to write a documentation string for it. what is the convention in specifying in the docstring that it takes a and returns a+1?
The idea of a docstring is to give the user a basic overview of what's going in and coming out without telling them too much about how that happens. In this case: ``` def foo(a): """Take a number a and return its value incremented by 1.""" return a + 1 ``` For a less trivial example, I like the one in [Dive I...
Take screenshot in Python on Mac OS X
4,524,723
5
2010-12-24T06:52:55Z
4,525,615
12
2010-12-24T10:07:19Z
[ "python", "osx", "screenshot" ]
ImageGrab from PIL would have been ideal. I'm looking for similar functionality, specifically the ability to define the screenshot's bounding box. I've been looking for a library to do so on Mac OS X but haven't had any luck. I also wasn't able to find any sample code to do it (maybe pyobjc?).
While not exactly what you want, in a pinch you might just use: ``` os.system("screencapture screen.png") ``` Then open that image with the Image module. I'm sure a better solution exists though.
Take screenshot in Python on Mac OS X
4,524,723
5
2010-12-24T06:52:55Z
13,026,264
8
2012-10-23T08:26:00Z
[ "python", "osx", "screenshot" ]
ImageGrab from PIL would have been ideal. I'm looking for similar functionality, specifically the ability to define the screenshot's bounding box. I've been looking for a library to do so on Mac OS X but haven't had any luck. I also wasn't able to find any sample code to do it (maybe pyobjc?).
Here's how to capture and save a screenshot with PyObjC, based on [my answer here](http://stackoverflow.com/a/13024603/745) You can capture the entire screen, or specify a region to capture. If you don't need to do that, I'd recommend just calling the `screencapture` command (more features, more robust, and quicker - ...
SQLAlchemy declarative syntax with autoload (reflection) in Pylons
4,526,498
7
2010-12-24T13:02:38Z
4,555,998
8
2010-12-29T16:51:55Z
[ "python", "reflection", "sqlalchemy", "pylons", "declarative" ]
I would like to use autoload to use an existings database. I know how to do it without declarative syntax (model/\_*init*\_.py): ``` def init_model(engine): """Call me before using any of the tables or classes in the model""" t_events = Table('events', Base.metadata, schema='events', autoload=True, autoload_wi...
OK, I think I figured it out. The solution is to declare the model objects outside the `model/__init__.py`. I concluded that `__init__.py` gets imported as the first file when importing something from a module (in this case `model`) and this causes problems because the model objects are declared before `init_model()` i...
repeated phrases in the text Python
4,526,762
2
2010-12-24T14:11:45Z
4,528,371
7
2010-12-24T21:16:43Z
[ "python", "text", "repeat" ]
I have a problem and I have no idea how to solve it. Please, give a piece of advice. I have a text. Big, big text. The task is to find all the repeated phrases which lenght is 3(contain of three words) in the text.
You have, it seems to me, two problems. The first is coming up with an efficient way of normalizing the input. You say you want to find all of the three-word phrases in the input, but what constitutes a phrase? For instance, are `the black dog` and `The black, dog?` the same phrase? A way of doing this, as marcog sug...
Python urllib2. URLError: <urlopen error [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted>
4,526,933
4
2010-12-24T14:58:56Z
4,527,161
7
2010-12-24T15:57:41Z
[ "python", "urllib2" ]
I'm making multiple connection to API. Making delete query. I got that error on a 3000'th query. Something like this: ``` def delete_request(self,path): opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request('%s%s'%(self.endpoint,path)) signature = self._gen_auth('DELETE', path, '')...
The error comes from Windows itself, see [Avoiding TCP/IP Port Exhaustion](http://msdn.microsoft.com/en-us/library/aa560610%28v=bts.20%29.aspx). To fix the error close your connection, you are not calling opener.close() hence leaking sockets.
how to install numpy and scipy on OS X?
4,527,338
6
2010-12-24T16:38:28Z
4,527,357
8
2010-12-24T16:43:56Z
[ "python", "osx", "numpy", "scipy" ]
Hey guys I'm new to Mac so please bear with me. I'm using snow leopard 10.6.4 at the moment. I want to install numpy and scipy, so I downloaded the python2.6,numpy and scipy dmg files from their official site. However, I'm having problem import numpy: ``` Library/Frameworks/Python.framework/Versions/2.6/lib/python2....
Sounds as though you might be trying to use a 32-bit library from a 64-bit Python. Looks like there's an unofficial [64-bit Numpy available for Snow Leopard](http://www.scipy.org/Download#head-eb99a6ef6be4f9225176b355d92f2afb59a90602). --- EDIT: The Python 2.6 .dmg available [here](http://www.python.org/download/rele...
how to install numpy and scipy on OS X?
4,527,338
6
2010-12-24T16:38:28Z
12,772,070
7
2012-10-07T19:25:07Z
[ "python", "osx", "numpy", "scipy" ]
Hey guys I'm new to Mac so please bear with me. I'm using snow leopard 10.6.4 at the moment. I want to install numpy and scipy, so I downloaded the python2.6,numpy and scipy dmg files from their official site. However, I'm having problem import numpy: ``` Library/Frameworks/Python.framework/Versions/2.6/lib/python2....
I had the same error message when I was trying my freshly-installed numpy and scipy in python2.7 on Mac OSX 10.6.8 . Later I found out that there were two .dmg for python2.7: * numpy-1.6.2-py2.7-python.org-macosx10.3.dmg * numpy-1.6.2-py2.7-python.org-macosx10.6.dmg It was the package in 10.3.dmg giving me the error ...
Python Dictionary contains List as Value - How to update?
4,527,454
18
2010-12-24T17:06:49Z
4,527,479
16
2010-12-24T17:11:55Z
[ "python", "list", "dictionary" ]
I have a dictionary which has value as a list. ``` dictionary = { 'C1' : [10,20,30] 'C2' : [20,30,40] } ``` Let's say I want to increment all the values in list of C1 by 10, how do I do it? `dictionary.get('C1')` gives me the list but how do i update it?
``` >>> dictionary = {'C1' : [10,20,30],'C2' : [20,30,40]} >>> dictionary['C1'] = [x+1 for x in dictionary['C1']] >>> dictionary {'C2': [20, 30, 40], 'C1': [11, 21, 31]} ```
Check if module exists, if not install it in python
4,527,554
12
2010-12-24T17:30:44Z
4,527,622
9
2010-12-24T17:48:51Z
[ "python", "module", "import" ]
Hay, i want to check if a module exists, if it doesn't install it. Any ideas how to do this? So far i have this code which correctly prints 'f' if the module doesn't exist. ``` try: import keyring except ImportError: print 'f' ``` Thanks
Here is how it should be done, and if I am wrong, please correct me. However, Noufal seems to confirm it in another answer to this question, so I guess it's right. When writing the `setup.py` script for some scripts I wrote, I was dependent on the package manager of my distribution to install the required library for ...
Check if module exists, if not install it in python
4,527,554
12
2010-12-24T17:30:44Z
4,529,027
7
2010-12-25T01:55:29Z
[ "python", "module", "import" ]
Hay, i want to check if a module exists, if it doesn't install it. Any ideas how to do this? So far i have this code which correctly prints 'f' if the module doesn't exist. ``` try: import keyring except ImportError: print 'f' ``` Thanks
This approach of dynamic import work really well in cases you just want to print a message if module is not installed. Automatically installing a module **SHOULDN'T** be done like issuing pip via `subprocess`. That's why we have setuptools (or distribute). [We have some great tutorials on packaging](http://guide.pytho...
Comparing two dictionaries in Python
4,527,942
71
2010-12-24T19:09:12Z
4,527,957
76
2010-12-24T19:11:54Z
[ "python", "dictionary", "comparison" ]
I have two dictionaries, but for simplification, I will take these two: ``` >>> x = dict(a=1, b=2) >>> y = dict(a=2, b=2) ``` Now, I want to compare whether each `key, value` pair in `x` has the same corresponding value in `y`. So I wrote this: ``` >>> for x_values, y_values in zip(x.iteritems(), y.iteritems()): ...
What you want to do is simply `x==y` What you do is not a good idea, because the items in a dictionary are not supposed to have any order. You might be comparing `[('a',1),('b',1)]` with `[('b',1), ('a',1)]` (same dictionaries, different order). For example, see this: ``` >>> x = dict(a=2, b=2,c=3, d=4) >>> x {'a': ...
Comparing two dictionaries in Python
4,527,942
71
2010-12-24T19:09:12Z
4,527,978
67
2010-12-24T19:17:26Z
[ "python", "dictionary", "comparison" ]
I have two dictionaries, but for simplification, I will take these two: ``` >>> x = dict(a=1, b=2) >>> y = dict(a=2, b=2) ``` Now, I want to compare whether each `key, value` pair in `x` has the same corresponding value in `y`. So I wrote this: ``` >>> for x_values, y_values in zip(x.iteritems(), y.iteritems()): ...
If you want to know how many values match in both the dictionaries, you should have said that :) Maybe something like this: ``` shared_items = set(x.items()) & set(y.items()) print len(shared_items) ```
Comparing two dictionaries in Python
4,527,942
71
2010-12-24T19:09:12Z
17,095,033
30
2013-06-13T19:04:40Z
[ "python", "dictionary", "comparison" ]
I have two dictionaries, but for simplification, I will take these two: ``` >>> x = dict(a=1, b=2) >>> y = dict(a=2, b=2) ``` Now, I want to compare whether each `key, value` pair in `x` has the same corresponding value in `y`. So I wrote this: ``` >>> for x_values, y_values in zip(x.iteritems(), y.iteritems()): ...
I'm new to python but I ended up doing something similar to @mouad ``` unmatched_item = set(dict_1.items()) ^ set(dict_2.items()) len(unmatched_item) # should be 0 ``` The XOR operator (`^`) should eliminate all elements of the dict when they are the same in both dicts.
Comparing two dictionaries in Python
4,527,942
71
2010-12-24T19:09:12Z
18,860,653
34
2013-09-17T22:02:10Z
[ "python", "dictionary", "comparison" ]
I have two dictionaries, but for simplification, I will take these two: ``` >>> x = dict(a=1, b=2) >>> y = dict(a=2, b=2) ``` Now, I want to compare whether each `key, value` pair in `x` has the same corresponding value in `y`. So I wrote this: ``` >>> for x_values, y_values in zip(x.iteritems(), y.iteritems()): ...
``` def dict_compare(d1, d2): d1_keys = set(d1.keys()) d2_keys = set(d2.keys()) intersect_keys = d1_keys.intersection(d2_keys) added = d1_keys - d2_keys removed = d2_keys - d1_keys modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]} same = set(o for o in intersect_keys ...
Comparing two dictionaries in Python
4,527,942
71
2010-12-24T19:09:12Z
29,932,489
22
2015-04-29T00:51:26Z
[ "python", "dictionary", "comparison" ]
I have two dictionaries, but for simplification, I will take these two: ``` >>> x = dict(a=1, b=2) >>> y = dict(a=2, b=2) ``` Now, I want to compare whether each `key, value` pair in `x` has the same corresponding value in `y`. So I wrote this: ``` >>> for x_values, y_values in zip(x.iteritems(), y.iteritems()): ...
Just use: ``` assert cmp(dict1, dict2) == 0 ```
Python virtualenv questions
4,527,958
26
2010-12-24T19:11:56Z
4,528,057
47
2010-12-24T19:38:52Z
[ "python", "windows", "linux", "virtualenv" ]
I'm using VirtualEnv on Windows XP. I'm wondering if I have my brain wrapped around it correctly. I ran `virtualenv ENV` and it created `C:\WINDOWS\system32\ENV`. I then changed my `PATH` variable to include `C:\WINDOWS\system32\ENV\Scripts` instead of `C:\Python27\Scripts`. Then, I checked out Django into `C:\WINDOWS...
Normally `virtualenv` creates environments in the current directory. Unless you're intending to create virtual environments in `C:\Windows\system32` for some reason, I would use a different directory for environments. You shouldn't need to mess with paths: use the `activate` script (in `<env>\Scripts`) to ensure that ...
Convert string to JSON using Python
4,528,099
92
2010-12-24T19:48:19Z
4,528,110
198
2010-12-24T19:51:47Z
[ "python", "json", "string", "dictionary" ]
I'm a little bit confused with JSON in Python. To me, it seems like a dictionary, and for that reason I'm trying to do that: ``` { "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": ...
[`json.loads()`](http://docs.python.org/library/json.html#json.loads) ``` d = json.loads(j) print d['glossary']['title'] ```
Convert string to JSON using Python
4,528,099
92
2010-12-24T19:48:19Z
4,535,307
11
2010-12-26T20:33:36Z
[ "python", "json", "string", "dictionary" ]
I'm a little bit confused with JSON in Python. To me, it seems like a dictionary, and for that reason I'm trying to do that: ``` { "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": ...
use simplejson or cjson for speedups ``` import simplejson as json json.loads(obj) or cjson.decode(obj) ```
Convert string to JSON using Python
4,528,099
92
2010-12-24T19:48:19Z
12,455,202
35
2012-09-17T07:59:52Z
[ "python", "json", "string", "dictionary" ]
I'm a little bit confused with JSON in Python. To me, it seems like a dictionary, and for that reason I'm trying to do that: ``` { "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": ...
When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted Here is the simple solution ``` import json m = {'id': 2, 'name': 'hussain'} n = json.dumps(m) o = json.loads(n) print o['id'], o['name'] ```
Clear all widgets in a layout in pyqt
4,528,347
14
2010-12-24T21:07:06Z
13,103,617
31
2012-10-27T19:50:55Z
[ "python", "qt", "pyqt", "pyqt4" ]
Is there a way to clear (delete) all the widgets in a layout? ``` self.plot_layout = QtGui.QGridLayout() self.plot_layout.setGeometry(QtCore.QRect(200,200,200,200)) self.root_layout.addLayout(self.plot_layout) self.plot_layout.addWidget(MyWidget()) ``` Now I want to replace the widget in `plot_layout`...
After a lot of research (and this one took quite time, so I add it here for future reference), this is the way I found to really clear and **delete** the widgets in a layout: ``` for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) ``` What the documentation says about the ...
Clear all widgets in a layout in pyqt
4,528,347
14
2010-12-24T21:07:06Z
25,330,164
7
2014-08-15T16:18:21Z
[ "python", "qt", "pyqt", "pyqt4" ]
Is there a way to clear (delete) all the widgets in a layout? ``` self.plot_layout = QtGui.QGridLayout() self.plot_layout.setGeometry(QtCore.QRect(200,200,200,200)) self.root_layout.addLayout(self.plot_layout) self.plot_layout.addWidget(MyWidget()) ``` Now I want to replace the widget in `plot_layout`...
The answer from PALEN works well if you do not need to put new widgets to your layout. ``` for i in reversed(range(layout.count())): layout.itemAt(i).widget().setParent(None) ``` But you will get a "Segmentation fault (core dumped)" at some point if you empty and fill the layout many times or with many widgets. ...
In Python, is use of `del` statement a code smell?
4,528,403
25
2010-12-24T21:28:39Z
4,528,418
21
2010-12-24T21:35:34Z
[ "python", "del" ]
I tend to use it whenever I am working on a prototype script, and: 1. Use a somewhat common variable (such as `fileCount`), and 2. Have a large method (20+ lines), and 3. Do not use classes or namespaces yet. In this situation, in order to avoid potential variable clash, I delete the bugger as soon as I am done with ...
I don't think that `del` by itself is a code smell. Reusing a variable name in the same namespace is definitely a code smell as is not using classes and other namespaces where appropriate. So using `del` to facilitate that sort of thing is a code smell. The only really appropriate use of `del` that I can think of off...
Wrapping around a python list as a slice operation
4,528,740
11
2010-12-24T23:41:49Z
4,528,747
12
2010-12-24T23:45:02Z
[ "python", "slice" ]
Consider the following simple python code ``` >>> L = range(3) >>> L [0, 1, 2] ``` We can take slices of this array as follows: ``` >>> L[1:3] [1, 2] ``` Is there any way to wrap around the above array by shifting to the left ``` [1, 2, 0] ``` by simply using slice operations?
Rotate left `n` elements (or right for negative n): ``` L = L[n:] + L[:n] ``` Note that [collections.deque](http://docs.python.org/library/collections.html#collections.deque) has support for [rotations](http://docs.python.org/library/collections.html#collections.deque.rotate). It might be better to use that instead o...
Python Telnet connection
4,528,831
9
2010-12-25T00:16:50Z
4,530,252
7
2010-12-25T12:28:58Z
[ "python", "telnet" ]
I was playing around with python 3.1 when I came to a problem. I want to connect to a telnet server. Here is my code: ``` import sys import telnetlib tn = telnetlib.Telnet("10.0.0.138") tn.read_until(b"Username :", 2) tn.write(b"\n") tn.read_until(b"Password :", 2) tn.write(b"\n") tn.read_until(b"=>", 2) tn.write...
Lol, i had pretty much the same router as you. Try this, bit of my old code: ``` tn = telnetlib.Telnet(HOST) tn.read_until('Username : ') tn.write(user+ "\r") tn.read_until("Password : ") tn.write(password+ "\n") tn.write("\r") ``` This is for Python 2, but try just adding the extra space after the semicolon. A...
Convert alphabet letters to number in Python
4,528,982
22
2010-12-25T01:36:45Z
4,528,997
41
2010-12-25T01:42:59Z
[ "python" ]
How can the following be finished? ``` characters = ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''t''u''v''w''x''y''z'] numbers = ['1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24'] text = raw_input(' Write text: ') ``` I've tried to solve it many ways, but couldn't get...
What about something like this: ``` print [ord(char) - 96 for char in raw_input('Write Text: ').lower()] ``` [ord](http://docs.python.org/library/functions.html#ord) [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) [ASCII character codes](http://www.asciitable.com/) *...
Convert alphabet letters to number in Python
4,528,982
22
2010-12-25T01:36:45Z
4,535,403
7
2010-12-26T21:02:05Z
[ "python" ]
How can the following be finished? ``` characters = ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''t''u''v''w''x''y''z'] numbers = ['1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24'] text = raw_input(' Write text: ') ``` I've tried to solve it many ways, but couldn't get...
If you are going to use this conversion a lot, consider calculating once and putting the results in a dictionary: ``` >>> import string >>> di=dict(zip(string.letters,[ord(c)%32 for c in string.letters])) >>> di['c'] 3 ``` The advantage is dictionary lookups are very fast vs iterating over a list on every call. ```...
What does this Python one-liner mean?
4,529,452
6
2010-12-25T05:57:33Z
4,529,488
11
2010-12-25T06:13:04Z
[ "python", "syntax" ]
``` s=p=1;exec"if s%p*s%~-~p:print`p`+','+`p+2`\ns*=p*p;p+=2\n"*999 ``` [Source.](http://golf.shinh.org/reveal.rb?Twin+primes/hiro.suzuki%E3%80%80/1187877291&py)
Here is an unraveling of the basic idea. ``` # p = 1; s = p s=p=1 #exec"if s%p*s%~-~p:print`p`+','+`p+2`\ns*=p*p;p+=2\n"*999 for i in range(999): # s%p = remainder of s/p # ~p = 1s complement of p if s%p*s%~-~p: # `p` = repr(p) print`p`+','+`p+2` # s = s*p*p s*=p*p # p = p+2 ...
how to remove these '&quot;' in django template
4,529,484
10
2010-12-25T06:09:15Z
4,529,492
16
2010-12-25T06:17:44Z
[ "javascript", "python", "django" ]
this is my code in `homepage.html`: ``` <script type="text/javascript"> var jstree_jsondata={{json1}}; alert(typeof jstree_jsondata) </script> ``` and it show this in the source code : ``` var jstree_jsondata= [ { &quot;data&quot; : &quot;kkkqq node&quot;, &quot;attr&quot; : { &quot;id&quot; : &quot;ooo&...
Change the line: ``` var jstree_jsondata={{json1}} ``` to ``` var jstree_jsondata={{ json1|safe }} ``` This uses the `safe` filter to tell Django that the contents should be output literally without changing characters to html entities. The reason for the name 'safe' is that you are declaring that the data to be ou...
Saving an Object (Data persistence in Python)
4,529,815
81
2010-12-25T09:02:03Z
4,529,901
159
2010-12-25T09:35:16Z
[ "python", "object", "save", "pickle" ]
I've created an object like this: ``` company1.name = 'banana' company1.value = 40 ``` I would like to save this object. How can I do that?
You could use the `pickle` module in the standard library. Here's an elementary application of it to your example: ``` import pickle class Company(object): def __init__(self, name, value): self.name = name self.value = value with open('company_data.pkl', 'wb') as output: company1 = Company(...
Saving an Object (Data persistence in Python)
4,529,815
81
2010-12-25T09:02:03Z
25,119,089
14
2014-08-04T12:49:23Z
[ "python", "object", "save", "pickle" ]
I've created an object like this: ``` company1.name = 'banana' company1.value = 40 ``` I would like to save this object. How can I do that?
I think it's a pretty strong assumption to assume that the object is a `class`. What if it's not a `class`? There's also the assumption that the object was not defined in the interpreter. What if it was defined in the interpreter? Also, what if the attributes were added dynamically? When some python objects have attrib...
Python: How to get a value of datetime.today() that is "timezone aware"?
4,530,069
122
2010-12-25T10:59:49Z
4,530,166
166
2010-12-25T11:44:33Z
[ "python", "datetime", "date", "timezone" ]
I am trying to subtract one date value from the value of `datetime.today()` to calculate how long ago something was. But it complains: ``` TypeError: can't subtract offset-naive and offset-aware datetimes ``` The value `datetime.today()` doesn't seem to be "timezone aware", while my other date value is. How do I get ...
In the standard library, there is no cross-platform way to create aware timezones without creating your own timezone class. On Windows, there's `win32timezone.utcnow()`, but that's part of pywin32. I would rather suggest to use the [pytz library](http://pytz.sourceforge.net/), which has an up-to-date database of most ...
Python: How to get a value of datetime.today() that is "timezone aware"?
4,530,069
122
2010-12-25T10:59:49Z
14,796,941
8
2013-02-10T10:51:11Z
[ "python", "datetime", "date", "timezone" ]
I am trying to subtract one date value from the value of `datetime.today()` to calculate how long ago something was. But it complains: ``` TypeError: can't subtract offset-naive and offset-aware datetimes ``` The value `datetime.today()` doesn't seem to be "timezone aware", while my other date value is. How do I get ...
Another method to construct time zone aware datetime object representing current time: ``` import datetime import pytz pytz.utc.localize( datetime.datetime.utcnow() ) ```
Python: How to get a value of datetime.today() that is "timezone aware"?
4,530,069
122
2010-12-25T10:59:49Z
16,660,476
38
2013-05-21T00:50:35Z
[ "python", "datetime", "date", "timezone" ]
I am trying to subtract one date value from the value of `datetime.today()` to calculate how long ago something was. But it complains: ``` TypeError: can't subtract offset-naive and offset-aware datetimes ``` The value `datetime.today()` doesn't seem to be "timezone aware", while my other date value is. How do I get ...
Get the current time, in a specific timezone: ``` import datetime import pytz my_date = datetime.datetime.now(pytz.timezone('US/Pacific')) ```
Python: saving objects and using pickle. extension of filename
4,530,111
14
2010-12-25T11:14:36Z
23,852,816
17
2014-05-25T06:54:25Z
[ "python", "object", "save", "pickle", "file-extension" ]
Hello I´m trying using the next piece of code: ``` import pickle object = Object() filehandler = open(filename, 'w') pickle.dump(object, filehandler) ``` I would like to know what should be the extension of the file 'filename'. Thank you!
You could use any `filename`, but as an FYI it's common to use ".p" (for obvious reasons). ``` pickle.dump( favorite_color, open( "save.p", "wb" ) ) ``` Read: [UsingPickle](https://wiki.python.org/moin/UsingPickle)
Saving and loading objects and using pickle
4,530,611
19
2010-12-25T15:17:17Z
4,530,688
16
2010-12-25T15:50:41Z
[ "python", "object", "pickle" ]
I´m trying to save and load objects using `pickle` module. First I declare my objects: ``` >>> class Fruits:pass ... >>> banana = Fruits() >>> banana.color = 'yellow' >>> banana.value = 30 ``` After that I open a file called 'Fruits.obj'(previously I created a new .txt file and I renamed 'Fruits.obj'): ``` >>> imp...
As for your second problem: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python31\lib\pickle.py", line 1365, in load encoding=encoding, errors=errors).load() EOFError ``` After you have read the contents of the file, the file pointer will be at the end of the file - there w...
Saving and loading objects and using pickle
4,530,611
19
2010-12-25T15:17:17Z
4,531,859
7
2010-12-25T22:05:54Z
[ "python", "object", "pickle" ]
I´m trying to save and load objects using `pickle` module. First I declare my objects: ``` >>> class Fruits:pass ... >>> banana = Fruits() >>> banana.color = 'yellow' >>> banana.value = 30 ``` After that I open a file called 'Fruits.obj'(previously I created a new .txt file and I renamed 'Fruits.obj'): ``` >>> imp...
The following works for me: ``` class Fruits: pass banana = Fruits() banana.color = 'yellow' banana.value = 30 import pickle filehandler = open("Fruits.obj","wb") pickle.dump(banana,filehandler) filehandler.close() file = open("Fruits.obj",'rb') object_file = pickle.load(file) file.close() print(object_file.colo...
Automatically import all modules in the current directory into python interactive interpreter
4,530,763
4
2010-12-25T16:21:42Z
4,530,797
7
2010-12-25T16:29:54Z
[ "python", "matlab", "module", "import" ]
Coming from a Matlab background, I wanted to write small functions in python, and test them individually in the interpreter. However, every time I start the interpreter, I have to import all the modules. In contrast, with matlab all you do is give it the path to the directory and you can execute any matlab function thr...
Try [autoimp](http://www.connellybarnes.com/code/autoimp/). Example from the webpage: ``` >>> from autoimp import * >>> os.stat('.') >>> Image.open('test.bmp') >>> pylab.plot([1,2],[3,4]) >>> scipy.linalg.eig([[1,2],[3,4]]) ```
why does this python script wait till the timer thread is executed?
4,531,164
3
2010-12-25T18:16:51Z
4,531,275
7
2010-12-25T18:57:08Z
[ "python", "execution" ]
``` from threading import Timer def startTimer(): t = Timer(10.0, foo, ['hello world', 'tell me more'] ) t.start() print 'Timer function invoked' print 'function exit' def foo(msg, msg2): print 'foo was executed' print msg print msg2 if __name__ == '__main__': startTimer() print 'end of program'...
Timer is just a thread and Python waits for all non-`daemonic` threads before stopping the interpreter. > A thread can be flagged as a “daemon > thread”. The significance of this flag > is that the entire Python program > exits when only daemon threads are > left. The initial value is inherited > from the creating...
What's the logical value of "string" in Python?
4,531,794
7
2010-12-25T21:45:51Z
4,531,814
8
2010-12-25T21:50:55Z
[ "python", "string", "casting", "boolean" ]
I erroneously wrote this code in Python: ``` name = input("what is your name?") if name == "Kamran" or "Samaneh": print("That is a nice name") else: print("You have a boring name ;)") ``` It always prints out "That is a nice name" even when the input is neither "Kamran" nor "Samaneh". Am I correct in saying ...
Any non empty string in Python (and most other languages) is true as are all non-zero numbers and non-empty lists, dictionaries, sets and tuples.1 A nicer way to do what you want is: ``` name = input("what is your name?") if name in ("Kamran", "Samaneh"): print("That is a nice name") else: print("You have a b...
TypeError: unhashable type: 'dict', when dict used as a key for another dict
4,531,941
37
2010-12-25T22:33:42Z
4,531,954
45
2010-12-25T22:37:28Z
[ "python", "json", "hash" ]
I have this piece of code: ``` for element in json[referenceElement].keys(): ``` When I run that code, I get this error: > TypeError: unhashable type: 'dict' What is the cause of that error and what can I do to fix it?
From the error, I infer that `referenceElement` is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!). ``` >>> d1, d2 = {}, {} >>> d1[d2] = 1 Traceback (most recent call last): File "<input>", line 1, in <module> Type...
Meaning of >> in print statement
4,532,147
15
2010-12-25T23:36:08Z
4,532,152
7
2010-12-25T23:38:02Z
[ "python", "syntax", "python-2.x" ]
I was wondering what does `print >> dbfile, key` mean in python. What is the `>>` supposed to do?
This redirects `print` to a file (in this case, `dbfile`). the `>>` is just a special syntax used for this.
Meaning of >> in print statement
4,532,147
15
2010-12-25T23:36:08Z
4,532,213
12
2010-12-25T23:55:25Z
[ "python", "syntax", "python-2.x" ]
I was wondering what does `print >> dbfile, key` mean in python. What is the `>>` supposed to do?
It should be noted that the `>>` syntax is specific to Python 2.x. In Python 3.x, that syntax goes away and code needs to be changed as follows: ``` print >>f, "Hello world" # Python 2.x print("Hello world", file=f) # Python 3.x ```
How to remove all of the data in a table using django
4,532,681
31
2010-12-26T03:52:53Z
4,532,693
33
2010-12-26T03:58:47Z
[ "python", "django", "model" ]
I have two questions : 1. how to delete the table in django 2. how to remove all of the data in table this is my code, but not successful : ``` Reporter.objects.delete() ```
Inside a manager: ``` def delete_everything(self): Reporter.objects.all().delete() def drop_table(self): cursor = connection.cursor() table_name = self.model._meta.db_table sql = "DROP TABLE %s;" % (table_name, ) cursor.execute(sql) ```
How to remove all of the data in a table using django
4,532,681
31
2010-12-26T03:52:53Z
29,477,118
10
2015-04-06T18:22:51Z
[ "python", "django", "model" ]
I have two questions : 1. how to delete the table in django 2. how to remove all of the data in table this is my code, but not successful : ``` Reporter.objects.delete() ```
As per the latest [documentation](https://docs.djangoproject.com/en/1.8/topics/db/queries/#deleting-objects), the correct method to call would be: ``` Reporter.objects.all().delete() ```
django.db.utils.DatabaseError
4,532,880
5
2010-12-26T05:34:24Z
5,107,904
12
2011-02-24T17:01:00Z
[ "python", "django" ]
I'm setting up a django model to store regions, like USA, Germany, etc. I made the region name unique for the table. I have a script that populates the database from a list and if there is a duplicate region name IntegrityError is thrown as expected but then another error happens and I can't tell why from the error mes...
You should reset your db state if something fails for example: ``` from django.db import transaction @transaction.commit_manually def Populate(): try: Region(name=server['locale']).save() print 'Added region: %(locale)s' % server except IntegrityError: transaction.rollback() else: ...
Python unittest (using SQLAlchemy) does not write/update database?
4,533,245
2
2010-12-26T08:47:37Z
4,533,392
7
2010-12-26T09:45:48Z
[ "python", "unit-testing", "postgresql", "sqlalchemy", "pyramid" ]
I am puzzled at why my Python unittest runs perfectly fine without actually updating the database. I can even see the SQL statements from SQLAlchemy and step through the newly created user object's email -- ``` ...INFO sqlalchemy.engine.base.Engine.0x...954c INSERT INTO users (user_id, user_name, email, ...) VALUES (...
Not knowing SQLAlchemy, but that sounds like the test is being run in a transaction and that this transaction is never committed. Either explicitly rolled back, or automatically rolled back when the connection closes.
Is using readlines in Python bad code?
4,533,884
5
2010-12-26T12:53:54Z
4,533,893
9
2010-12-26T12:56:15Z
[ "python" ]
I got downvoted for an answer using file.readlines. The critic said that using readlines is crap code (along with other very rude statements). Is it so bad?
I assume that the problem was the fact that `readlines()` loads the whole file into memory, which - theoretically - can be a lot. A lazy approach (iterating over the file and reading progressively as needed) is indeed better in terms of memory usage. Not sure about efficiency, though.
How to test python code on command line
4,534,058
2
2010-12-26T13:57:24Z
4,534,062
7
2010-12-26T13:59:59Z
[ "python", "class", "command-line", "module", "reload" ]
While writing and testing a python method, I am currently using the following approach: ``` import foo as f bar = f.bar() bar.runMyMethodAndSeeIfItWorks() ``` If I change something in my method, and I need to retest it, I have to execute the following: ``` f = reload(foo) bar = f.bar() bar.runMyMethodAndSeeIfItWor...
Write a real unit test, and run it from the command line. I find this is one of the most compelling reasons for adopting unit testing: you're going to need to try out your methods as you write them anyway, you might as well do it in a form that will be runnable for evermore after that.
TypeError: 'module' object is not callable
4,534,438
180
2010-12-26T15:56:50Z
4,534,443
262
2010-12-26T15:59:34Z
[ "python", "sockets" ]
``` File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__ self.serv = socket(AF_INET,SOCK_STREAM) TypeError: 'module' object is not callable ``` Why am I getting this error? I'm confused. What do you need to know to answer my question?
`socket` is a module, containing the class `socket`. You need to do `socket.socket(...)` or `from socket import socket`: ``` >>> import socket >>> socket <module 'socket' from 'C:\Python27\lib\socket.pyc'> >>> socket.socket <class 'socket._socketobject'> >>> >>> from socket import socket >>> socket <class 'socket._so...
TypeError: 'module' object is not callable
4,534,438
180
2010-12-26T15:56:50Z
4,534,445
12
2010-12-26T15:59:50Z
[ "python", "sockets" ]
``` File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__ self.serv = socket(AF_INET,SOCK_STREAM) TypeError: 'module' object is not callable ``` Why am I getting this error? I'm confused. What do you need to know to answer my question?
It seems like what you've done is imported the `socket` module as `import socket`. Therefore `socket` is the module. You either need to change that line to `self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)`, as well as every other use of the `socket` module, or change the import statement to `from socket i...
TypeError: 'module' object is not callable
4,534,438
180
2010-12-26T15:56:50Z
14,248,105
18
2013-01-09T23:07:00Z
[ "python", "sockets" ]
``` File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__ self.serv = socket(AF_INET,SOCK_STREAM) TypeError: 'module' object is not callable ``` Why am I getting this error? I'm confused. What do you need to know to answer my question?
Here is another gotcha, that took me awhile to see even after reading these posts. I was setting up a script to call my python bin scripts. I was getting the module not callable too. My zig was that I was doing the following: ``` from mypackage.bin import myscript ... myscript(...) ``` when my zag needed to do the f...
TypeError: 'module' object is not callable
4,534,438
180
2010-12-26T15:56:50Z
26,929,628
29
2014-11-14T12:05:07Z
[ "python", "sockets" ]
``` File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__ self.serv = socket(AF_INET,SOCK_STREAM) TypeError: 'module' object is not callable ``` Why am I getting this error? I'm confused. What do you need to know to answer my question?
Add to "\_\_init\_\_.py", eg: ``` from YourClass import YourClass ``` Then, you will have an instance of your class ready when you import it on another script: ``` from YourClassParentDir import YourClass ```
Get legend as a separate picture in Matplotlib
4,534,480
16
2010-12-26T16:09:53Z
4,534,645
13
2010-12-26T17:01:19Z
[ "python", "matplotlib" ]
I'm developing a Web application and want to display a figure and its legend in different locations on the page. Which means I need to save the legend as a separate png file. Is this possible in Matplotlib in a more or less straightforward way?
This could work: ``` import pylab fig = pylab.figure() figlegend = pylab.figure(figsize=(3,2)) ax = fig.add_subplot(111) lines = ax.plot(range(10), pylab.randn(10), range(10), pylab.randn(10)) figlegend.legend(lines, ('one', 'two'), 'center') fig.show() figlegend.show() figlegend.savefig('legend.png') ``` ![alt text]...
Get legend as a separate picture in Matplotlib
4,534,480
16
2010-12-26T16:09:53Z
9,518,489
8
2012-03-01T15:01:24Z
[ "python", "matplotlib" ]
I'm developing a Web application and want to display a figure and its legend in different locations on the page. Which means I need to save the legend as a separate png file. Is this possible in Matplotlib in a more or less straightforward way?
use `pylab.figlegend(..)` and `get_legend_handles_labels(..)`: ``` import pylab, numpy x = numpy.arange(10) # create a figure for the data figData = pylab.figure() ax = pylab.gca() for i in xrange(3): pylab.plot(x, x * (i+1), label='line %d' % i) # create a second figure for the legend figLegend = pylab.figure...
finding the greatest Fibonacci number within limited time in python
4,534,486
2
2010-12-26T16:11:29Z
4,534,510
7
2010-12-26T16:17:53Z
[ "python" ]
I need a code that calculates nth fibonacci number as well as giving me the time used to calculate it, in python. ``` def fib(n): if n==0 or n==1: return 1 else: return fib(n-1)+fib(n-2) ``` The calculation of the number step must use a such method.
This is a classic dynamic programming/recursion with memoization problem. Notice that in your code, you recursively call `fib(x-1)` a *lot*. This is a huge waste of effort: once you calculate it once, you should store it for later use so that you don't have to calculate it again. In Python 3 you can do this with the gl...
Python Web Framework with best Mongo support
4,534,684
16
2010-12-26T17:14:49Z
4,545,295
10
2010-12-28T10:16:11Z
[ "python", "mongodb" ]
I'm looking to write a small web app to utilise a dataset I already have stored in a MongoDB collection. I've been writing more Python than other languages lately and would like to broaden my repertoire and write a Python web app. It seems however that most if not all of the current popular Python web development fram...
I have not tried MongoKit although it has been around for a while and retains a good reputation. I personally prefer [MongoEngine](http://mongoengine.org) and feel very comfortable with it (maybe because I like its nice homepage and good documentation). There is also a very good opensource project named [Mumblr](https:...
initialize a numpy array
4,535,374
49
2010-12-26T20:52:45Z
4,535,387
64
2010-12-26T20:56:34Z
[ "python", "arrays", "numpy" ]
Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop, I can do: ``` a = [] for i in range(5): a.append(i) ``` I want to do something similar with a numpy array. I know about vstack, concatenate ...
> [`numpy.zeros`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html) > > Return a new array of given shape and > type, filled with zeros. or > [`numpy.ones`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html) > > Return a new array of given shape and > type, filled with ones. or ...
initialize a numpy array
4,535,374
49
2010-12-26T20:52:45Z
4,562,455
14
2010-12-30T12:08:27Z
[ "python", "arrays", "numpy" ]
Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop, I can do: ``` a = [] for i in range(5): a.append(i) ``` I want to do something similar with a numpy array. I know about vstack, concatenate ...
The way I usually do that is by creating a regular list, then append my stuff into it, and finally transform the list to a numpy array as follows : ``` import numpy as np big_array = [] # empty regular list for i in range(5): arr = i*np.ones((2,4)) # for instance big_array.append(arr) big_np_array = np.array(...
Django Asynchronous Processing
4,535,540
7
2010-12-26T21:45:43Z
4,536,676
11
2010-12-27T04:52:33Z
[ "python", "django", "asynchronous", "celery", "cython" ]
I have a bunch of Django requests which executes some mathematical computations ( written in C and executed via a Cython module ) which may take an indeterminate amount ( on the order of 1 second ) of time to execute. Also the requests don't need to access the database and are all independent of each other and Django. ...
Celery would be perfect for this. Since what you're doing is relatively simple (read: you don't need complex rules about how tasks should be routed), you could probably get away with using the Redis backend, which means you don't need to setup/configure RabbitMQ (which, in my experience, is more difficult). I use Red...
Python list should be empty on class instance initialisation, but it's not. Why?
4,535,667
2
2010-12-26T22:25:40Z
4,535,675
8
2010-12-26T22:28:33Z
[ "python", "list", "initialization" ]
I would like to create instances of a class containing a list that's empty by default; instead of later setting this list to the final full list I would like to successively add items to it. Here's a piece of sample code illustrating this: ``` #!/usr/bin/python class test: def __init__(self, lst=[], intg=0): ...
It is a very bad idea to use a mutable object as a default value, as you do here: ``` def __init__(self, lst=[], intg=0): # ... ``` Change it to this: ``` def __init__(self, lst=None, intg=0): if lst is None: lst = [] # ... ``` The reason that your version doesn't work is that the empty list...
python - how to pipe the output using popen?
4,537,259
5
2010-12-27T07:39:09Z
4,537,277
13
2010-12-27T07:42:53Z
[ "python", "popen" ]
I want to `pipe` output of my file using `popen`, how can I do that? **test.py**: ``` while True: print"hello" ``` **a.py** : ``` import os os.popen('python test.py') ``` I want to pipe the output using `os.popen`. how can i do the same?
First of all, os.popen() is deprecated, use the subprocess module instead. You can use it like this: ``` from subprocess import Popen, PIPE output = Popen(['command-to-run', 'some-argument'], stdout=PIPE) print output.stdout.read() ```
python - how to pipe the output using popen?
4,537,259
5
2010-12-27T07:39:09Z
4,537,280
13
2010-12-27T07:43:21Z
[ "python", "popen" ]
I want to `pipe` output of my file using `popen`, how can I do that? **test.py**: ``` while True: print"hello" ``` **a.py** : ``` import os os.popen('python test.py') ``` I want to pipe the output using `os.popen`. how can i do the same?
Use the [`subprocess`](http://docs.python.org/library/subprocess.html) module, here is an example: ``` from subprocess import Popen, PIPE proc = Popen(["python","test.py"], stdout=PIPE) output = proc.communicate()[0] ```
I get a 400 Bad Request error while using django-piston
4,537,314
11
2010-12-27T07:50:52Z
5,427,418
10
2011-03-25T00:58:27Z
[ "python", "django", "json", "rest", "django-piston" ]
I am trying to use Piston to provide REST support to Django. I have implemented my handlers as per the documentation provided . The problem is that i can "read" and "delete" my resource but i cannot "create" or "update". Each time i hit the relevant api i get a 400 Bad request Error. I have extended the Resource class...
This is happening because Piston doesn't like the fact that ExtJS is putting "charset=UTF-8" in the content-type of the header. Easily fixed by adding some middleware to make the content-type a bit more Piston friendly, create a file called middleware.py in your application base directory: ``` class ContentTypeMiddle...
I get a 400 Bad Request error while using django-piston
4,537,314
11
2010-12-27T07:50:52Z
5,604,202
7
2011-04-09T09:40:23Z
[ "python", "django", "json", "rest", "django-piston" ]
I am trying to use Piston to provide REST support to Django. I have implemented my handlers as per the documentation provided . The problem is that i can "read" and "delete" my resource but i cannot "create" or "update". Each time i hit the relevant api i get a 400 Bad request Error. I have extended the Resource class...
Proposed solutions still did not work for me (django 1.2.3/piston 0.2.2) so I've tweaked joekrell solution and this finally works (I'm only using POST and PUT, but presumably you can add other verbs to the list): ``` class ContentTypeMiddleware(object): def process_request(self, request): if request.method in ('...
HTML5 video element non-seekable when using Django development server
4,538,810
7
2010-12-27T13:00:03Z
4,541,728
11
2010-12-27T20:49:18Z
[ "javascript", "python", "django", "html5", "html5-video" ]
I've got a Django app serving a webpage with an HTML5 element. There's a wierd "feature", turning the video element to be non-seekable: `video.seekable` returns a `timeRanges` object with `length=0`, whereas it should be `length=1`. This means I can't edit the video. JavaScript can't do anything either. The thing is,...
Django's dev server probably doesn't support HTTP byte ranges, which is what browsers usually use to implement seeking. Any production web server, e.g. Apache, lighttpd, or nginx, should support these fine. If you can run your entire Django app one of these servers the problem should go away. A workaround would be to...
TemplateSyntaxError: 'settings_tags' is not a valid tag library
4,539,266
6
2010-12-27T14:14:25Z
4,541,966
17
2010-12-27T21:29:31Z
[ "python", "django", "satchmo" ]
i got this error when i try to run this test case: WHICH IS written in tests.py of my django application: ``` def test_accounts_register( self ): self.url = 'http://royalflag.com.pk/accounts/register/' self.c = Client() self.values = { 'email': 'bilal@gmail.com', 'first_name': 'bilal', ...
It seems to me you probably have a code like `{% load settings_tags %}` somewhere in your template. Django looks for `templatetags/settings_tags.py` file in your installed apps' directories. This is the result of not finding a file like this. Maybe the app, which contains it is not in your `INSTALLED_APPS` or maybe it'...
TemplateSyntaxError: 'settings_tags' is not a valid tag library
4,539,266
6
2010-12-27T14:14:25Z
10,880,258
14
2012-06-04T11:07:52Z
[ "python", "django", "satchmo" ]
i got this error when i try to run this test case: WHICH IS written in tests.py of my django application: ``` def test_accounts_register( self ): self.url = 'http://royalflag.com.pk/accounts/register/' self.c = Client() self.values = { 'email': 'bilal@gmail.com', 'first_name': 'bilal', ...
Sometimes this happens when you forgot to put an \_\_ init \_\_.py in the package.
Can I do a reduce on a list comprehension into two lists, based on two values?
4,539,704
2
2010-12-27T15:28:38Z
4,539,747
9
2010-12-27T15:33:28Z
[ "python", "python-2.5" ]
I've got the following code. ``` sum_review = reduce(add,[book['rw'] for book in books]) sum_rating = reduce(add,[book['rg'] for book in books]) items = len(books) avg_review = sum_review/items avg_rating = sum_rating/items ``` What I'd like is this. ``` sum_review,sum_rating = reduce(add,([book['rw'],[book['rg']) f...
I'd avoid using reduce here. For something so simple use `sum`: ``` sum_review = sum(book['rw'] for book in books) sum_rating = sum(book['rg'] for book in books) ``` In my opinion this simpler version doesn't need refactoring to remove redundancy. With just two items (`rw` and `rg`) I think it's best to just leave it...
Python and Unicode: How everything should be Unicode
4,540,791
21
2010-12-27T18:15:29Z
4,541,001
11
2010-12-27T18:45:32Z
[ "python", "unicode", "bytestring" ]
Forgive if this a long a question: I have been programming in Python for around six months. Self taught, starting with the Python tutorial and then SO and then just using Google for stuff. Here is the sad part: No one told me all strings should be Unicode. No, I am not lying or making this up, but where does the tuto...
No, not every string "should be Unicode". Within your Python code, you know if the string literals needs to be Unicode or not, so it doesn't make any sense to make every string literal into a Unicode literal. But there are cases where you should use Unicode. For example, if you have arbitrary input that is text, use U...
Python and Unicode: How everything should be Unicode
4,540,791
21
2010-12-27T18:15:29Z
4,541,305
13
2010-12-27T19:42:40Z
[ "python", "unicode", "bytestring" ]
Forgive if this a long a question: I have been programming in Python for around six months. Self taught, starting with the Python tutorial and then SO and then just using Google for stuff. Here is the sad part: No one told me all strings should be Unicode. No, I am not lying or making this up, but where does the tuto...
The "always use Unicode" suggestion is primarily to make the transition to Python 3 easier. If you have a lot of non-Unicode string access in your code, it'll take more work to port it. Also, you shouldn't have to decide on a case-by-case basis whether a string should be stored as Unicode or not. You shouldn't have to...
Check if a number is int or float
4,541,155
51
2010-12-27T19:14:41Z
4,541,167
97
2010-12-27T19:16:39Z
[ "python" ]
Here's how I did it: ``` inNumber = somenumber inNumberint = int(inNumber) if inNumber == inNumberint: print "this number is an int" else: print "this number is a float" ``` Something like that. Are there any nicer looking ways to do this?
Use [isinstance](http://docs.python.org/library/functions.html#isinstance). ``` >>> x = 12 >>> isinstance(x, int) True >>> y = 12.0 >>> isinstance(y, float) True ``` So: ``` >>> if isinstance(x, int): print 'x is a int!' x is a int! ``` \**EDIT:*\* As pointed out, in case of long integers, the above won't...
Check if a number is int or float
4,541,155
51
2010-12-27T19:14:41Z
4,541,207
11
2010-12-27T19:23:27Z
[ "python" ]
Here's how I did it: ``` inNumber = somenumber inNumberint = int(inNumber) if inNumber == inNumberint: print "this number is an int" else: print "this number is a float" ``` Something like that. Are there any nicer looking ways to do this?
It's easier to ask forgiveness than ask permission. Simply perform the operation. If it works, the object was of an acceptable, suitable, proper type. If the operation doesn't work, the object was not of a suitable type. Knowing the type rarely helps. Simply attempt the operation and see if it works. ``` inNumber = s...
Check if a number is int or float
4,541,155
51
2010-12-27T19:14:41Z
25,455,489
19
2014-08-22T21:02:08Z
[ "python" ]
Here's how I did it: ``` inNumber = somenumber inNumberint = int(inNumber) if inNumber == inNumberint: print "this number is an int" else: print "this number is a float" ``` Something like that. Are there any nicer looking ways to do this?
One-liner: ``` isinstance(yourNumber, numbers.Real) ``` This avoids some problems: ``` >>> isinstance(99**10,int) False ``` Demo: ``` >>> import numbers >>> someInt = 10 >>> someLongInt = 100000L >>> someFloat = 0.5 >>> isinstance(someInt, numbers.Real) True >>> isinstance(someLongInt, numbers.Real) True >>> isi...
How to close a Python thread from within
4,541,190
23
2010-12-27T19:20:38Z
4,541,213
28
2010-12-27T19:24:23Z
[ "python", "multithreading" ]
For every client connecting to my server I spawn a new thread, like this: ``` # Create a new client c = Client(self.server.accept(), globQueue[globQueueIndex], globQueueIndex, serverQueue ) # Start it c.start() # And thread it self.threads.append(c) ``` Now, I know I can close *all* the threads using this code: ``...
When you start a thread, it begins executing a function you give it (if you're extending `threading.Thread`, the function will be `run()`). To end the thread, just return from that function. According to [this](http://docs.python.org/library/thread.html), you can also call `thread.exit()`, which will throw an exceptio...
How to create a DateTime equal to 15 minutes ago?
4,541,629
49
2010-12-27T20:34:04Z
4,541,666
13
2010-12-27T20:40:09Z
[ "python", "datetime" ]
I need to create a DateTime object that represents the current time minus 15 minutes.
``` datetime.datetime.now() - datetime.timedelta(minutes=15) ```
How to create a DateTime equal to 15 minutes ago?
4,541,629
49
2010-12-27T20:34:04Z
4,541,668
89
2010-12-27T20:40:26Z
[ "python", "datetime" ]
I need to create a DateTime object that represents the current time minus 15 minutes.
import datetime and then the magic timedelta stuff: ``` In [63]: datetime.datetime.now() Out[63]: datetime.datetime(2010, 12, 27, 14, 39, 19, 700401) In [64]: datetime.datetime.now() - datetime.timedelta(minutes=15) Out[64]: datetime.datetime(2010, 12, 27, 14, 24, 21, 684435) ```
Modifying a Python dictionary from different threads
4,542,344
11
2010-12-27T22:39:55Z
4,542,587
14
2010-12-27T23:27:24Z
[ "python", "multithreading", "variables", "dictionary", "locking" ]
When it comes to threading, I know you have to make sure you're not editing a variable at the same time another thread is editing it, as your changes can be lost (when incrementing a counter, for example) Does the same apply to dictionaries? Or is a dictionary a collection of variables? If every thread were to lock t...
> Does the same apply to dictionaries? Or is a dictionary a collection of variables? Let's be more general: **What does "atomic operation" mean?** From [Wikipedia](http://en.wikipedia.org/wiki/Atomic_operation) : > In concurrent programming, an > operation (or set of operations) is > atomic, linearizable, indivisib...
Import from sibling directory
4,542,352
19
2010-12-27T22:41:13Z
4,542,391
15
2010-12-27T22:47:26Z
[ "python", "path", "directory", "parent", "sys" ]
I have a Python class called "ClassA" and another Python class which is supposed to import ClassA which is "ClassB". The directory structure is as follows: ``` MainDir ../Dir ..../DirA/ClassA ..../DirB/ClassB ``` How would I use `sys.path` so that ClassB can use ClassA?
You can use [relative import](http://docs.python.org/whatsnew/2.5.html#pep-328) (example from link, current module - `A.B.C`): ``` from . import D # Imports A.B.D from .. import E # Imports A.E from ..F import G # Imports A.F.G ```
Import from sibling directory
4,542,352
19
2010-12-27T22:41:13Z
4,542,450
11
2010-12-27T22:57:20Z
[ "python", "path", "directory", "parent", "sys" ]
I have a Python class called "ClassA" and another Python class which is supposed to import ClassA which is "ClassB". The directory structure is as follows: ``` MainDir ../Dir ..../DirA/ClassA ..../DirB/ClassB ``` How would I use `sys.path` so that ClassB can use ClassA?
You really should be using packages. Then MainDir is placed at a point in the file system on sys.path (e.g. .../site-packages), then you can say in ClassB: ``` from MainDir.Dir.DirA import ClassA # which is actually a module ``` You just have to place files named `__init__.py` in each directory to make it a package h...
Import from sibling directory
4,542,352
19
2010-12-27T22:41:13Z
9,806,045
33
2012-03-21T13:54:44Z
[ "python", "path", "directory", "parent", "sys" ]
I have a Python class called "ClassA" and another Python class which is supposed to import ClassA which is "ClassB". The directory structure is as follows: ``` MainDir ../Dir ..../DirA/ClassA ..../DirB/ClassB ``` How would I use `sys.path` so that ClassB can use ClassA?
*as a literal answer to the question '**Python Import from parent directory**':* to import 'mymodule' that is in the parent directory of your current module: ``` import os parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0,parentdir) import mymodule ``` **edit** Unfortunate...
Google App Engine: how to send html using send_mail
4,542,730
4
2010-12-27T23:53:21Z
4,546,464
7
2010-12-28T13:37:33Z
[ "python", "google-app-engine" ]
I have a app with a kind of rest api that I'm using to send emails . However it currently sends only text email so I need to know how to modify it and make it send html . Below is the code : ``` from __future__ import with_statement #!/usr/bin/env python # import cgi import os import logging import contextlib from x...
Have a look to the [Email message fields](http://code.google.com/intl/it/appengine/docs/python/mail/emailmessagefields.html) of the `send_mail` function. Here is the parameter you need: > **html** > An HTML version of the body content, for recipients that prefer HTML email. You should add the `html` input paramet...
I want to roll 3 dice with independent numbers from each other
4,542,768
3
2010-12-28T00:02:09Z
4,542,784
8
2010-12-28T00:06:37Z
[ "python", "random" ]
I want to write a python program that will simulate 3 dice being rolled at the same time but I want the 3 dice to always have a different number from each other every time they are rolled. ex on the first roll I get 2,1,6 that is fine but I dont want the prog. to ever roll duplicates for ex 2,4,2. (3,3,3, would also be...
Try [`random.sample`](http://docs.python.org/library/random.html#random.sample): ``` >>> sides = 6 >>> dice = random.sample(range(1, sides + 1), 3) [3, 6, 1] ``` I'd advise that you reconsider whether it is a good idea to have variables called `die1`, `die2`, `die3`. It is usually better to use a list as in the abov...
Efficient Context-Free Grammar parser, preferably Python-friendly
4,543,008
15
2010-12-28T01:06:15Z
4,543,154
10
2010-12-28T01:50:37Z
[ "python", "parsing", "nlp", "grammar", "nltk" ]
I am in need of parsing a small subset of English for one of my project, described as a context-free grammar with (1-level) feature structures ([example](http://code.google.com/p/nltk/source/browse/trunk/nltk/examples/grammars/book_grammars/feat0.fcfg?r=8260)) and I need to do it efficiently . Right now I'm using [NLT...
By all means take a look at [Pyparsing](http://pyparsing.wikispaces.com/). It's the most pythonic implementations of parsing I've come across, and it's a great design from a purely academic standpoint. I used both [ANTLR](http://www.antlr.org/) and [JavaCC](http://en.wikipedia.org/wiki/JavaCC) to teach translator and ...
why there's a start argument in python's built-in sum function
4,543,129
5
2010-12-28T01:43:11Z
4,543,139
13
2010-12-28T01:45:10Z
[ "python" ]
In the **sum** function, the prototype is **sum(iterable[,start])**, which sums everything in the iterable object plus the start value. I wonder why there is a start value in here? Is there nay particular use case this value is needed? Please don't give any more examples how start is used. I am wondering why it exist ...
If you are summing things that aren't integers you may need to provide a start value to avoid an error. ``` >>> from datetime import timedelta >>> timedeltas = [timedelta(1), timedelta(2)] >>> sum(timedeltas) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(...
Debugging djcelery's celeryd via pdb
4,543,967
15
2010-12-28T05:50:48Z
4,907,357
10
2011-02-05T14:27:30Z
[ "python", "django", "debugging", "celery" ]
Have anybody tried debugging celeryd worker using pdb? Whenever a breakpoint is encountered (either by running celeryd via pdb, or by `pdb.set_trace()`), I hit the following error: ``` Error while handling action event. Traceback (most recent call last): File "/home/jeeyo/workspace3/uwcr/subscriptions/tasks.py", lin...
I had the same problem. Try using celery.contrib.rdb instead: <http://docs.celeryproject.org/en/latest/tutorials/debugging.html>
How do I standardize a matrix?
4,544,292
6
2010-12-28T07:07:09Z
4,544,459
29
2010-12-28T07:41:54Z
[ "python", "algorithm", "math", "numpy" ]
Basically, take a matrix and change it so that its mean is equal to 0 and variance is 1. I'm using numpy's arrays so if it can already do it it's better, but I can implement it myself as long as I can find an algorithm. edit: nvm nimrodm has a better implementation
The following subtracts the mean of A from each element (the new mean is 0), then normalizes the result by the standard deviation. ``` from numpy import * A = (A - mean(A)) / std(A) ``` The above is for standardizing the entire matrix as a whole, If A has many dimensions and you want to standardize each column indivi...
Automatically growing lists in Python
4,544,630
9
2010-12-28T08:15:12Z
4,544,699
26
2010-12-28T08:30:27Z
[ "python", "list" ]
Is there a way to make an automatically growing list in Python? What I mean is to make a list that would grow when an index that does not yet exist is referenced. Basically the behaviour of Ruby arrays. Thanks in advance!
Sure it's possible, you just have to use a subclass of list to do it. ``` class GrowingList(list): def __setitem__(self, index, value): if index >= len(self): self.extend([None]*(index + 1 - len(self))) list.__setitem__(self, index, value) ``` Usage: ``` >>> grow = GrowingList() >>> g...
How can you get the call tree with python profilers?
4,544,784
14
2010-12-28T08:46:35Z
4,544,800
7
2010-12-28T08:49:44Z
[ "python", "tree", "profiling" ]
I used to use a nice Apple profiler that is built into the System Monitor application. As long as your C++ code was compiled with debug information, you could sample your running application and it would print out an indented tree telling you what percent of the parent function's time was spent in this function (and th...
Check out this library <http://pycallgraph.slowchop.com/> for call graphs. It works really well. If you want to profile specific functions, check out <http://mg.pov.lt/blog/profiling.html> This is a result from the profilehooks module. ![alt text](http://i.stack.imgur.com/Qz0rP.png)
How can you get the call tree with python profilers?
4,544,784
14
2010-12-28T08:46:35Z
22,693,080
7
2014-03-27T16:04:52Z
[ "python", "tree", "profiling" ]
I used to use a nice Apple profiler that is built into the System Monitor application. As long as your C++ code was compiled with debug information, you could sample your running application and it would print out an indented tree telling you what percent of the parent function's time was spent in this function (and th...
I recently wanted the same thing, so took a stab at implementing one myself. The project's on Github. <https://github.com/joerick/pyinstrument> Here's how you would use it: ``` from pyinstrument import Profiler profiler = Profiler() profiler.start() # code you want to profile profiler.stop() print(profiler.outpu...
How can you get the call tree with python profilers?
4,544,784
14
2010-12-28T08:46:35Z
23,164,271
20
2014-04-19T00:14:56Z
[ "python", "tree", "profiling" ]
I used to use a nice Apple profiler that is built into the System Monitor application. As long as your C++ code was compiled with debug information, you could sample your running application and it would print out an indented tree telling you what percent of the parent function's time was spent in this function (and th...
I just stumbled on this as well, and spent some time learning how to generate a call graph (the normal results of cProfile is not terribly informative). Future reference, here's another way to generate a beautiful call-tree graphic with cProfile + gprof2dot + graphViz. ——————— 1. Install GraphViz: <http...
Quickly determine if a number is prime in Python for numbers < 1 billion
4,545,114
6
2010-12-28T09:49:35Z
4,545,175
10
2010-12-28T10:00:05Z
[ "python", "python-3.x", "primes" ]
My current algorithm to check the primality of numbers in python is way to slow for numbers between 10 million and 1 billion. I want it to be improved knowing that I will never get numbers bigger than 1 billion. The context is that I can't get an implementation that is quick enough for solving problem 60 of project Eu...
For numbers as large as 10^9, one approach can be to generate all primes up to sqrt(10^9) and then simply check the divisibility of the input number against the numbers in that list. If a number isn't divisible by any other prime less than or equal to its square root, it must itself be a prime (it must have at least on...
UnicodeDecodeError when redirecting to file
4,545,661
77
2010-12-28T11:24:45Z
4,545,695
10
2010-12-28T11:30:24Z
[ "python", "unicode" ]
I run this snippet twice, in the Ubuntu terminal (encoding set to utf-8), once with `./test.py` and then with `./test.py >out.txt`: ``` uni = u"\u001A\u0BC3\u1451\U0001D10C" print uni ``` Without redirection it prints garbage. With redirection I get a UnicodeDecodeError. Can someone explain why I get the error only i...
Encode it while printing ``` uni = u"\u001A\u0BC3\u1451\U0001D10C" print uni.encode("utf-8") ``` This is because when you run the script manually python encodes it before outputting it to terminal, when you pipe it python does not encode it itself so you have to encode manually when doing I/O.
UnicodeDecodeError when redirecting to file
4,545,661
77
2010-12-28T11:24:45Z
4,546,129
187
2010-12-28T12:44:23Z
[ "python", "unicode" ]
I run this snippet twice, in the Ubuntu terminal (encoding set to utf-8), once with `./test.py` and then with `./test.py >out.txt`: ``` uni = u"\u001A\u0BC3\u1451\U0001D10C" print uni ``` Without redirection it prints garbage. With redirection I get a UnicodeDecodeError. Can someone explain why I get the error only i...
The whole key to such encoding problems is to understand that there are in principle **two distinct concepts of "string"**: (1) string of *characters*, and (2) string/array of *bytes*. This distinction has been mostly ignored for a long time because of the historic ubiquity of encodings with no more than 256 characters...
UnicodeDecodeError when redirecting to file
4,545,661
77
2010-12-28T11:24:45Z
4,551,045
18
2010-12-29T02:24:42Z
[ "python", "unicode" ]
I run this snippet twice, in the Ubuntu terminal (encoding set to utf-8), once with `./test.py` and then with `./test.py >out.txt`: ``` uni = u"\u001A\u0BC3\u1451\U0001D10C" print uni ``` Without redirection it prints garbage. With redirection I get a UnicodeDecodeError. Can someone explain why I get the error only i...
Python always encodes Unicode strings when writing to a terminal, file, pipe, etc. When writing to a terminal Python can usually determine the encoding of the terminal and use it correctly. When writing to a file or pipe Python defaults to the 'ascii' encoding unless explicitly told otherwise. Python can be told what t...
Python - can I detect unicode string language code?
4,545,977
9
2010-12-28T12:21:11Z
4,546,813
12
2010-12-28T14:38:35Z
[ "python", "unicode", "internationalization", "detection" ]
I'm faced with a situation where I'm reading a string of text and I need to detect the language code (en, de, fr, sp, etc). Is there a simple way to do this in python? thanks.
If you need to detect language in response to a user action then you could use [google ajax language API](http://code.google.com/apis/language/translate/v1/using_rest_langdetect.html): ``` #!/usr/bin/env python import json import urllib, urllib2 def detect_language(text, userip=None, referrer="http://stackove...
Django self-referential relationship?
4,547,101
5
2010-12-28T15:24:45Z
4,547,130
9
2010-12-28T15:30:01Z
[ "python", "django", "django-models" ]
I'm trying to create model Page, page should be able to have "child pages" too. My model code below keeps [crashing Python](http://pastie.org/private/butthk1aaeb3pmh7mmag1g) on my Mac (python 2.6.1) and Ubuntu 10.04 (python 2.6.5): ``` from django.db import models from django.contrib import admin class Page(models.M...
I suggest you use `django-mptt` which offers easier to use method of recursively spitting the structure out, example @ <http://django-mptt.github.com/django-mptt/templates.html> You have to register mptt with the model [first](http://django-mptt.github.com/django-mptt/models.html), though. Here is my code using it: [...
Django self-referential relationship?
4,547,101
5
2010-12-28T15:24:45Z
4,547,507
11
2010-12-28T16:25:25Z
[ "python", "django", "django-models" ]
I'm trying to create model Page, page should be able to have "child pages" too. My model code below keeps [crashing Python](http://pastie.org/private/butthk1aaeb3pmh7mmag1g) on my Mac (python 2.6.1) and Ubuntu 10.04 (python 2.6.5): ``` from django.db import models from django.contrib import admin class Page(models.M...
In terms of the model itself you're just thinking of this in the wrong direction. Instead of ``` children = models.ManyToManyField("self", blank=True) ``` use ``` parent = models.ForeignKey("self", blank=True, related_name="children") ``` This will let you access the children directly from a page record but should ...
Python - Default Counter Variable in For loop
4,547,256
3
2010-12-28T15:49:45Z
4,547,270
13
2010-12-28T15:51:43Z
[ "python" ]
Is there any default Counter Variable in For loop?
No, you give it a name: `for i in range(10): ...` If you want to iterate over elements of a collection in such a way that you get both the element and its index, the Pythonic way to do it is `for i,v in enumerate(l): print i,v` (where `l` is a list or any other object implementing the sequence protocol.)